From 0fc19a01cca7d67ccadfb059403c8172e72c8f5a Mon Sep 17 00:00:00 2001 From: Arturo Volpe Date: Tue, 29 Nov 2022 20:15:02 -0300 Subject: [PATCH 01/12] feat: Migrate to hibernate 6 This commit is big because: * The package javax.persistence is removed, the new package jakarta.persistence is used everywhere. * Hibernate 6 removes it custom criteria builder api, so we need to migrate everything to jpa criteria query. Signed-off-by: Arturo Volpe --- libraries.gradle | 13 +- modules/dbsupport/build.gradle | 3 +- .../src/main/java/org/jpos/ee/DB.java | 4 +- .../src/main/java/org/jpos/ee/DBFilter.java | 6 +- .../src/main/java/org/jpos/ee/DBManager.java | 19 +- .../ee/converter/ObjectNodeConverter.java | 7 +- .../org/jpos/ee/converter/TagsConverter.java | 6 +- .../java/org/jpos/ee/usertype/JsonType.java | 15 +- .../java/org/jpos/ee/usertype/JsonbType.java | 12 +- .../java/org/jpos/ee/usertype/TagsType.java | 15 +- .../java/org/jpos/ee/ConsumerManager.java | 21 +- .../src/main/java/org/jpos/ee/Realm.java | 20 +- .../java/org/jpos/ee/RevisionManager.java | 89 ++-- .../main/java/org/jpos/ee/UserManager.java | 87 ++-- .../src/main/java/org/jpos/gl/GLSession.java | 464 +++++++++++------- .../main/java/org/jpos/gl/tools/Export.java | 31 +- .../main/java/org/jpos/gl/tools/Import.java | 16 +- .../java/org/jpos/gl/AddExportUserTest.java | 4 +- .../org/jpos/qi/minigl/AccountManager.java | 41 +- .../jpos/qi/minigl/GLTransactionManager.java | 4 +- .../java/org/jpos/qi/minigl/LayersHelper.java | 6 +- .../jpos/qi/sysconfig/SysConfigHelper.java | 6 +- .../java/org/jpos/ee/ResultCodeFinder.java | 26 +- .../java/org/jpos/ee/ResultCodeManager.java | 26 +- .../src/main/java/org/jpos/ee/SeqNo.java | 10 +- .../main/java/org/jpos/ee/SeqNoManager.java | 2 +- .../org/jpos/ee/status/StatusManager.java | 29 +- .../src/main/java/org/jpos/ee/SysConfig.java | 8 +- .../java/org/jpos/ee/SysConfigManager.java | 7 +- .../main/java/org/jpos/ee/ThingsManager.java | 320 ++++++------ .../java/org/jpos/transaction/DebugDB.java | 4 +- subprojects.gradle | 4 +- 32 files changed, 710 insertions(+), 615 deletions(-) diff --git a/libraries.gradle b/libraries.gradle index b11998f2a4..c22fdcecfb 100644 --- a/libraries.gradle +++ b/libraries.gradle @@ -2,7 +2,7 @@ ext { jposVersion = '2.1.8-SNAPSHOT' slf4jVersion = '1.7.28' logbackVersion = '1.2.8' - hibernateVersion = '5.6.11.Final' + hibernateVersion = '6.1.5.Final' geronimoVersion = '1.1.1' jettyVersion = '9.4.44.v20210927' servletApiVersion = '4.0.1' @@ -27,6 +27,7 @@ ext { orgjsonVersion = '20200518' postgresqlEmbeddedVersion = '1.2.8' postgresqlBinVersion = '12.3.0' + dom4jVersion = '2.1.3' libraries = [ //jUnit (Tests) @@ -56,9 +57,10 @@ ext { joda_time: 'joda-time:joda-time:2.10.12', //Hibernate - hibernate_core: "org.hibernate:hibernate-core:${hibernateVersion}", - hibernate_envers: "org.hibernate:hibernate-envers:${hibernateVersion}", - hibernate_c3p0: "org.hibernate:hibernate-c3p0:${hibernateVersion}", + hibernate_core: "org.hibernate.orm:hibernate-core:${hibernateVersion}", + hibernate_envers: "org.hibernate.orm:hibernate-envers:${hibernateVersion}", + hibernate_c3p0: "org.hibernate.orm:hibernate-c3p0:${hibernateVersion}", + hibernate_ant: "org.hibernate.orm:hibernate-ant:${hibernateVersion}", c3p0: "com.mchange:c3p0:${c3p0Version}", hibernate_ehcache: "org.hibernate:hibernate-ehcache:${hibernateVersion}", jta: "org.apache.geronimo.specs:geronimo-jta_1.1_spec:${geronimoVersion}", @@ -132,7 +134,8 @@ ext { liquibase: "org.liquibase:liquibase-core:${liquibaseVersion}", elk: "org.elasticsearch.client:elasticsearch-rest-high-level-client:${elkVersion}", - orgJson: "org.json:json:${orgjsonVersion}" + orgJson: "org.json:json:${orgjsonVersion}", + dom4j: "org.dom4j:dom4j:${dom4jVersion}" ] jsonSchemaValidatorLibs = [ diff --git a/modules/dbsupport/build.gradle b/modules/dbsupport/build.gradle index 007326358e..95b122b795 100644 --- a/modules/dbsupport/build.gradle +++ b/modules/dbsupport/build.gradle @@ -5,9 +5,10 @@ dependencies { api libraries.hibernate_core api libraries.hibernate_envers api libraries.hibernate_c3p0 + api libraries.hibernate_ant api libraries.c3p0 // force c3p0 version (temporary fix un Hibernate bumps up version) - api libraries.hibernate_ehcache api libraries.jta + api libraries.dom4j api libraries.jacksonDatabind } diff --git a/modules/dbsupport/src/main/java/org/jpos/ee/DB.java b/modules/dbsupport/src/main/java/org/jpos/ee/DB.java index 8d70e96edf..3f07274200 100644 --- a/modules/dbsupport/src/main/java/org/jpos/ee/DB.java +++ b/modules/dbsupport/src/main/java/org/jpos/ee/DB.java @@ -494,13 +494,13 @@ public void printStats() info.addMessage("==== STATISTICS ===="); SessionStatistics statistics = session().getStatistics(); info.addMessage("==== ENTITIES ===="); - Set entityKeys = statistics.getEntityKeys(); + Set entityKeys = (Set) statistics.getEntityKeys(); for (EntityKey ek : entityKeys) { info.addMessage(String.format("[%s] %s", ek.getIdentifier(), ek.getEntityName())); } info.addMessage("==== COLLECTIONS ===="); - Set collectionKeys = statistics.getCollectionKeys(); + Set collectionKeys = (Set) statistics.getCollectionKeys(); for (CollectionKey ck : collectionKeys) { info.addMessage(String.format("[%s] %s", ck.getKey(), ck.getRole())); diff --git a/modules/dbsupport/src/main/java/org/jpos/ee/DBFilter.java b/modules/dbsupport/src/main/java/org/jpos/ee/DBFilter.java index 7e844d1702..c49c229470 100644 --- a/modules/dbsupport/src/main/java/org/jpos/ee/DBFilter.java +++ b/modules/dbsupport/src/main/java/org/jpos/ee/DBFilter.java @@ -19,9 +19,9 @@ package org.jpos.ee; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; /** * Functional interface to create predicates for querying {@link DBManager} diff --git a/modules/dbsupport/src/main/java/org/jpos/ee/DBManager.java b/modules/dbsupport/src/main/java/org/jpos/ee/DBManager.java index ee69569f75..755a0d7c25 100644 --- a/modules/dbsupport/src/main/java/org/jpos/ee/DBManager.java +++ b/modules/dbsupport/src/main/java/org/jpos/ee/DBManager.java @@ -18,11 +18,10 @@ package org.jpos.ee; -import org.hibernate.query.criteria.internal.OrderImpl; - -import javax.persistence.NoResultException; -import javax.persistence.criteria.*; +import jakarta.persistence.NoResultException; +import jakarta.persistence.criteria.*; import org.hibernate.query.Query; + import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -62,8 +61,10 @@ public List getAll(int offset, int limit, Map orders) { //ORDERS if (orders != null) { for (Map.Entry entry : orders.entrySet()) { - OrderImpl order = new OrderImpl(root.get(entry.getKey()), entry.getValue()); - orderList.add(order); + if (entry.getValue() == null || entry.getValue()) + orderList.add(criteriaBuilder.asc(root.get(entry.getKey()))); + else + orderList.add(criteriaBuilder.desc(root.get(entry.getKey()))); } } Predicate[] predicates = buildFilters(root); @@ -75,10 +76,9 @@ public List getAll(int offset, int limit, Map orders) { if (limit != -1) { queryImp.setMaxResults(limit); } - List list = queryImp + return queryImp .setFirstResult(offset) .getResultList(); - return list; } public List getAll() { @@ -115,10 +115,9 @@ public List getItemsByParam(int offset, int limit, String param, Object value if (limit != -1) { queryImp.setMaxResults(limit); } - List list = queryImp + return queryImp .setFirstResult(offset) .getResultList(); - return list; } catch (NoResultException nre) { return null; } diff --git a/modules/dbsupport/src/main/java/org/jpos/ee/converter/ObjectNodeConverter.java b/modules/dbsupport/src/main/java/org/jpos/ee/converter/ObjectNodeConverter.java index f4f66fb707..c34011d175 100644 --- a/modules/dbsupport/src/main/java/org/jpos/ee/converter/ObjectNodeConverter.java +++ b/modules/dbsupport/src/main/java/org/jpos/ee/converter/ObjectNodeConverter.java @@ -20,12 +20,13 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; -import javax.persistence.AttributeConverter; -import javax.persistence.Converter; +import jakarta.persistence.AttributeConverter; +import jakarta.persistence.Converter; + import java.io.IOException; @Converter(autoApply = true) -public class ObjectNodeConverter implements AttributeConverter { +public class ObjectNodeConverter implements AttributeConverter { @Override public String convertToDatabaseColumn(ObjectNode attribute) { diff --git a/modules/dbsupport/src/main/java/org/jpos/ee/converter/TagsConverter.java b/modules/dbsupport/src/main/java/org/jpos/ee/converter/TagsConverter.java index 5c39a4f948..610e23336a 100644 --- a/modules/dbsupport/src/main/java/org/jpos/ee/converter/TagsConverter.java +++ b/modules/dbsupport/src/main/java/org/jpos/ee/converter/TagsConverter.java @@ -18,12 +18,12 @@ package org.jpos.ee.converter; +import jakarta.persistence.AttributeConverter; +import jakarta.persistence.Converter; import org.jpos.util.Tags; -import javax.persistence.AttributeConverter; -import javax.persistence.Converter; @Converter(autoApply = true) -public class TagsConverter implements AttributeConverter { +public class TagsConverter implements AttributeConverter { @Override public String convertToDatabaseColumn(Tags tags) { return tags != null && tags.size() > 0 ? tags.toString() : ""; diff --git a/modules/dbsupport/src/main/java/org/jpos/ee/usertype/JsonType.java b/modules/dbsupport/src/main/java/org/jpos/ee/usertype/JsonType.java index 78c1f1267a..900d780730 100644 --- a/modules/dbsupport/src/main/java/org/jpos/ee/usertype/JsonType.java +++ b/modules/dbsupport/src/main/java/org/jpos/ee/usertype/JsonType.java @@ -25,7 +25,6 @@ import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.node.ObjectNode; import org.hibernate.HibernateException; -import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.usertype.UserType; @@ -37,8 +36,7 @@ import java.sql.Types; import java.text.SimpleDateFormat; -public class JsonType implements UserType { - private static int[] TYPES = { Types.VARCHAR }; +public class JsonType implements UserType { private static ObjectMapper mapper = new ObjectMapper() @@ -51,8 +49,8 @@ public class JsonType implements UserType { .setSerializationInclusion(JsonInclude.Include.NON_NULL); @Override - public int[] sqlTypes() { - return TYPES; + public int getSqlType() { + return Types.VARCHAR; } @Override @@ -70,20 +68,21 @@ public int hashCode(Object x) throws HibernateException { return x.hashCode(); } + /** * Retrieve an instance of the mapped class from a JDBC resultset. Implementors * should handle possibility of null values. * * @param rs a JDBC result set - * @param names the column names + * @param position the column position * @param session * @param owner the containing entity @return Object * @throws HibernateException * @throws SQLException */ @Override - public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException { - String json = rs.getString(names[0]); + public Object nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException { + String json = rs.getString(position); if (rs.wasNull()) return null; try { diff --git a/modules/dbsupport/src/main/java/org/jpos/ee/usertype/JsonbType.java b/modules/dbsupport/src/main/java/org/jpos/ee/usertype/JsonbType.java index 1594403d3b..8cb06e34f8 100644 --- a/modules/dbsupport/src/main/java/org/jpos/ee/usertype/JsonbType.java +++ b/modules/dbsupport/src/main/java/org/jpos/ee/usertype/JsonbType.java @@ -43,7 +43,7 @@ * * @author avolpe@fintech.works */ -public class JsonbType implements UserType { +public class JsonbType implements UserType { private static ObjectMapper mapper = new ObjectMapper() @@ -56,12 +56,12 @@ public class JsonbType implements UserType { .setSerializationInclusion(JsonInclude.Include.NON_NULL); @Override - public int[] sqlTypes() { - return new int[]{Types.JAVA_OBJECT}; + public int getSqlType() { + return Types.OTHER; } @Override - public Class returnedClass() { + public Class returnedClass() { return ObjectNode.class; } @@ -87,10 +87,10 @@ public int hashCode(final Object x) { @Override public Object nullSafeGet(ResultSet rs, - String[] names, + int position, SharedSessionContractImplementor session, Object owner) throws SQLException { - final String json = rs.getString(names[0]); + final String json = rs.getString(position); if (json == null) { return null; } diff --git a/modules/dbsupport/src/main/java/org/jpos/ee/usertype/TagsType.java b/modules/dbsupport/src/main/java/org/jpos/ee/usertype/TagsType.java index 654eed3d70..7f771833b2 100644 --- a/modules/dbsupport/src/main/java/org/jpos/ee/usertype/TagsType.java +++ b/modules/dbsupport/src/main/java/org/jpos/ee/usertype/TagsType.java @@ -19,9 +19,9 @@ package org.jpos.ee.usertype; import org.hibernate.HibernateException; -import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.usertype.UserType; +import org.jpos.util.Tags; import java.io.Serializable; import java.sql.PreparedStatement; @@ -29,14 +29,11 @@ import java.sql.SQLException; import java.sql.Types; -import org.jpos.util.Tags; - public class TagsType implements UserType { - private static int[] TYPES = { Types.VARCHAR }; @Override - public int[] sqlTypes() { - return TYPES; + public int getSqlType() { + return Types.VARCHAR; } @Override @@ -59,15 +56,15 @@ public int hashCode(Object o) throws HibernateException { * should handle possibility of null values. * * @param rs a JDBC result set - * @param names the column names + * @param position the column position * @param session * @param owner the containing entity @return Object * @throws HibernateException * @throws SQLException */ @Override - public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException { - String tags = rs.getString(names[0]); + public Object nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException { + String tags = rs.getString(position); if (rs.wasNull()) return null; return new Tags(tags); diff --git a/modules/eeuser/src/main/java/org/jpos/ee/ConsumerManager.java b/modules/eeuser/src/main/java/org/jpos/ee/ConsumerManager.java index c65a14169e..136c2c269e 100644 --- a/modules/eeuser/src/main/java/org/jpos/ee/ConsumerManager.java +++ b/modules/eeuser/src/main/java/org/jpos/ee/ConsumerManager.java @@ -18,31 +18,30 @@ package org.jpos.ee; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; import org.hibernate.HibernateException; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; -import java.util.*; +import java.util.List; @SuppressWarnings("unused") public class ConsumerManager extends DBManager { private User user; - public ConsumerManager (DB db) { - super(db,Consumer.class); + public ConsumerManager(DB db) { + super(db, Consumer.class); } public ConsumerManager(DB db, User user) { - super(db,Consumer.class); + super(db, Consumer.class); this.user = user; } - public Consumer getById (String id) throws HibernateException - { + public Consumer getById(String id) throws HibernateException { return getItemByParam("id", id, true); } - public List getConsumers (User user) { + public List getConsumers(User user) { this.user = user; List consumers = getAll(); this.user = null; @@ -52,8 +51,8 @@ public List getConsumers (User user) { protected Predicate[] buildFilters(Root root) { Predicate notDeleted = db.session.getCriteriaBuilder().isFalse(root.get("deleted")); if (user != null) { - Predicate p = db.session().getCriteriaBuilder().equal(root.get("user"),user.getId()); - return new Predicate[]{notDeleted,p}; + Predicate p = db.session().getCriteriaBuilder().equal(root.get("user"), user.getId()); + return new Predicate[]{notDeleted, p}; } return new Predicate[]{notDeleted}; } diff --git a/modules/eeuser/src/main/java/org/jpos/ee/Realm.java b/modules/eeuser/src/main/java/org/jpos/ee/Realm.java index 74b4681eac..04ac2c2fec 100644 --- a/modules/eeuser/src/main/java/org/jpos/ee/Realm.java +++ b/modules/eeuser/src/main/java/org/jpos/ee/Realm.java @@ -18,14 +18,14 @@ package org.jpos.ee; +import jakarta.persistence.*; import org.hibernate.annotations.CacheConcurrencyStrategy; -import javax.persistence.*; import java.io.Serializable; import java.util.Objects; @Entity -@Table(name = "realm", uniqueConstraints={@UniqueConstraint(columnNames={"name"}, name="UK_realm_name")}) +@Table(name = "realm", uniqueConstraints = {@UniqueConstraint(columnNames = {"name"}, name = "UK_realm_name")}) @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class Realm extends Cloneable implements Serializable { private static final long serialVersionUID = -5382324365781372973L; @@ -34,10 +34,10 @@ public class Realm extends Cloneable implements Serializable { @Column(name = "id", updatable = false, nullable = false) private Long id; - @Column(length=64) + @Column(length = 64) private String name; - @Column(length=8000) + @Column(length = 8000) private String description; public Long getId() { @@ -82,10 +82,10 @@ public Realm(String name, String description) { @Override public String toString() { return "Realm{" + - "id=" + id + - ", name='" + name + '\'' + - ", description='" + description + '\'' + - '}'; + "id=" + id + + ", name='" + name + '\'' + + ", description='" + description + '\'' + + '}'; } @Override @@ -94,8 +94,8 @@ public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) return false; Realm realm = (Realm) o; return Objects.equals(id, realm.id) && - Objects.equals(name, realm.name) && - Objects.equals(description, realm.description); + Objects.equals(name, realm.name) && + Objects.equals(description, realm.description); } @Override diff --git a/modules/eeuser/src/main/java/org/jpos/ee/RevisionManager.java b/modules/eeuser/src/main/java/org/jpos/ee/RevisionManager.java index 86b7fd14fb..7e86fd99a6 100644 --- a/modules/eeuser/src/main/java/org/jpos/ee/RevisionManager.java +++ b/modules/eeuser/src/main/java/org/jpos/ee/RevisionManager.java @@ -18,59 +18,65 @@ package org.jpos.ee; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; +import org.hibernate.HibernateException; + import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; -import org.hibernate.Criteria; -import org.hibernate.HibernateException; -import org.hibernate.criterion.Order; -import org.hibernate.criterion.Restrictions; -import org.hibernate.query.criteria.internal.OrderImpl; - -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; - @SuppressWarnings("unused") public class RevisionManager extends DBManager { - public RevisionManager (DB db) { - super(db,Revision.class); + public RevisionManager(DB db) { + super(db, Revision.class); } - @SuppressWarnings("unchecked") - public List getRevisionsByRef (String ref) - throws HibernateException - { - Criteria crit = db.session().createCriteria (Revision.class) - .add (Restrictions.eq ("ref", ref)) - .addOrder (Order.desc("id")); - return (List) crit.list(); + + public List getRevisionsByRef(String ref) throws HibernateException { + CriteriaBuilder criteriaBuilder = db.session().getCriteriaBuilder(); + CriteriaQuery query = criteriaBuilder.createQuery(Revision.class); + Root root = query.from(Revision.class); + + query = query + .where(criteriaBuilder.equal(root.get("ref"), ref)) + .orderBy(criteriaBuilder.desc(root.get("id"))) + .select(root); + + return db.session.createQuery(query).getResultList(); } - @SuppressWarnings("unchecked") - public List getRevisionsByAuthor (User author) - throws HibernateException - { - Criteria crit = db.session().createCriteria (Revision.class) - .add (Restrictions.eq ("author", author)) - .addOrder (Order.desc("id")); - return (List) crit.list(); + + public List getRevisionsByAuthor(User author) + throws HibernateException { + CriteriaBuilder criteriaBuilder = db.session().getCriteriaBuilder(); + CriteriaQuery query = criteriaBuilder.createQuery(Revision.class); + Root root = query.from(Revision.class); + + query = query + .where(criteriaBuilder.equal(root.get("author"), author)) + .orderBy(criteriaBuilder.desc(root.get("id"))) + .select(root); + + return db.session.createQuery(query).getResultList(); } //overridden to avoid LazyInitializationExc @Override - public List getAll(int offset, int limit, Map orders) { + public List getAll(int offset, int limit, Map orders) { CriteriaBuilder criteriaBuilder = db.session().getCriteriaBuilder(); CriteriaQuery query = criteriaBuilder.createQuery(Revision.class); Root root = query.from(Revision.class); // To avoid LazyInitializationExc root.fetch("author"); - List orderList = new ArrayList<>(); + List orderList = new ArrayList<>(); //ORDERS - for (Map.Entry entry : orders.entrySet()) { - OrderImpl order = new OrderImpl(root.get(entry.getKey()),entry.getValue()); - orderList.add(order); + for (Map.Entry entry : orders.entrySet()) { + if (entry.getValue() == null || entry.getValue()) + orderList.add(criteriaBuilder.asc(root.get(entry.getKey()))); + else + orderList.add(criteriaBuilder.desc(root.get(entry.getKey()))); } query.select(root); query.orderBy(orderList); @@ -81,22 +87,21 @@ public List getAll(int offset, int limit, Map orders) } - /** * factory method used to create a Revision associated with this user. * * @param author the revision author - * @param ref associated with this revision - * @param info information + * @param ref associated with this revision + * @param info information * @return a revision entry */ - public Revision createRevision (User author, String ref, String info) { + public Revision createRevision(User author, String ref, String info) { Revision re = new Revision(); - re.setDate (new Date()); - re.setInfo (info); - re.setRef (ref); - re.setAuthor (author); - db.save (re); + re.setDate(new Date()); + re.setInfo(info); + re.setRef(ref); + re.setAuthor(author); + db.save(re); return re; } } diff --git a/modules/eeuser/src/main/java/org/jpos/ee/UserManager.java b/modules/eeuser/src/main/java/org/jpos/ee/UserManager.java index 333a4307c0..9c6d6b71c3 100644 --- a/modules/eeuser/src/main/java/org/jpos/ee/UserManager.java +++ b/modules/eeuser/src/main/java/org/jpos/ee/UserManager.java @@ -18,13 +18,12 @@ package org.jpos.ee; -import java.util.Date; -import java.util.List; - -import org.bouncycastle.util.encoders.Base64; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; import org.hibernate.HibernateException; -import javax.persistence.criteria.*; +import java.util.Date; +import java.util.List; /** * @author Alejandro Revilla @@ -32,32 +31,32 @@ public class UserManager extends DBManager { private HashVersion version; - public UserManager (DB db) { - this (db, HashVersion.ONE); + public UserManager(DB db) { + this(db, HashVersion.ONE); } - public UserManager (DB db, HashVersion version) { - super (db, User.class); + public UserManager(DB db, HashVersion version) { + super(db, User.class); this.version = version; } - public void setPassword (User u, String clearpass) throws Exception { + public void setPassword(User u, String clearpass) throws Exception { setPassword(u, clearpass, null, version); } - public void setPassword (User u, String clearpass, User author) throws Exception { + public void setPassword(User u, String clearpass, User author) throws Exception { setPassword(u, clearpass, author, version); } - public void setPassword (User u, String clearpass, User author, HashVersion v) throws Exception { + public void setPassword(User u, String clearpass, User author, HashVersion v) throws Exception { if (u.getPasswordHash() != null) u.addPasswordHistoryValue(u.getPasswordHash()); switch (v) { case ZERO: - setV0Password (u, clearpass); + setV0Password(u, clearpass); break; case ONE: - setV1Password (u, clearpass); + setV1Password(u, clearpass); break; } u.setPasswordChanged(new Date()); @@ -73,52 +72,51 @@ public void setPassword (User u, String clearpass, User author, HashVersion v) t * @return all users * @throws HibernateException on low level hibernate related exception */ - public List findAll () throws HibernateException { + public List findAll() throws HibernateException { return super.getAll(); } @Override protected Predicate[] buildFilters(Root root) { - return new Predicate[] { + return new Predicate[]{ db.session().getCriteriaBuilder().isFalse(root.get("deleted")) }; } - public User getUserByNick (String nick) - throws HibernateException - { + public User getUserByNick(String nick) + throws HibernateException { return getUserByNick(nick, false); } - public User getUserByNick (String nick, boolean includeDeleted) - throws HibernateException - { - return getItemByParam("nick",nick,!includeDeleted); + + public User getUserByNick(String nick, boolean includeDeleted) + throws HibernateException { + return getItemByParam("nick", nick, !includeDeleted); } /** * @param nick name. * @param pass hash * @return the user - * @throws BLException if invalid user/pass + * @throws BLException if invalid user/pass * @throws HibernateException on low level hibernate related exception */ - public User getUserByNick (String nick, String pass) throws Exception { + public User getUserByNick(String nick, String pass) throws Exception { User u = getUserByNick(nick); - assertNotNull (u, "User does not exist"); + assertNotNull(u, "User does not exist"); assertTrue(checkPassword(u, pass), "Invalid password"); return u; } public User getUserById(long id, boolean includeDeleted) throws HibernateException { - return getItemByParam("id",id,!includeDeleted); + return getItemByParam("id", id, !includeDeleted); } public User getUserById(long id) throws HibernateException { - return getUserById(id,false); + return getUserById(id, false); } - public boolean checkPassword (User u, String clearpass) throws Exception { + public boolean checkPassword(User u, String clearpass) throws Exception { assertNotNull(clearpass, "Invalid pass"); String passwordHash = u.getPasswordHash(); assertNotNull(passwordHash, "Password is null"); @@ -134,12 +132,12 @@ public boolean checkPassword (User u, String clearpass) throws Exception { } /** - * @param u the user + * @param u the user * @param clearpass new password in clear * @return true if password is in PasswordHistory */ - public boolean checkNewPassword (User u, String clearpass) throws Exception { - if (checkPassword (u, clearpass)) { + public boolean checkNewPassword(User u, String clearpass) throws Exception { + if (checkPassword(u, clearpass)) { return false; // same password not allowed } for (PasswordHistory p : u.getPasswordhistory()) { @@ -149,15 +147,14 @@ public boolean checkNewPassword (User u, String clearpass) throws Exception { if (checkV0Password(p.getValue(), u.getId(), clearpass)) return false; case ONE: - if (checkV1Password (p.getValue(), clearpass)) + if (checkV1Password(p.getValue(), clearpass)) return false; } } return true; } - public boolean upgradePassword (User u, String clearpass) throws Exception - { + public boolean upgradePassword(User u, String clearpass) throws Exception { assertNotNull(clearpass, "Invalid pass"); String passwordHash = u.getPasswordHash(); assertNotNull(passwordHash, "Password is null"); @@ -177,12 +174,12 @@ public void setVersion(HashVersion version) { this.version = version; } - private void setV1Password (User u, String clearpass) throws Exception { + private void setV1Password(User u, String clearpass) throws Exception { assertNotNull(clearpass, "Invalid password"); - u.setPasswordHash(HashVersion.ONE.hash(Long.toString(u.getId(),16), clearpass, HashVersion.ONE.getSalt())); + u.setPasswordHash(HashVersion.ONE.hash(Long.toString(u.getId(), 16), clearpass, HashVersion.ONE.getSalt())); } - private boolean checkV1Password (String passwordHash, String clearpass) throws Exception { + private boolean checkV1Password(String passwordHash, String clearpass) throws Exception { return HashVersion.ONE.check("", clearpass, passwordHash); } @@ -191,18 +188,18 @@ private boolean checkV0Password(String passwordHash, long id, String clearpass) } // HELPER METHODS - protected void assertNotNull (Object obj, String error) throws BLException { + protected void assertNotNull(Object obj, String error) throws BLException { if (obj == null) - throw new BLException (error); + throw new BLException(error); } - protected void assertTrue (boolean condition, String error) - throws BLException - { + + protected void assertTrue(boolean condition, String error) + throws BLException { if (!condition) - throw new BLException (error); + throw new BLException(error); } - private void setV0Password (User u, String clearpass) throws Exception { + private void setV0Password(User u, String clearpass) throws Exception { assertNotNull(clearpass, "Invalid password"); u.setPasswordHash(HashVersion.ZERO.hash(Long.toString(u.getId()), clearpass, null)); } diff --git a/modules/minigl/src/main/java/org/jpos/gl/GLSession.java b/modules/minigl/src/main/java/org/jpos/gl/GLSession.java index 62b267f7c9..db1af32fc3 100644 --- a/modules/minigl/src/main/java/org/jpos/gl/GLSession.java +++ b/modules/minigl/src/main/java/org/jpos/gl/GLSession.java @@ -18,23 +18,18 @@ package org.jpos.gl; -import java.math.BigInteger; -import java.util.*; -import java.math.BigDecimal; -import java.util.concurrent.DelayQueue; - +import com.sun.jdi.LongType; +import jakarta.persistence.criteria.*; import org.hibernate.*; -import org.hibernate.criterion.Order; -import org.hibernate.criterion.Projections; -import org.hibernate.criterion.Restrictions; -import org.hibernate.criterion.Disjunction; import org.hibernate.exception.ConstraintViolationException; +import org.hibernate.query.Query; import org.hibernate.transform.AliasToEntityMapResultTransformer; -import org.hibernate.type.LongType; - - import org.jpos.ee.DB; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.*; + /** * MiniGL facility entry point. * @@ -265,12 +260,12 @@ public Account getChart (String code) throws HibernateException, GLException { checkPermission (GLPermission.READ); - Query q = session.createQuery ( - "from acct in class org.jpos.gl.CompositeAccount where code=:code and parent is null" + Query q = session.createQuery ( + "from acct in class org.jpos.gl.CompositeAccount where code=:code and parent is null", Account.class ); q.setParameter ("code", code); - Iterator iter = q.list().iterator(); - return (Account) (iter.hasNext() ? iter.next() : null); + Iterator iter = q.list().iterator(); + return iter.hasNext() ? iter.next() : null; } /** * @return List of charts of accounts. @@ -282,10 +277,9 @@ public List getCharts () throws HibernateException, GLException { checkPermission (GLPermission.READ); - Query q = session.createQuery( - "from acct in class org.jpos.gl.CompositeAccount where parent is null" - ); - return q.list(); + return session.createQuery( + "from acct in class org.jpos.gl.CompositeAccount where parent is null", Account.class + ).getResultList(); } /** @@ -304,7 +298,7 @@ public Account getAccount (Account chart, String code) Query q = session.createQuery ( "from acct in class org.jpos.gl.Account where root=:chart and code=:code" ); - q.setLong ("chart", chart.getId()); + q.setParameter ("chart", chart.getId()); q.setParameter ("code", code); Iterator iter = q.list().iterator(); return (Account) (iter.hasNext() ? iter.next() : null); @@ -418,7 +412,7 @@ public FinalAccount getFinalAccount (Account chart, String code) Query q = session.createQuery ( "from acct in class org.jpos.gl.FinalAccount where root=:chart and code=:code" ); - q.setLong ("chart", chart.getId()); + q.setParameter ("chart", chart.getId()); q.setParameter ("code", code); Iterator iter = q.list().iterator(); return (FinalAccount) (iter.hasNext() ? iter.next() : null); @@ -437,7 +431,7 @@ public List getFinalAccounts (Account chart) Query q = session.createQuery ( "from acct in class org.jpos.gl.FinalAccount where root=:chart" ); - q.setLong ("chart", chart.getId()); + q.setParameter ("chart", chart.getId()); return (List) q.list(); } /** @@ -484,7 +478,7 @@ public List getAllAccounts (Account chart) Query q = session.createQuery ( "from acct in class org.jpos.gl.Account where root=:chart" ); - q.setLong ("chart", chart.getId()); + q.setParameter ("chart", chart.getId()); return (List) q.list(); } @@ -504,7 +498,7 @@ public CompositeAccount getCompositeAccount (Account chart, String code) Query q = session.createQuery ( "from acct in class org.jpos.gl.CompositeAccount where root=:chart and code=:code" ); - q.setLong ("chart", chart.getId()); + q.setParameter ("chart", chart.getId()); q.setParameter ("code", code); Iterator iter = q.list().iterator(); return (CompositeAccount) (iter.hasNext() ? iter.next() : null); @@ -604,10 +598,14 @@ public List getAllJournals () * @see org.jpos.gl.Currency */ public List getCurrencyCodes() { - return db.session() - .createCriteria(Currency.class) - .setProjection(Projections.id()) - .list(); + CriteriaBuilder criteriaBuilder = db.session().getCriteriaBuilder(); + CriteriaQuery query = criteriaBuilder.createQuery(String.class); + Root root = query.from(Currency.class); + + query = query + .select(root.get("id")); + + return db.session().createQuery(query).getResultList(); } /** @@ -749,7 +747,7 @@ public GLTransaction getTransaction (Journal journal, long id) * @return list of transactions * @throws GLException if user doesn't have READ permission on this journal. */ - public Criteria createFindTransactionsCriteria + public Query createFindTransactionsCriteria (Journal journal, Date start, Date end, String searchString, boolean findByPostDate, int pageNumber, int pageSize) throws HibernateException, GLException @@ -774,7 +772,7 @@ public GLTransaction getTransaction (Journal journal, long id) * @return list of transactions * @throws GLException if user doesn't have READ permission on this journal. */ - public Criteria createFindTransactionsCriteriaByRange + public Query createFindTransactionsCriteriaByRange (Journal journal, Date start, Date end, String searchString, boolean findByPostDate, int firstResult, int pageSize) throws HibernateException, GLException @@ -787,25 +785,36 @@ public GLTransaction getTransaction (Journal journal, long id) if (end != null) end = Util.ceil (end); } - Criteria crit = session.createCriteria (GLTransaction.class) - .add (Restrictions.eq ("journal", journal)); + + CriteriaBuilder criteriaBuilder = db.session().getCriteriaBuilder(); + CriteriaQuery query = criteriaBuilder.createQuery(GLTransaction.class); + Root root = query.from(GLTransaction.class); + + List restrictions = new ArrayList<>(); + + restrictions.add(criteriaBuilder.equal(root.get("journal"), journal)); if (start != null && start.equals (end)) - crit.add (Restrictions.eq (dateField, start)); + restrictions.add(criteriaBuilder.equal(root.get(dateField), start)); else { if (start != null) - crit.add (Restrictions.ge (dateField, start)); + restrictions.add(criteriaBuilder.greaterThanOrEqualTo(root.get(dateField), start)); if (end != null) - crit.add (Restrictions.le (dateField, end)); + restrictions.add(criteriaBuilder.lessThanOrEqualTo(root.get(dateField), start)); } if (searchString != null) - crit.add (Restrictions.like ("detail", "%" + searchString + "%")); + restrictions.add(criteriaBuilder.like(root.get("detail"), "%" + searchString + "%")); + query = query.where(restrictions.toArray(new Predicate[] {})); + + Query toRet = db.session() + .createQuery(query); if (pageSize > 0 && firstResult > 0) { - crit.setMaxResults (pageSize); - crit.setFirstResult (firstResult); + + toRet = toRet.setFirstResult(firstResult) + .setMaxResults(pageSize); } - return crit; + return toRet; } /** @@ -819,13 +828,13 @@ public GLTransaction getTransaction (Journal journal, long id) * @return list of transactions * @throws GLException if user doesn't have READ permission on this journal. */ - public List findTransactions + public List findTransactions (Journal journal, Date start, Date end, String searchString, boolean findByPostDate, int pageNumber, int pageSize) throws HibernateException, GLException { - return createFindTransactionsCriteria - (journal, start, end, searchString, findByPostDate, pageNumber, pageSize).list(); + return createFindTransactionsCriteria(journal, start, end, searchString, findByPostDate, pageNumber, pageSize) + .getResultList(); } /** @@ -853,37 +862,45 @@ public GLTransaction getTransaction (Journal journal, long id) * @return list of transactions' ids * @throws GLException if user doesn't have READ permission on this journal. */ - public List findTransactionsIds + public List findTransactionsIds (Journal journal, Date start, Date end, String searchString, boolean findByPostDate, int pageNumber, int pageSize) - throws HibernateException, GLException - { - checkPermission (GLPermission.READ, journal); + throws HibernateException, GLException { + checkPermission(GLPermission.READ, journal); String dateField = findByPostDate ? "postDate" : "timestamp"; if (findByPostDate) { if (start != null) - start = Util.floor (start); + start = Util.floor(start); if (end != null) - end = Util.ceil (end); + end = Util.ceil(end); } - Criteria crit = session.createCriteria (GLTransaction.class) - .add (Restrictions.eq ("journal", journal)); - crit.setProjection(Projections.id()); - if (start != null && start.equals (end)) - crit.add (Restrictions.eq (dateField, start)); - else { + + CriteriaBuilder criteriaBuilder = db.session().getCriteriaBuilder(); + CriteriaQuery query = criteriaBuilder.createQuery(Long.class); + Root root = query.from(GLTransaction.class); + + List predicates = new ArrayList<>(); + predicates.add(criteriaBuilder.equal(root.get("journal"), journal)); + + if (start != null && start.equals(end)) + predicates.add(criteriaBuilder.equal(root.get(dateField), start)); + else{ if (start != null) - crit.add (Restrictions.ge (dateField, start)); + predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get(dateField), start)); if (end != null) - crit.add (Restrictions.le (dateField, end)); + predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get(dateField), end)); } if (searchString != null) - crit.add (Restrictions.like ("detail", "%" + searchString + "%")); + predicates.add(criteriaBuilder.equal(root.get("detail"), "%" + searchString + "%")); + query = query.select(root.get("id")) + .where(predicates.toArray(new Predicate[]{})); + + Query toRet = session.createQuery(query); if (pageSize > 0 && pageNumber > 0) { - crit.setMaxResults (pageSize); - crit.setFirstResult (pageSize * (pageNumber - 1)); + toRet = toRet.setMaxResults(pageSize) + .setFirstResult(pageSize * (pageNumber - 1)); } - return crit.list(); + return toRet.getResultList(); } /** @@ -907,20 +924,28 @@ public GLTransaction getTransaction (Journal journal, long id) if (end != null) end = Util.ceil (end); } - Criteria crit = session.createCriteria (GLTransaction.class) - .add (Restrictions.eq ("journal", journal)); - crit.setProjection(Projections.rowCount()); - if (start != null && start.equals (end)) - crit.add (Restrictions.eq (dateField, start)); - else { + CriteriaBuilder criteriaBuilder = db.session().getCriteriaBuilder(); + CriteriaQuery query = criteriaBuilder.createQuery(Long.class); + Root root = query.from(GLTransaction.class); + + List predicates = new ArrayList<>(); + predicates.add(criteriaBuilder.equal(root.get("journal"), journal)); + + if (start != null && start.equals(end)) + predicates.add(criteriaBuilder.equal(root.get(dateField), start)); + else{ if (start != null) - crit.add (Restrictions.ge (dateField, start)); + predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get(dateField), start)); if (end != null) - crit.add (Restrictions.le (dateField, end)); + predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get(dateField), end)); } if (searchString != null) - crit.add (Restrictions.like ("detail", "%" + searchString + "%")); - return (Long)crit.uniqueResult(); + predicates.add(criteriaBuilder.equal(root.get("detail"), "%" + searchString + "%")); + query = query + .where(predicates.toArray(new Predicate[]{})) + .select(criteriaBuilder.count(root.get("id"))); + + return session.createQuery(query).getSingleResult(); } /** @@ -934,7 +959,7 @@ public GLUser getUser() { * @param journal the journal. * @param acct the account. * @return current balance. - * @throws GLException if user doesn't have READ permission on this jounral. + * @throws GLException if user doesn't have READ permission on this journal. */ public BigDecimal getBalance (Journal journal, Account acct) throws HibernateException, GLException @@ -1007,7 +1032,7 @@ public BigDecimal getMaxBalance (Journal journal, Account acct, short[]... layer } return maxBalance == null ? ZERO : maxBalance; } - + /** * Current Balance for account in a given journal. * @param journal the journal. @@ -1125,35 +1150,42 @@ public BigDecimal getBalance (Journal journal, Account acct, Date date, String l } } else if (acct.isFinalAccount()) { - Criteria entryCrit = session.createCriteria (GLEntry.class) - .add (Restrictions.eq ("account", acct)) - .add (Restrictions.in ("layer", (Object[])toShortArray (layersCopy))); + + CriteriaBuilder criteriaBuilder = db.session().getCriteriaBuilder(); + CriteriaQuery query = criteriaBuilder.createQuery(GLEntry.class); + Root root = query.from(GLEntry.class); + + List predicates = new ArrayList<>(); + predicates.add(criteriaBuilder.equal(root.get("account"), acct)); + predicates.add(criteriaBuilder.equal(root.get("layer"), toShortArray (layersCopy))); + if (maxId > 0L) - entryCrit.add (Restrictions.le ("id", maxId)); + predicates.add(criteriaBuilder.equal(root.get("id"), maxId)); - Criteria txnCrit = entryCrit.createCriteria ("transaction") - .add (Restrictions.eq ("journal", journal)); + Join joinTransaction = root.join("transaction"); + predicates.add(criteriaBuilder.equal(joinTransaction.get("journal"), journal)); if (date != null) { if (inclusive) { - txnCrit.add (Restrictions.lt ("postDate", Util.tomorrow (date))); + predicates.add(criteriaBuilder.lessThan(joinTransaction.get("postDate"), Util.tomorrow(date))); } else { - date = Util.floor (date); - txnCrit.add (Restrictions.lt ("postDate", date)); + date = Util.floor(date); + predicates.add(criteriaBuilder.lessThan(joinTransaction.get("postDate"), date)); } Checkpoint chkp = getRecentCheckpoint (journal, acct, date, inclusive, layersCopy); if (chkp != null) { balance[0] = chkp.getBalance(); - txnCrit.add (Restrictions.ge ("postDate", chkp.getDate())); + predicates.add(criteriaBuilder.greaterThanOrEqualTo(joinTransaction.get("postDate"), chkp.getDate())); } } else if (!ignoreBalanceCache) { BalanceCache bcache = getBalanceCache (journal, acct, layersCopy); if (bcache != null && (maxId == 0 || bcache.getRef() <= maxId)) { balance[0] = bcache.getBalance(); - entryCrit.add (Restrictions.gt("id", bcache.getRef())); + predicates.add(criteriaBuilder.greaterThan(joinTransaction.get("id"), bcache.getRef())); } } - List l = txnCrit.list(); + query = query.where(predicates.toArray(new Predicate[] {})); + List l = session.createQuery(query).getResultList(); balance[0] = applyEntries (balance[0], l); balance[1] = new BigDecimal (l.size()); // hint for checkpoint } @@ -1252,7 +1284,7 @@ else if (acct.isChart()) { qs.append(')'); select.append(qs); - Query q = session.createSQLQuery(select.toString()); + Query q = session.createNativeQuery(select.toString()); q.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE); if (acct.isFinalAccount() || acct.isChart()) q.setParameter("acctId", acct.getId()); @@ -1328,59 +1360,78 @@ private String layersToString (short[] layers) { throws HibernateException, GLException { checkPermission (GLPermission.READ); - Criteria crit = session.createCriteria (GLEntry.class); + CriteriaBuilder criteriaBuilder = db.session().getCriteriaBuilder(); + CriteriaQuery query = criteriaBuilder.createQuery(GLEntry.class); + Root root = query.from(GLEntry.class); + + query = query + .select(root); + + + List ands = new ArrayList<>(); boolean hasChildren = false; if (acct.isCompositeAccount()) { - Disjunction dis = Restrictions.disjunction(); - for (Long l : getChildren (acct)) { - hasChildren = true; - dis.add (Restrictions.idEq(l)); - } - if (hasChildren) { - Criteria subCrit = crit.createCriteria(("account")); - subCrit.add (dis); + List disjuntions = new ArrayList<>(); + List childrenIds = getChildren(acct); + hasChildren = !childrenIds.isEmpty(); + + if (!childrenIds.isEmpty()) { + Join joinAccount = root.join("account"); + for (Long l : getChildren (acct)) { + disjuntions.add(criteriaBuilder.equal(joinAccount.get("id"), l)); + } + ands.add(criteriaBuilder.or(disjuntions.toArray(new Predicate[]{}))); } } if (!hasChildren) { - crit.add (Restrictions.eq ("account", acct)); + ands.add(criteriaBuilder.equal(root.get("account"), acct)); } - crit.add (Restrictions.in ("layer", (Object[])toShortArray (layers))); - crit = crit.createCriteria ("transaction") - .add (Restrictions.eq ("journal", journal)); + ands.add(criteriaBuilder.in(root.get("layer")).in((Object[]) toShortArray(layers))); + + Join transaction = root.join("transaction"); + ands.add(criteriaBuilder.equal(transaction.get("journal"), journal)); if (start != null || (start == null && ascendingOrder)) { start = Util.floor(start); - crit.add (Restrictions.ge ("postDate", start)); + ands.add(criteriaBuilder.greaterThanOrEqualTo(transaction.get("postDate"), start)); } if (end != null || (end == null && ascendingOrder)) { end = Util.ceil(end); - crit.add (Restrictions.le ("postDate", end)); + ands.add(criteriaBuilder.lessThanOrEqualTo(transaction.get("postDate"), end)); } - if (maxResults > 0) - crit.setMaxResults(maxResults); long maxEntry = 0L; - List entries; - BigDecimal initialBalance[]; + BigDecimal[] initialBalance; + boolean inclusive = false; if (ascendingOrder) { - crit.addOrder (Order.asc ("postDate")); - crit.addOrder (Order.asc ("timestamp")); - crit.addOrder (Order.asc ("id")); - entries = crit.list(); - initialBalance = getBalances(journal, acct, start, false, layers, maxEntry); + query.orderBy( + criteriaBuilder.asc(transaction.get("postDate")), + criteriaBuilder.asc(transaction.get("timestamp")), + criteriaBuilder.asc(transaction.get("id")) + ); } else { - crit.addOrder (Order.desc ("postDate")); - crit.addOrder (Order.desc ("timestamp")); - crit.addOrder (Order.desc ("id")); - entries = crit.list(); - if (entries.size() > 0) { - maxEntry = entries.get(0).getId(); - } - initialBalance = getBalances(journal, acct, end, true, layers, maxEntry); + inclusive = true; + query.orderBy( + criteriaBuilder.desc(transaction.get("postDate")), + criteriaBuilder.desc(transaction.get("timestamp")), + criteriaBuilder.desc(transaction.get("id")) + ); + } + + Query finalQuery = session.createQuery(query.where(ands.toArray(new Predicate[]{}))); + if (maxResults > 0) finalQuery = finalQuery.setMaxResults(maxResults); + + List entries = finalQuery.getResultList(); + if (inclusive && !entries.isEmpty()) { + maxEntry = entries.get(0).getId(); } + + initialBalance = getBalances(journal, acct, end, inclusive, layers, maxEntry); + + return new AccountDetail(journal, acct, initialBalance[0], start, end, entries, layers, ascendingOrder); } @@ -1458,16 +1509,28 @@ private String layersToString (short[] layers) { throws HibernateException, GLException { checkPermission (GLPermission.CHECKPOINT, journal); - Criteria crit = session.createCriteria (BalanceCache.class) - .add (Restrictions.eq ("journal", journal)) - .add (Restrictions.eq ("account", acct)); + CriteriaBuilder criteriaBuilder = db.session().getCriteriaBuilder(); + CriteriaQuery query = criteriaBuilder.createQuery(BalanceCache.class); + Root root = query.from(BalanceCache.class); + + query = query + .select(root); + + List ands = new ArrayList<>(); + ands.add(criteriaBuilder.equal(root.get("journal"), journal)); + ands.add(criteriaBuilder.equal(root.get("account"), acct)); + if (layers != null) - crit.add (Restrictions.eq ("layers", layersToString(layers))); + ands.add(criteriaBuilder.equal(root.get("layers"), layersToString(layers))); + + query = query.where(ands.toArray(new Predicate[]{})) + .orderBy(criteriaBuilder.desc(root.get("ref"))); + + return session.createQuery(query) + .setMaxResults(1) + .getSingleResult(); - crit.addOrder (Order.desc ("ref")); - crit.setMaxResults (1); - return (BalanceCache) crit.uniqueResult(); } @@ -1621,9 +1684,15 @@ public Transaction beginTransaction(int timeout) throws HibernateException { } public GLUser getUser (String nick) throws HibernateException { - return (GLUser) session.createCriteria (GLUser.class) - .add (Restrictions.eq ("nick", nick)) - .uniqueResult(); + CriteriaBuilder criteriaBuilder = db.session().getCriteriaBuilder(); + CriteriaQuery query = criteriaBuilder.createQuery(GLUser.class); + Root root = query.from(GLUser.class); + + query = query + .where(criteriaBuilder.equal(root.get("nick"), nick)) + .select(root); + + return session.createQuery(query).uniqueResult(); } /** * set a journal's lockDate @@ -1653,30 +1722,35 @@ public void setLockDate (Journal journal, Date lockDate) sb.append (" and layers = :layers"); Query query = session.createQuery (sb.toString()) - .setEntity ("journal", journal); + .setParameter ("journal", journal); if (account != null) - query.setEntity ("account", account); + query.setParameter ("account", account); if (layers != null) - query.setString ("layers", layersToString (layers)); + query.setParameter ("layers", layersToString (layers)); query.executeUpdate(); } public GLTransactionGroup createGroup (String name, List transactions) { GLTransactionGroup group = new GLTransactionGroup (name); - Set txns = new HashSet(); - for (GLTransaction t : transactions) - txns.add (t); + Set txns = new HashSet<>(transactions); group.setTransactions(txns); - session().save (group); + session().save(group); return group; } - public GLTransactionGroup findTransactionGroup (String name) { - Criteria crit = session.createCriteria (GLTransactionGroup.class) - .add (Restrictions.eq ("name", name)); - crit.setMaxResults (1); - return (GLTransactionGroup) crit.uniqueResult(); + public GLTransactionGroup findTransactionGroup(String name) { + CriteriaBuilder criteriaBuilder = db.session().getCriteriaBuilder(); + CriteriaQuery query = criteriaBuilder.createQuery(GLTransactionGroup.class); + Root root = query.from(GLTransactionGroup.class); + + query = query + .where(criteriaBuilder.equal(root.get("name"), name)) + .select(root); + + return db.session().createQuery(query) + .setMaxResults(1) + .getSingleResult(); } public BigDecimal getBalance @@ -1780,13 +1854,13 @@ private Account[] getAccounts (GLTransaction txn) { } return accounts; } - private List getAccountHierarchyIds (Account acct) + private List getAccountHierarchyIds (Account acct) throws GLException { if (acct == null) throw new GLException ("Invalid entry - account is null"); Account p = acct; - List l = new ArrayList(); + List l = new ArrayList<>(); while (p != null) { l.add (p.getId()); p = p.getParent(); @@ -1805,33 +1879,39 @@ private void invalidateCheckpoints (GLTransaction txn) (Journal journal, Account[] accounts, Date start, Date end, short[] layers) throws HibernateException { - Criteria crit = session.createCriteria (Checkpoint.class) - .add (Restrictions.eq ("journal", journal)); + CriteriaBuilder criteriaBuilder = db.session().getCriteriaBuilder(); + CriteriaQuery query = criteriaBuilder.createQuery(Checkpoint.class); + Root root = query.from(Checkpoint.class); + + List predicates = new ArrayList<>(); + predicates.add(criteriaBuilder.equal(root.get("journal"), journal)); + + query = query.select(root); + if (accounts.length > 0) - crit = crit.add (Restrictions.in ("account", (Object[])accounts)); + predicates.add(criteriaBuilder.in(root.get("account")).in(accounts)); if (layers != null) - crit.add (Restrictions.eq ("layers", layersToString(layers))); + predicates.add(criteriaBuilder.equal(root.get("layers"), layersToString(layers))); if (start.equals (end)) - crit.add (Restrictions.eq ("date", start)); + predicates.add(criteriaBuilder.equal(root.get("date"), start)); else { - crit.add (Restrictions.ge ("date", start)); + predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("date"), start)); if (end != null) { - crit.add (Restrictions.le ("date", end)); + predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("date"), end)); } } - Iterator iter = crit.list().iterator(); - while (iter.hasNext()) { - Checkpoint cp = (Checkpoint) iter.next(); - session.delete (cp); + List checkPoints = session + .createQuery(query.where(predicates.toArray(new Predicate[]{}))) + .getResultList(); + for (Checkpoint checkpoint: checkPoints) { + session.delete (checkpoint); } } - private BigDecimal applyEntries (BigDecimal balance, List entries) + private BigDecimal applyEntries (BigDecimal balance, List entries) throws GLException { - Iterator iter = entries.iterator(); - while (iter.hasNext()) { - GLEntry entry = (GLEntry) iter.next(); + for(GLEntry entry: entries) { if (entry.isIncrease ()) { balance = balance.add (entry.getAmount()); } @@ -1866,20 +1946,19 @@ private Object getRuleImpl (String clazz) throws GLException return impl; } private void addRules - (Map ruleMap, Journal journal, List acctHierarchy, int offset) + (Map ruleMap, Journal journal, List acctHierarchy, int offset) throws HibernateException { - Query q = session.createQuery ( - "from org.jpos.gl.RuleInfo where journal=:journal and account in (:accts) order by id" + Query q = session.createQuery ( + "from org.jpos.gl.RuleInfo where journal=:journal and account in (:accts) order by id", + RuleInfo.class ); q.setParameter ("journal", journal); - q.setParameterList ("accts", acctHierarchy, new LongType()); + q.setParameterList ("accts", acctHierarchy, Long.class); q.setCacheable (true); q.setCacheRegion ("rules"); - Iterator iter = q.iterate(); - while (iter.hasNext()) { - RuleInfo ri = (RuleInfo) iter.next(); + for (RuleInfo ri: q.list()) { RuleEntry k = new RuleEntry (ri, ri.getAccount()); RuleEntry re = (RuleEntry) ruleMap.get (k.getKey()); if (re == null) @@ -1888,12 +1967,10 @@ private Object getRuleImpl (String clazz) throws GLException re.addOffset (offset); } } - private void applyRules (GLTransaction txn, Collection rules) + private void applyRules (GLTransaction txn, Collection rules) throws HibernateException, GLException { - Iterator iter = rules.iterator(); - while (iter.hasNext()) { - RuleEntry re = (RuleEntry) iter.next(); + for (RuleEntry re: rules) { RuleInfo ri = re.getRuleInfo(); JournalRule rule = (JournalRule) getRuleImpl (ri.getClazz()); rule.check ( @@ -1905,24 +1982,20 @@ private void applyRules (GLTransaction txn, Collection rules) private Collection getRules (GLTransaction txn) throws HibernateException, GLException { - Map map = new LinkedHashMap (); + Map map = new LinkedHashMap<> (); Journal journal = txn.getJournal(); - Query q = session.createQuery ( - "from org.jpos.gl.RuleInfo where journal=:journal and account is null order by id" + Query q = session.createQuery ( + "from org.jpos.gl.RuleInfo where journal=:journal and account is null order by id", RuleInfo.class ); q.setParameter ("journal", journal); - Iterator iter = q.list().iterator(); - while (iter.hasNext()) { - RuleInfo ri = (RuleInfo) iter.next(); + for (RuleInfo ri: q.getResultList()) { RuleEntry re = new RuleEntry (ri); map.put (re.getKey(), re); } - iter = txn.getEntries().iterator(); - for (int i=0; iter.hasNext(); i++) { - GLEntry entry = (GLEntry) iter.next(); - addRules (map, journal, - getAccountHierarchyIds (entry.getAccount()), i); + for (int i = 0; i < txn.getEntries().size(); i++) { + GLEntry entry = txn.getEntries().get(i); + addRules(map, journal, getAccountHierarchyIds(entry.getAccount()), i); } return map.values(); } @@ -1954,7 +2027,7 @@ private Collection getRules (GLTransaction txn) (Journal journal, Date start, Date end, boolean credit, short layer) throws HibernateException, GLException { - StringBuffer qs = new StringBuffer ( + StringBuilder qs = new StringBuilder ( "select entry.account, sum(entry.amount)" + " from org.jpos.gl.GLEntry entry," + " org.jpos.gl.GLTransaction txn" + @@ -1971,17 +2044,17 @@ private Collection getRules (GLTransaction txn) qs.append (" and txn.postDate <= :end"); } qs.append (" group by entry.account"); - Query q = session.createQuery (qs.toString()); - q.setLong ("journal", journal.getId()); + Query q = session.createNativeQuery(qs.toString()); + q.setParameter ("journal", journal.getId()); q.setParameter ("credit", credit ? "Y" : "N"); - q.setShort ("layer", layer); + q.setParameter ("layer", layer); if (equalDate) q.setParameter ("date", start); else { q.setParameter ("start", start); q.setParameter ("end", end); } - return q.iterate(); + return q.list().iterator(); } private void deleteGLTransactions (Journal journal, Date start, Date end) throws HibernateException, GLException @@ -1998,7 +2071,7 @@ private void deleteGLTransactions (Journal journal, Date start, Date end) qs.append (" and postDate <= :endDate"); } Query q = session.createQuery (qs.toString()); - q.setLong ("journal", journal.getId()); + q.setParameter ("journal", journal.getId()); if (equalDate) q.setParameter ("date", start); else { @@ -2007,7 +2080,7 @@ private void deleteGLTransactions (Journal journal, Date start, Date end) } ScrollableResults sr = q.scroll(ScrollMode.FORWARD_ONLY); while (sr.next()) { - session.delete (sr.get(0)); + session.delete (sr.get()); } } private static Short[] toShortArray (short[] i) { @@ -2020,12 +2093,21 @@ private static Short[] toShortArray (short[] i) { } private long getMaxGLEntryId () { - Criteria crit = session.createCriteria (GLEntry.class); - crit.addOrder (Order.desc ("id")); - crit.setMaxResults (1); - GLEntry entry = (GLEntry) crit.uniqueResult(); - return entry != null ? entry.getId() : 0L; + + CriteriaBuilder criteriaBuilder = db.session().getCriteriaBuilder(); + CriteriaQuery query = criteriaBuilder.createQuery(Long.class); + Root root = query.from(GLEntry.class); + + query = query + .orderBy(criteriaBuilder.desc(root.get("id"))) + .select(root.get("id")); + + return db.session() + .createQuery(query) + .setMaxResults(1) + .getSingleResult(); } + private long getSafeMaxGLEntryId() { return Math.max (getMaxGLEntryId()-SAFE_WINDOW, 0L); } diff --git a/modules/minigl/src/main/java/org/jpos/gl/tools/Export.java b/modules/minigl/src/main/java/org/jpos/gl/tools/Export.java index f87833ac67..702bc991e0 100644 --- a/modules/minigl/src/main/java/org/jpos/gl/tools/Export.java +++ b/modules/minigl/src/main/java/org/jpos/gl/tools/Export.java @@ -18,32 +18,23 @@ package org.jpos.gl.tools; -import java.io.IOException; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.util.Iterator; - +import org.hibernate.HibernateException; +import org.hibernate.Session; +import org.hibernate.query.Query; +import org.jdom2.Comment; +import org.jdom2.DocType; import org.jdom2.Document; import org.jdom2.Element; -import org.jdom2.DocType; -import org.jdom2.Comment; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; +import org.jpos.ee.DB; +import org.jpos.gl.*; +import java.io.IOException; +import java.io.OutputStream; +import java.io.PrintWriter; import java.sql.SQLException; -import org.hibernate.Query; -import org.hibernate.Session; -import org.hibernate.HibernateException; - -import org.jpos.ee.DB; -import org.jpos.gl.GLUser; -import org.jpos.gl.Journal; -import org.jpos.gl.RuleInfo; -import org.jpos.gl.Account; -import org.jpos.gl.GLException; -import org.jpos.gl.GLSession; -import org.jpos.gl.GLTransaction; -import org.jpos.gl.Currency; +import java.util.Iterator; /** * Export to an XML document as described in diff --git a/modules/minigl/src/main/java/org/jpos/gl/tools/Import.java b/modules/minigl/src/main/java/org/jpos/gl/tools/Import.java index 9ffeefc793..1649bacc39 100644 --- a/modules/minigl/src/main/java/org/jpos/gl/tools/Import.java +++ b/modules/minigl/src/main/java/org/jpos/gl/tools/Import.java @@ -18,11 +18,11 @@ package org.jpos.gl.tools; +import jakarta.persistence.Query; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.dom4j.DocumentException; import org.hibernate.HibernateException; -import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import org.jdom2.Document; @@ -259,8 +259,8 @@ private Account getAccount (Session sess, Account chart, Element elem) "from acct in class org.jpos.gl.Account where code = :code and acct.root = :chart"); q.setParameter ("code", elem.getAttributeValue ("account")); - q.setLong ("chart", chart.getId()); - List l = q.list(); + q.setParameter ("chart", chart.getId()); + List l = q.getResultList(); return l.size() == 1 ? ((Account) l.get (0)) : null; } private FinalAccount getFinalAccount @@ -271,8 +271,8 @@ private Account getAccount (Session sess, Account chart, Element elem) "from acct in class org.jpos.gl.FinalAccount where code = :code and acct.root = :root" ); q.setParameter ("code", elem.getAttributeValue ("account")); - q.setLong ("root", chart.getId()); - List l = q.list(); + q.setParameter ("root", chart.getId()); + List l = q.getResultList(); return l.size() == 1 ? ((FinalAccount) l.get (0)) : null; } private CompositeAccount getChart (Session sess, String chartCode) @@ -282,7 +282,7 @@ private CompositeAccount getChart (Session sess, String chartCode) "from acct in class org.jpos.gl.CompositeAccount where code = :code and parent is null" ); q.setParameter ("code", chartCode); - List l = q.list(); + List l = q.getResultList(); return (CompositeAccount) ((l.size() > 0) ? l.get (0) : null); } private void createJournalRules @@ -313,7 +313,7 @@ private GLUser getUser (Session session, String nick) { Query q = session.createQuery ("from GLUser u where u.nick=:nick"); q.setParameter ("nick", nick); - List l = q.list(); + List l = q.getResultList(); if (l.size() == 0) { throw new IllegalArgumentException ( "Invalid nick '" + nick + "'" @@ -344,7 +344,7 @@ private Journal getJournal (Session sess, String name) "from journal in class org.jpos.gl.Journal where name = :name" ); q.setParameter ("name", name); - List l = q.list(); + List l = q.getResultList(); return (Journal) ((l.size() > 0) ? l.get (0) : null); } public InputSource resolveEntity (String publicId, String systemId) { diff --git a/modules/minigl/src/test/java/org/jpos/gl/AddExportUserTest.java b/modules/minigl/src/test/java/org/jpos/gl/AddExportUserTest.java index d3695fb096..60913a44eb 100644 --- a/modules/minigl/src/test/java/org/jpos/gl/AddExportUserTest.java +++ b/modules/minigl/src/test/java/org/jpos/gl/AddExportUserTest.java @@ -21,7 +21,7 @@ import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.HibernateException; -import org.hibernate.Query; +import org.hibernate.query.Query; import org.jpos.ee.DB; import org.junit.jupiter.api.Test; @@ -47,7 +47,7 @@ public void testAddExportUser() throws Exception { sess.close (); } - private GLUser getUser (Session session, String nick) + private GLUser getUser (Session session, String nick) throws HibernateException { Query q = session.createQuery ("from GLUser u where u.nick=:nick"); diff --git a/modules/qi-minigl/src/main/java/org/jpos/qi/minigl/AccountManager.java b/modules/qi-minigl/src/main/java/org/jpos/qi/minigl/AccountManager.java index 24972e723c..5e707a18f7 100644 --- a/modules/qi-minigl/src/main/java/org/jpos/qi/minigl/AccountManager.java +++ b/modules/qi-minigl/src/main/java/org/jpos/qi/minigl/AccountManager.java @@ -18,13 +18,12 @@ package org.jpos.qi.minigl; -import org.hibernate.query.criteria.internal.OrderImpl; +import jakarta.persistence.criteria.*; import org.jpos.ee.DB; import org.jpos.ee.DBManager; import org.jpos.gl.Account; import org.jpos.gl.CompositeAccount; -import javax.persistence.criteria.*; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -34,12 +33,12 @@ */ public class AccountManager extends DBManager { - + public AccountManager(DB db) { - super(db,Account.class); + super(db, Account.class); } - public List getAllChildren(int offset, int limit, Map orders, Account parent, boolean onlyComposite) throws Exception { + public List getAllChildren(int offset, int limit, Map orders, Account parent, boolean onlyComposite) { CriteriaBuilder criteriaBuilder = db.session().getCriteriaBuilder(); CriteriaQuery query; Root root; @@ -52,9 +51,11 @@ public List getAllChildren(int offset, int limit, Map orders, Ac } List orderList = new ArrayList<>(); //ORDERS - for (Map.Entry entry : orders.entrySet()) { - OrderImpl order = new OrderImpl(root.get(entry.getKey()),entry.getValue()); - orderList.add(order); + for (Map.Entry entry : orders.entrySet()) { + if (entry.getValue() == null || entry.getValue()) + orderList.add(criteriaBuilder.asc(root.get(entry.getKey()))); + else + orderList.add(criteriaBuilder.desc(root.get(entry.getKey()))); } //Is child of parent Predicate p; @@ -66,42 +67,42 @@ public List getAllChildren(int offset, int limit, Map orders, Ac query.select(root); query.orderBy(orderList); query.where(p); - List list = db.session().createQuery(query) + return (List) db.session().createQuery(query) .setMaxResults(limit) .setFirstResult(offset) .getResultList(); - return list; } - public List getAllChildren(int offset, int limit, Map orders, Account parent) throws Exception { + public List getAllChildren(int offset, int limit, Map orders, Account parent) { return getAllChildren(offset, limit, orders, parent, false); } - public List getAllCompositeChildren(int offset, int limit, Map orders, Account parent) throws Exception { + public List getAllCompositeChildren(int offset, int limit, Map orders, Account parent) { return getAllChildren(offset, limit, orders, parent, true); } - public List getCompositeAccounts(int offset, int limit, Map orders) throws Exception { + public List getCompositeAccounts(int offset, int limit, Map orders) { CriteriaBuilder criteriaBuilder = db.session().getCriteriaBuilder(); CriteriaQuery query = criteriaBuilder.createQuery(CompositeAccount.class); Root root = query.from(CompositeAccount.class); List orderList = new ArrayList<>(); //ORDERS - for (Map.Entry entry : orders.entrySet()) { - OrderImpl order = new OrderImpl(root.get(entry.getKey()),entry.getValue()); - orderList.add(order); + for (Map.Entry entry : orders.entrySet()) { + if (entry.getValue() == null || entry.getValue()) + orderList.add(criteriaBuilder.asc(root.get(entry.getKey()))); + else + orderList.add(criteriaBuilder.desc(root.get(entry.getKey()))); } query.select(root); query.orderBy(orderList); - List list = db.session().createQuery(query) + return db.session().createQuery(query) .setMaxResults(limit) .setFirstResult(offset) .getResultList(); - return list; } - public int getCompositeAccountsCount() { + public int getCompositeAccountsCount() { CriteriaBuilder criteriaBuilder = db.session().getCriteriaBuilder(); CriteriaQuery query = criteriaBuilder.createQuery(Long.class); Root root = query.from(CompositeAccount.class); @@ -109,7 +110,7 @@ public int getCompositeAccountsCount() { return db.session().createQuery(query).getSingleResult().intValue(); } - public int getCompositeChildrenCount (Account parent) { + public int getCompositeChildrenCount(Account parent) { CriteriaBuilder criteriaBuilder = db.session().getCriteriaBuilder(); CriteriaQuery query = criteriaBuilder.createQuery(Long.class); Root root = query.from(CompositeAccount.class); diff --git a/modules/qi-minigl/src/main/java/org/jpos/qi/minigl/GLTransactionManager.java b/modules/qi-minigl/src/main/java/org/jpos/qi/minigl/GLTransactionManager.java index 8e2a321eb7..946ac5f6d6 100644 --- a/modules/qi-minigl/src/main/java/org/jpos/qi/minigl/GLTransactionManager.java +++ b/modules/qi-minigl/src/main/java/org/jpos/qi/minigl/GLTransactionManager.java @@ -22,8 +22,8 @@ import org.jpos.ee.DBManager; import org.jpos.gl.GLTransaction; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; import java.util.Date; public class GLTransactionManager extends DBManager { diff --git a/modules/qi-minigl/src/main/java/org/jpos/qi/minigl/LayersHelper.java b/modules/qi-minigl/src/main/java/org/jpos/qi/minigl/LayersHelper.java index fd6937c5eb..da0238ae06 100644 --- a/modules/qi-minigl/src/main/java/org/jpos/qi/minigl/LayersHelper.java +++ b/modules/qi-minigl/src/main/java/org/jpos/qi/minigl/LayersHelper.java @@ -26,10 +26,6 @@ import org.jpos.qi.QI; import org.jpos.qi.QIHelper; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; import java.util.List; import java.util.Map; import java.util.Set; @@ -43,7 +39,7 @@ protected LayersHelper() { } @Override - public Stream getAll(int offset, int limit, Map orders) throws Exception { + public Stream getAll(int offset, int limit, Map orders) throws Exception { List all = DB.exec(db -> { LayerManager mgr = new LayerManager(db); return mgr.getAll(offset,limit,orders); diff --git a/modules/qi-sysconfig/src/main/java/org/jpos/qi/sysconfig/SysConfigHelper.java b/modules/qi-sysconfig/src/main/java/org/jpos/qi/sysconfig/SysConfigHelper.java index 9f2657575c..6b989d6147 100644 --- a/modules/qi-sysconfig/src/main/java/org/jpos/qi/sysconfig/SysConfigHelper.java +++ b/modules/qi-sysconfig/src/main/java/org/jpos/qi/sysconfig/SysConfigHelper.java @@ -26,7 +26,7 @@ import org.jpos.qi.QI; import org.jpos.qi.QIHelper; -import javax.persistence.NoResultException; +import jakarta.persistence.NoResultException; import java.util.*; import java.util.stream.Stream; @@ -41,7 +41,7 @@ public SysConfigHelper (String prefix) { public SysConfig getSysConfig (String param) { try { - return (SysConfig) DB.exec((db) -> { + return DB.exec((db) -> { SysConfigManager mgr = new SysConfigManager(db, prefix); return mgr.getItemByParam("id", param, false); } @@ -57,7 +57,7 @@ public SysConfig getSysConfig (String param) { @Override public boolean updateEntity (Binder binder) throws BLException { try { - return (boolean) DB.execWithTransaction((db) -> { + return DB.execWithTransaction((db) -> { SysConfig oldSysConfig = (SysConfig) ((SysConfig) getOriginalEntity()).clone(); binder.writeBean(getOriginalEntity()); SysConfig s = (SysConfig) getOriginalEntity(); diff --git a/modules/resultcode/src/main/java/org/jpos/ee/ResultCodeFinder.java b/modules/resultcode/src/main/java/org/jpos/ee/ResultCodeFinder.java index c0b8b50f70..deab1be11f 100644 --- a/modules/resultcode/src/main/java/org/jpos/ee/ResultCodeFinder.java +++ b/modules/resultcode/src/main/java/org/jpos/ee/ResultCodeFinder.java @@ -18,27 +18,31 @@ package org.jpos.ee; +import org.hibernate.HibernateException; +import org.hibernate.Session; +import org.hibernate.query.Query; + import java.io.Serializable; import java.util.List; -import java.sql.SQLException; - -import org.hibernate.*; -/** Automatically generated Finder class for ResultCodeFinder. - * @author Hibernate FinderGenerator **/ +/** + * Automatically generated Finder class for ResultCodeFinder. + * + * @author Hibernate FinderGenerator + **/ public class ResultCodeFinder implements Serializable { - public static List findByMnemonic(Session session, java.lang.String mnemonic) throws SQLException, HibernateException { - Query q = session.createQuery ( - "from org.jpos.ee.ResultCode as resultcode where resultcode.mnemonic=:mnemonic" + public static List findByMnemonic(Session session, java.lang.String mnemonic) throws HibernateException { + Query q = session.createQuery( + "from org.jpos.ee.ResultCode as resultcode where resultcode.mnemonic=:mnemonic", ResultCode.class ); - q.setParameter ("mnemonic", mnemonic); + q.setParameter("mnemonic", mnemonic); return q.list(); } - public static List findAll(Session session) throws SQLException, HibernateException { + public static List findAll(Session session) throws HibernateException { return session.createQuery( - "from ResultCode in class org.jpos.ee.ResultCode" + "from ResultCode in class org.jpos.ee.ResultCode", ResultCode.class ).list(); } } diff --git a/modules/resultcode/src/main/java/org/jpos/ee/ResultCodeManager.java b/modules/resultcode/src/main/java/org/jpos/ee/ResultCodeManager.java index 503dd68d34..41034f729a 100644 --- a/modules/resultcode/src/main/java/org/jpos/ee/ResultCodeManager.java +++ b/modules/resultcode/src/main/java/org/jpos/ee/ResultCodeManager.java @@ -18,16 +18,12 @@ package org.jpos.ee; -import java.util.List; -import java.util.Iterator; -import java.sql.SQLException; -import org.jpos.util.Logger; -import org.jpos.util.LogEvent; -import org.jpos.core.Configuration; -import org.hibernate.Query; -import org.hibernate.Transaction; import org.hibernate.HibernateException; import org.hibernate.ObjectNotFoundException; +import org.jpos.util.LogEvent; +import org.jpos.util.Logger; + +import java.util.List; public class ResultCodeManager { DB db; @@ -38,8 +34,8 @@ public ResultCodeManager (DB db) { } public ResultCode get (long id) { try { - return (ResultCode) db.session().load ( - ResultCode.class, new Long(id) + return db.session().load ( + ResultCode.class, id ); } catch (ObjectNotFoundException e) { LogEvent evt = db.getLog().createWarn (); @@ -53,20 +49,18 @@ ResultCode.class, new Long(id) } public ResultCode get (String rc) { try { - List l = ResultCodeFinder.findByMnemonic (db.session(), rc); - if (l.size() == 0) { + List l = ResultCodeFinder.findByMnemonic (db.session(), rc); + if (l.isEmpty()) { LogEvent evt = db.getLog().createWarn (); evt.addMessage ( "error loading unconfigured result code '" + rc + "'" ); Logger.log (evt); } else { - return (ResultCode) l.get(0); + return l.get(0); } } catch (HibernateException e) { db.getLog().warn (e); - } catch (SQLException e) { - db.getLog().warn (e); } return null; } @@ -75,7 +69,7 @@ public ResultCode get (String rc, ResultCode defRc) { return resultCode != null ? resultCode : defRc; } public ResultCodeInfo getInfo (ResultCode rc, String locale) { - return (ResultCodeInfo) rc.getLocales().get(locale); + return rc.getLocales().get(locale); } public ResultCodeInfo getInfo (String rc, String locale) { ResultCode resultCode = get (rc); diff --git a/modules/seqno/src/main/java/org/jpos/ee/SeqNo.java b/modules/seqno/src/main/java/org/jpos/ee/SeqNo.java index f88485b234..251af4a541 100644 --- a/modules/seqno/src/main/java/org/jpos/ee/SeqNo.java +++ b/modules/seqno/src/main/java/org/jpos/ee/SeqNo.java @@ -18,12 +18,14 @@ package org.jpos.ee; -import java.io.Serializable; -import java.util.Objects; - +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; import org.hibernate.annotations.CacheConcurrencyStrategy; -import javax.persistence.*; +import java.io.Serializable; +import java.util.Objects; /** * SeqNo can be used to manage application level sequencers and both synchronous as well as asynchronous locking. diff --git a/modules/seqno/src/main/java/org/jpos/ee/SeqNoManager.java b/modules/seqno/src/main/java/org/jpos/ee/SeqNoManager.java index be128cb303..1b31d75d4b 100644 --- a/modules/seqno/src/main/java/org/jpos/ee/SeqNoManager.java +++ b/modules/seqno/src/main/java/org/jpos/ee/SeqNoManager.java @@ -20,7 +20,7 @@ import org.hibernate.LockMode; import org.jpos.iso.ISOUtil; -import javax.persistence.LockTimeoutException; +import jakarta.persistence.LockTimeoutException; /** * SeqNoManager can be used to manage application level sequencers and both synchronous as well as asynchronous locking. diff --git a/modules/status/src/main/java/org/jpos/ee/status/StatusManager.java b/modules/status/src/main/java/org/jpos/ee/status/StatusManager.java index 7b8a449d52..bb2bfec36b 100644 --- a/modules/status/src/main/java/org/jpos/ee/status/StatusManager.java +++ b/modules/status/src/main/java/org/jpos/ee/status/StatusManager.java @@ -19,19 +19,14 @@ package org.jpos.ee.status; import org.hibernate.HibernateException; -import org.hibernate.Query; import org.hibernate.Transaction; +import org.hibernate.query.Query; import org.jpos.ee.DB; import org.jpos.ee.SysLog; import org.jpos.ee.SysLogManager; import java.sql.SQLException; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; /** * @author Alejandro Revilla @@ -39,14 +34,14 @@ public class StatusManager { DB db; SysLogManager syslog; - public static final Map severity = new HashMap(); + public static final Map severity = new HashMap(); static { - severity.put (Status.OK, new Integer (SysLog.INFO)); - severity.put (Status.OFF, new Integer (SysLog.INFO)); - severity.put (Status.WARN, new Integer (SysLog.WARN)); - severity.put (Status.ERROR, new Integer (SysLog.ERROR)); - severity.put (Status.CRITICAL, new Integer (SysLog.CRITICAL)); + severity.put (Status.OK, SysLog.INFO); + severity.put (Status.OFF, SysLog.INFO); + severity.put (Status.WARN, SysLog.WARN); + severity.put (Status.ERROR, SysLog.ERROR); + severity.put (Status.CRITICAL, SysLog.CRITICAL); } public StatusManager (DB db) { @@ -312,10 +307,10 @@ public void check () throws HibernateException, SQLException { } } - public List findByExpired(boolean expired) throws SQLException, HibernateException { - Query q = db.session().createQuery ("from org.jpos.ee.status.Status where expired=:expired"); - q.setBoolean ("expired", expired); - return q.list(); + public List findByExpired(boolean expired) throws HibernateException { + return db.session().createQuery ("from org.jpos.ee.status.Status where expired=:expired", Status.class) + .setParameter("expired", expired) + .getResultList() ; } private void purgeEvents (Set events, int maxEvents) { if (maxEvents > 0) { diff --git a/modules/sysconfig/src/main/java/org/jpos/ee/SysConfig.java b/modules/sysconfig/src/main/java/org/jpos/ee/SysConfig.java index 3652320401..7dc1ce43e8 100644 --- a/modules/sysconfig/src/main/java/org/jpos/ee/SysConfig.java +++ b/modules/sysconfig/src/main/java/org/jpos/ee/SysConfig.java @@ -18,14 +18,16 @@ package org.jpos.ee; -import java.io.Serializable; - +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.hibernate.annotations.CacheConcurrencyStrategy; -import javax.persistence.*; +import java.io.Serializable; @Entity @Table(name = "sysconfig") diff --git a/modules/sysconfig/src/main/java/org/jpos/ee/SysConfigManager.java b/modules/sysconfig/src/main/java/org/jpos/ee/SysConfigManager.java index 57b05add29..d7286865fa 100644 --- a/modules/sysconfig/src/main/java/org/jpos/ee/SysConfigManager.java +++ b/modules/sysconfig/src/main/java/org/jpos/ee/SysConfigManager.java @@ -25,9 +25,8 @@ import org.hibernate.Transaction; import org.hibernate.HibernateException; import org.hibernate.resource.transaction.spi.TransactionStatus; -import org.hibernate.type.IntegerType; -import javax.persistence.criteria.*; +import jakarta.persistence.criteria.*; @SuppressWarnings("unused") public class SysConfigManager extends DBManager { @@ -227,9 +226,9 @@ public int getMaxIdLength() { String queryString = "select max(length(id)) as maxidlen from sysconfig"; if (prefix != null) queryString += " where id like :query"; - NativeQuery query = db.session().createNativeQuery(queryString); + NativeQuery query = db.session().createNativeQuery(queryString, Integer.class); if (prefix != null) query.setParameter ("query", prefix + "%"); - return (int) query.addScalar("maxidlen", IntegerType.INSTANCE).getSingleResult(); + return query.addScalar("maxidlen", Integer.class).getSingleResult(); } } diff --git a/modules/things/src/main/java/org/jpos/ee/ThingsManager.java b/modules/things/src/main/java/org/jpos/ee/ThingsManager.java index 2cbc26c249..33bbe9aab0 100644 --- a/modules/things/src/main/java/org/jpos/ee/ThingsManager.java +++ b/modules/things/src/main/java/org/jpos/ee/ThingsManager.java @@ -18,10 +18,11 @@ package org.jpos.ee; -import org.hibernate.Criteria; -import org.hibernate.Query; -import org.hibernate.criterion.Order; -import org.hibernate.criterion.Restrictions; + +import jakarta.persistence.TemporalType; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; import java.math.BigDecimal; import java.util.Date; @@ -30,170 +31,197 @@ @SuppressWarnings({"unused", "JpaQueryApiInspection"}) public class ThingsManager { DB db; + public ThingsManager(DB db) { super(); this.db = db; } - public Thing create (String type) { - Thing thing = new Thing (type); - db.save (thing); + + public Thing create(String type) { + Thing thing = new Thing(type); + db.save(thing); return thing; } - public Thing get (long id) { - return (Thing) db.session().get (Thing.class, id); - } - @SuppressWarnings("unchecked") - public List getAll (String type) { - Criteria crit = db.session().createCriteria (Thing.class) - .add (Restrictions.eq ("type", type)); - return (List) crit.list(); - } - @SuppressWarnings("unchecked") - public Thing getLast (String type) { - Criteria crit = db.session().createCriteria (Thing.class) - .add (Restrictions.eq ("type", type)) - .addOrder(Order.desc("id")); - List l = crit.list(); + + public Thing get(long id) { + return (Thing) db.session().get(Thing.class, id); + } + + public List getAll(String type) { + CriteriaBuilder criteriaBuilder = db.session().getCriteriaBuilder(); + CriteriaQuery query = criteriaBuilder.createQuery(Thing.class); + Root root = query.from(Thing.class); + + query = query + .where(criteriaBuilder.equal(root.get("type"), type)) + .select(root); + + return db.session.createQuery(query).getResultList(); + } + + public Thing getLast(String type) { + CriteriaBuilder criteriaBuilder = db.session().getCriteriaBuilder(); + CriteriaQuery query = criteriaBuilder.createQuery(Thing.class); + Root root = query.from(Thing.class); + + query = query + .where(criteriaBuilder.equal(root.get("type"), type)) + .orderBy(criteriaBuilder.desc(root.get("id"))) + .select(root); + + List l = db.session.createQuery(query).getResultList(); return l.size() > 0 ? l.get(0) : null; } + // === String ============================================================== - @SuppressWarnings("unchecked") - public List listByStringName (String type, String name) { - Query query = db.session().getNamedQuery ("list-by-string-name") - .setString ("type", type) - .setString ("name", name); - return (List) query.list(); - } - @SuppressWarnings("unchecked") - public List listByStringValue (String type, String value) { - Query query = db.session().getNamedQuery ("list-by-string-value") - .setString ("type", type) - .setString ("value", value); - return (List) query.list(); - } - @SuppressWarnings("unchecked") - public List listByStringNameValue (String type, String name, String value) { - Query query = db.session().getNamedQuery ("list-by-string-name-value") - .setString ("type", type) - .setString ("name", name) - .setString ("value", value); - return (List) query.list(); + public List listByStringName(String type, String name) { + return db.session().createNamedQuery("list-by-string-name", Thing.class) + .setParameter("type", type) + .setParameter("name", name) + .getResultList(); } + + public List listByStringValue(String type, String value) { + return db.session().createNamedQuery("list-by-string-value", Thing.class) + .setParameter("type", type) + .setParameter("value", value) + .list(); + } + + public List listByStringNameValue(String type, String name, String value) { + return db.session().createNamedQuery("list-by-string-name-value", Thing.class) + .setParameter("type", type) + .setParameter("name", name) + .setParameter("value", value) + .list(); + } + // === Text ============================================================== - @SuppressWarnings("unchecked") - public List listByTextName (String type, String name) { - Query query = db.session().getNamedQuery ("list-by-text-name") - .setString ("type", type) - .setString ("name", name); - return (List) query.list(); - } - @SuppressWarnings("unchecked") - public List listByTextValue (String type, String value) { - Query query = db.session().getNamedQuery ("list-by-text-value") - .setString ("type", type) - .setString ("value", value); - return (List) query.list(); - } - @SuppressWarnings("unchecked") - public List listByTextNameValue (String type, String name, String value) { - Query query = db.session().getNamedQuery ("list-by-text-name-value") - .setString ("type", type) - .setString ("name", name) - .setString ("value", value); - return (List) query.list(); + public List listByTextName(String type, String name) { + return db.session().createNamedQuery("list-by-text-name", Thing.class) + .setParameter("type", type) + .setParameter("name", name) + .list(); + } + + + public List listByTextValue(String type, String value) { + return db.session().createNamedQuery("list-by-text-value", Thing.class) + .setParameter("type", type) + .setParameter("value", value) + .list(); } + + + public List listByTextNameValue(String type, String name, String value) { + return db.session().createNamedQuery("list-by-text-name-value", Thing.class) + .setParameter("type", type) + .setParameter("name", name) + .setParameter("value", value) + .getResultList(); + } + // === Long ============================================================== - @SuppressWarnings("unchecked") - public List listByLongName (String type, String name) { - Query query = db.session().getNamedQuery ("list-by-long-name") - .setString ("type", type) - .setString ("name", name); - return (List) query.list(); - } - @SuppressWarnings("unchecked") - public List listByLongValue (String type, long value) { - Query query = db.session().getNamedQuery ("list-by-long-value") - .setString ("type", type) - .setLong ("value", value); - return (List) query.list(); - } - @SuppressWarnings("unchecked") - public List listByLongNameValue (String type, String name, long value) { - Query query = db.session().getNamedQuery ("list-by-long-name-value") - .setString ("type", type) - .setString ("name", name) - .setLong ("value", value); - return (List) query.list(); + + public List listByLongName(String type, String name) { + return db.session().createNamedQuery("list-by-long-name", Thing.class) + .setParameter("type", type) + .setParameter("name", name) + .getResultList(); + } + + + public List listByLongValue(String type, long value) { + return db.session().createNamedQuery("list-by-long-value", Thing.class) + .setParameter("type", type) + .setParameter("value", value, Long.class) + .getResultList(); } + + + public List listByLongNameValue(String type, String name, long value) { + return db.session().createNamedQuery("list-by-long-name-value", Thing.class) + .setParameter("type", type) + .setParameter("name", name) + .setParameter("value", value, Long.class) + .list(); + } + // === Date ============================================================== - @SuppressWarnings("unchecked") - public List listByDateName (String type, String name) { - Query query = db.session().getNamedQuery ("list-by-date-name") - .setString ("type", type) - .setString ("name", name); - return (List) query.list(); - } - @SuppressWarnings("unchecked") - public List listByDateValue (String type, Date value) { - Query query = db.session().getNamedQuery ("list-by-date-value") - .setString ("type", type) - .setDate ("value", value); - return (List) query.list(); - } - @SuppressWarnings("unchecked") - public List listByDateNameValue (String type, String name, Date value) { - Query query = db.session().getNamedQuery ("list-by-date-name-value") - .setString ("type", type) - .setString ("name", name) - .setDate ("value", value); - return (List) query.list(); + + public List listByDateName(String type, String name) { + return db.session().createNamedQuery("list-by-date-name", Thing.class) + .setParameter("type", type) + .setParameter("name", name) + .list(); + } + + + public List listByDateValue(String type, Date value) { + return db.session().createNamedQuery("list-by-date-value", Thing.class) + .setParameter("type", type) + .setParameter("value", value, TemporalType.DATE) + .list(); + } + + + public List listByDateNameValue(String type, String name, Date value) { + return db.session().createNamedQuery("list-by-date-name-value", Thing.class) + .setParameter("type", type) + .setParameter("name", name) + .setParameter("value", value, TemporalType.DATE) + .list(); } // === Timestamp ============================================================== - @SuppressWarnings("unchecked") + public List listByTimestampName(String type, String name) { - Query query = db.session().getNamedQuery ("list-by-timestamp-name") - .setString ("type", type) - .setString ("name", name); - return (List) query.list(); - } - @SuppressWarnings("unchecked") - public List listByTimestampValue (String type, Date value) { - Query query = db.session().getNamedQuery ("list-by-timestamp-value") - .setString ("type", type) - .setTimestamp ("value", value); - return (List) query.list(); - } - @SuppressWarnings("unchecked") - public List listByTimestampNameValue (String type, String name, Date value) { - Query query = db.session().getNamedQuery ("list-by-timestamp-name-value") - .setString ("type", type) - .setString ("name", name) - .setTimestamp ("value", value); - return (List) query.list(); + return db.session().createNamedQuery("list-by-timestamp-name", Thing.class) + .setParameter("type", type) + .setParameter("name", name) + .list(); + } + + + public List listByTimestampValue(String type, Date value) { + return db.session().createNamedQuery("list-by-timestamp-value", Thing.class) + .setParameter("type", type) + .setParameter("value", value, TemporalType.TIMESTAMP) + .list(); + } + + + public List listByTimestampNameValue(String type, String name, Date value) { + return db.session().createNamedQuery("list-by-timestamp-name-value", Thing.class) + .setParameter("type", type) + .setParameter("name", name) + .setParameter("value", value, TemporalType.TIMESTAMP) + .list(); } // === BigDecimal ============================================================== - @SuppressWarnings("unchecked") + public List listByBigDecimalName(String type, String name) { - Query query = db.session().getNamedQuery ("list-by-big-decimal-name") - .setString ("type", type) - .setString ("name", name); - return (List) query.list(); - } - @SuppressWarnings("unchecked") - public List listByBigDecimalValue (String type, BigDecimal value) { - Query query = db.session().getNamedQuery ("list-by-big-decimal-value") - .setString ("type", type) - .setBigDecimal ("value", value); - return (List) query.list(); - } - @SuppressWarnings("unchecked") - public List listByBigDecimalNameValue (String type, String name, BigDecimal value) { - Query query = db.session().getNamedQuery ("list-by-big-decimal-name-value") - .setString ("type", type) - .setString ("name", name) - .setBigDecimal ("value", value); - return (List) query.list(); + return db.session().createNamedQuery("list-by-big-decimal-name", Thing.class) + .setParameter("type", type) + .setParameter("name", name) + .list(); + } + + + public List listByBigDecimalValue(String type, BigDecimal value) { + return db.session().createNamedQuery("list-by-big-decimal-value", Thing.class) + .setParameter("type", type) + .setParameter("value", value, BigDecimal.class) + .list(); + } + + + public List listByBigDecimalNameValue(String type, String name, BigDecimal value) { + return db.session().createNamedQuery("list-by-big-decimal-name-value", Thing.class) + .setParameter("type", type) + .setParameter("name", name) + .setParameter("value", value, BigDecimal.class) + .list(); } } diff --git a/modules/txn/src/main/java/org/jpos/transaction/DebugDB.java b/modules/txn/src/main/java/org/jpos/transaction/DebugDB.java index 625d728913..07b3ea2715 100644 --- a/modules/txn/src/main/java/org/jpos/transaction/DebugDB.java +++ b/modules/txn/src/main/java/org/jpos/transaction/DebugDB.java @@ -37,7 +37,7 @@ public int prepare(long id, Serializable context) { Session session = db.session(); SessionStatistics statistics = session.getStatistics(); - Set entityKeys = statistics.getEntityKeys(); + Set entityKeys = (Set) statistics.getEntityKeys(); ctx.log (String.format ("ENTITIES: (%d)", statistics.getEntityCount())); for (EntityKey ek : entityKeys) { Object obj = session.get(ek.getEntityName(), ek.getIdentifier()); @@ -45,7 +45,7 @@ public int prepare(long id, Serializable context) { ctx.log(String.format("[%s] %s %s", ek.getIdentifier(), ek.getEntityName(), lockMode)); } ctx.log ("==== COLLECTIONS ===="); - Set collectionKeys = statistics.getCollectionKeys(); + Set collectionKeys = (Set) statistics.getCollectionKeys(); for (CollectionKey ck : collectionKeys) { ctx.log(String.format("[%s] %s", ck.getKey(), ck.getRole())); } diff --git a/subprojects.gradle b/subprojects.gradle index b3d10238af..cc9d098d1e 100644 --- a/subprojects.gradle +++ b/subprojects.gradle @@ -1,8 +1,8 @@ apply plugin: 'java-library' apply plugin: 'signing' -sourceCompatibility = 1.8 -targetCompatibility = 1.8 +sourceCompatibility = 11 +targetCompatibility = 11 [ compileJava, compileTestJava, javadoc ]*.options*.encoding = 'UTF-8' From 52f2b37ba43f836e1acdb58c0bbdd4aff12cb8b9 Mon Sep 17 00:00:00 2001 From: Arturo Volpe Date: Tue, 29 Nov 2022 20:56:44 -0300 Subject: [PATCH 02/12] feat: Disable ehcache The eh-cache should be enabled in a different way, the previous package is currently in Alpha. Signed-off-by: Arturo Volpe --- libraries.gradle | 3 ++- modules/dbsupport/src/main/resources/hibernate.cfg.xml | 8 ++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/libraries.gradle b/libraries.gradle index c22fdcecfb..3603b0df0b 100644 --- a/libraries.gradle +++ b/libraries.gradle @@ -3,6 +3,7 @@ ext { slf4jVersion = '1.7.28' logbackVersion = '1.2.8' hibernateVersion = '6.1.5.Final' + hibernateEhcacheVersion = '6.0.0.Alpha7' geronimoVersion = '1.1.1' jettyVersion = '9.4.44.v20210927' servletApiVersion = '4.0.1' @@ -62,7 +63,7 @@ ext { hibernate_c3p0: "org.hibernate.orm:hibernate-c3p0:${hibernateVersion}", hibernate_ant: "org.hibernate.orm:hibernate-ant:${hibernateVersion}", c3p0: "com.mchange:c3p0:${c3p0Version}", - hibernate_ehcache: "org.hibernate:hibernate-ehcache:${hibernateVersion}", + hibernate_ehcache: "org.hibernate:hibernate-ehcache:${hibernateEhcacheVersion}", jta: "org.apache.geronimo.specs:geronimo-jta_1.1_spec:${geronimoVersion}", //Supported Databases diff --git a/modules/dbsupport/src/main/resources/hibernate.cfg.xml b/modules/dbsupport/src/main/resources/hibernate.cfg.xml index 397b9beedd..5ca158d2a4 100644 --- a/modules/dbsupport/src/main/resources/hibernate.cfg.xml +++ b/modules/dbsupport/src/main/resources/hibernate.cfg.xml @@ -38,9 +38,9 @@ 300 300 3000 - true - true - true - org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory + + + + From 1fe42ad5c83098e4c74c4754da71497d59e89158 Mon Sep 17 00:00:00 2001 From: Arturo Volpe Date: Tue, 29 Nov 2022 20:57:11 -0300 Subject: [PATCH 03/12] feat: Add xerces to validate xmls Signed-off-by: Arturo Volpe --- modules/minigl/build.gradle | 1 + .../src/main/java/org/jpos/gl/GLSession.java | 51 ++++++++++--------- .../main/java/org/jpos/gl/tools/Export.java | 34 ++++++------- .../main/java/org/jpos/gl/tools/Import.java | 22 ++++---- .../src/test/java/org/jpos/gl/TestBase.java | 3 +- 5 files changed, 58 insertions(+), 53 deletions(-) diff --git a/modules/minigl/build.gradle b/modules/minigl/build.gradle index 2c9c447a4c..2dfeee447e 100644 --- a/modules/minigl/build.gradle +++ b/modules/minigl/build.gradle @@ -5,6 +5,7 @@ dependencies { api project(':modules:logback') api project(':modules:dbsupport') api libraries.commons_lang + implementation 'xerces:xercesImpl:2.12.2' testImplementation project(':modules:db-h2') testImplementation project(':modules:db-postgresql') testImplementation libraries.postgresql_embedded diff --git a/modules/minigl/src/main/java/org/jpos/gl/GLSession.java b/modules/minigl/src/main/java/org/jpos/gl/GLSession.java index db1af32fc3..5a28c5a37d 100644 --- a/modules/minigl/src/main/java/org/jpos/gl/GLSession.java +++ b/modules/minigl/src/main/java/org/jpos/gl/GLSession.java @@ -18,7 +18,6 @@ package org.jpos.gl; -import com.sun.jdi.LongType; import jakarta.persistence.criteria.*; import org.hibernate.*; import org.hibernate.exception.ConstraintViolationException; @@ -261,7 +260,7 @@ public Account getChart (String code) { checkPermission (GLPermission.READ); Query q = session.createQuery ( - "from acct in class org.jpos.gl.CompositeAccount where code=:code and parent is null", Account.class + "from CompositeAccount acct where code=:code and parent is null", Account.class ); q.setParameter ("code", code); Iterator iter = q.list().iterator(); @@ -278,7 +277,7 @@ public List getCharts () { checkPermission (GLPermission.READ); return session.createQuery( - "from acct in class org.jpos.gl.CompositeAccount where parent is null", Account.class + "from CompositeAccount acct where parent is null", Account.class ).getResultList(); } @@ -295,13 +294,13 @@ public Account getAccount (Account chart, String code) throws HibernateException, GLException { checkPermission (GLPermission.READ); - Query q = session.createQuery ( - "from acct in class org.jpos.gl.Account where root=:chart and code=:code" + Query q = session.createQuery ( + "from Account acct where root=:chart and code=:code", Account.class ); - q.setParameter ("chart", chart.getId()); + q.setParameter ("chart", chart); q.setParameter ("code", code); - Iterator iter = q.list().iterator(); - return (Account) (iter.hasNext() ? iter.next() : null); + Iterator iter = q.list().iterator(); + return iter.hasNext() ? iter.next() : null; } /** @@ -410,7 +409,7 @@ public FinalAccount getFinalAccount (Account chart, String code) { checkPermission (GLPermission.READ); Query q = session.createQuery ( - "from acct in class org.jpos.gl.FinalAccount where root=:chart and code=:code" + "from FinalAccount acct where root=:chart and code=:code" ); q.setParameter ("chart", chart.getId()); q.setParameter ("code", code); @@ -429,7 +428,7 @@ public List getFinalAccounts (Account chart) { checkPermission (GLPermission.READ); Query q = session.createQuery ( - "from acct in class org.jpos.gl.FinalAccount where root=:chart" + "from FinalAccount acct where root=:chart" ); q.setParameter ("chart", chart.getId()); return (List) q.list(); @@ -444,7 +443,7 @@ public List getFinalAccounts (Account chart) public List getCompositeChildren (Account parent) throws HibernateException, GLException { checkPermission (GLPermission.READ); Query q = session.createQuery( - "from acct in class org.jpos.gl.CompositeAccount where parent=:parent" + "from CompositeAccount acct where parent=:parent" ); q.setParameter ("parent", parent); return (List) q.list(); @@ -459,7 +458,7 @@ public List getCompositeChildren (Account parent) throws Hiber public List getFinalChildren (Account parent) throws HibernateException, GLException { checkPermission (GLPermission.READ); Query q = session.createQuery( - "from acct in class org.jpos.gl.FinalAccount where parent=:parent" + "from FinalAccount acct where parent=:parent" ); q.setParameter ("parent", parent); return (List) q.list(); @@ -476,7 +475,7 @@ public List getAllAccounts (Account chart) { checkPermission (GLPermission.READ); Query q = session.createQuery ( - "from acct in class org.jpos.gl.Account where root=:chart" + "from Account acct where root=:chart" ); q.setParameter ("chart", chart.getId()); return (List) q.list(); @@ -496,7 +495,7 @@ public CompositeAccount getCompositeAccount (Account chart, String code) { checkPermission (GLPermission.READ); Query q = session.createQuery ( - "from acct in class org.jpos.gl.CompositeAccount where root=:chart and code=:code" + "from CompositeAccount acct where root=:chart and code=:code" ); q.setParameter ("chart", chart.getId()); q.setParameter ("code", code); @@ -566,7 +565,7 @@ public Journal getJournal (String name) throws HibernateException, GLException { Query q = session.createQuery ( - "from journal in class org.jpos.gl.Journal where name=:name" + "from Journal journal where name=:name" ); q.setParameter ("name", name); Iterator iter = q.list().iterator(); @@ -588,7 +587,7 @@ public List getAllJournals () { checkPermission (GLPermission.READ); Query q = session.createQuery ( - "from acct in class org.jpos.gl.Journal order by chart" + "from Journal acct order by chart" ); return (List) q.list(); } @@ -1157,7 +1156,7 @@ else if (acct.isFinalAccount()) { List predicates = new ArrayList<>(); predicates.add(criteriaBuilder.equal(root.get("account"), acct)); - predicates.add(criteriaBuilder.equal(root.get("layer"), toShortArray (layersCopy))); + predicates.add(root.get("layer").in(Arrays.asList(toShortArray(layersCopy)))); if (maxId > 0L) predicates.add(criteriaBuilder.equal(root.get("id"), maxId)); @@ -1388,7 +1387,7 @@ private String layersToString (short[] layers) { ands.add(criteriaBuilder.equal(root.get("account"), acct)); } - ands.add(criteriaBuilder.in(root.get("layer")).in((Object[]) toShortArray(layers))); + ands.add(root.get("layer").in(Arrays.asList(toShortArray(layers)))); Join transaction = root.join("transaction"); ands.add(criteriaBuilder.equal(transaction.get("journal"), journal)); @@ -1527,10 +1526,11 @@ private String layersToString (short[] layers) { query = query.where(ands.toArray(new Predicate[]{})) .orderBy(criteriaBuilder.desc(root.get("ref"))); - return session.createQuery(query) + List caches = session.createQuery(query) .setMaxResults(1) - .getSingleResult(); - + .getResultList(); + if (caches.isEmpty()) return null; + return caches.get(0); } @@ -1889,7 +1889,7 @@ private void invalidateCheckpoints (GLTransaction txn) query = query.select(root); if (accounts.length > 0) - predicates.add(criteriaBuilder.in(root.get("account")).in(accounts)); + predicates.add(root.get("account").in(Arrays.asList(accounts))); if (layers != null) predicates.add(criteriaBuilder.equal(root.get("layers"), layersToString(layers))); @@ -2083,12 +2083,13 @@ private void deleteGLTransactions (Journal journal, Date start, Date end) session.delete (sr.get()); } } - private static Short[] toShortArray (short[] i) { + + private static Short[] toShortArray(short[] i) { if (i == null) return new Short[0]; Short[] sa = new Short[i.length]; - for (int j=0; jminigl.dtd * * @author Alejandro Revilla @@ -69,32 +69,32 @@ public Document getDocument () addUsers (root); addCurrencies (root); addCharts (root); - addJournals (root); +// addJournals (root); addTransactions (root); doc.setRootElement (root); return doc; } - public void export (OutputStream os) + public void export (OutputStream os) throws IOException, SQLException, HibernateException { XMLOutputter out = new XMLOutputter (Format.getPrettyFormat ()); out.output (getDocument(), os); } - public void export (PrintWriter writer) + public void export (PrintWriter writer) throws IOException, SQLException, HibernateException { XMLOutputter out = new XMLOutputter (Format.getPrettyFormat ()); out.output (getDocument(), writer); } - private void addCharts (Element parentElement) + private void addCharts (Element parentElement) throws SQLException, HibernateException { Session sess = gls.open(); Query q = sess.createQuery ( - "from acct in class org.jpos.gl.CompositeAccount where parent is null order by code"); + "from CompositeAccount acct where parent is null order by code"); Iterator iter = q.list().iterator(); while (iter.hasNext()) { Account acct = (Account) iter.next (); @@ -103,12 +103,12 @@ private void addCharts (Element parentElement) gls.close (); } - private void addTransactions (Element parentElement) + private void addTransactions (Element parentElement) throws SQLException, HibernateException { Session sess = gls.open(); Iterator iter = sess.createQuery ( - "from transacc in class org.jpos.gl.GLTransaction order by id" + "from GLTransaction transacc order by id" ).list().iterator(); while (iter.hasNext()) { GLTransaction glt = (GLTransaction) iter.next (); @@ -117,12 +117,12 @@ private void addTransactions (Element parentElement) gls.close (); } - private void addUsers (Element parentElement) + private void addUsers (Element parentElement) throws SQLException, HibernateException { Session sess = gls.open(); Iterator iter = sess.createQuery ( - "from gluser in class org.jpos.gl.GLUser order by id" + "from GLUser gluser order by id" ).list().iterator(); while (iter.hasNext()) { GLUser user = (GLUser) iter.next (); @@ -131,12 +131,12 @@ private void addUsers (Element parentElement) gls.close (); } - private void addCurrencies (Element parentElement) + private void addCurrencies (Element parentElement) throws SQLException, HibernateException { Session sess = gls.open(); Iterator iter = sess.createQuery ( - "from currency in class org.jpos.gl.Currency order by id" + "from Currency currency order by id" ).list().iterator(); while (iter.hasNext()) { Currency currency = (Currency) iter.next (); @@ -144,11 +144,11 @@ private void addCurrencies (Element parentElement) } gls.close (); } - private void addJournalRules - (Session sess, Journal journal, Element parentElement) + private void addJournalRules + (Session sess, Journal journal, Element parentElement) throws SQLException, HibernateException { - Query q = sess.createQuery ("from ruleinfo in class org.jpos.gl.RuleInfo where journal=:journal order by id"); + Query q = sess.createQuery ("from RuleInfo ruleinfo where journal=:journal order by id"); q.setParameter ("journal", journal); Iterator iter = q.list().iterator(); while (iter.hasNext()) { @@ -156,12 +156,12 @@ private void addCurrencies (Element parentElement) parentElement.addContent (rule.toXML ()); } } - private void addJournals (Element root) + private void addJournals (Element root) throws SQLException, HibernateException { Session sess = gls.open(); Iterator iter = sess.createQuery ( - "from journal in class org.jpos.gl.Journal order by id" + "from Journal journal order by id" ).list().iterator(); while (iter.hasNext()) { diff --git a/modules/minigl/src/main/java/org/jpos/gl/tools/Import.java b/modules/minigl/src/main/java/org/jpos/gl/tools/Import.java index 1649bacc39..c71ad00314 100644 --- a/modules/minigl/src/main/java/org/jpos/gl/tools/Import.java +++ b/modules/minigl/src/main/java/org/jpos/gl/tools/Import.java @@ -19,6 +19,7 @@ package org.jpos.gl.tools; import jakarta.persistence.Query; +import jakarta.persistence.TypedQuery; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.dom4j.DocumentException; @@ -256,30 +257,31 @@ private Account getAccount (Session sess, Account chart, Element elem) throws SQLException, HibernateException { Query q = sess.createQuery ( - "from acct in class org.jpos.gl.Account where code = :code and acct.root = :chart"); + "SELECT acct FROM Account acct WHERE code = :code AND acct.root = :chart"); q.setParameter ("code", elem.getAttributeValue ("account")); - q.setParameter ("chart", chart.getId()); + q.setParameter ("chart", chart); List l = q.getResultList(); return l.size() == 1 ? ((Account) l.get (0)) : null; } private FinalAccount getFinalAccount (Session sess, Account chart, Element elem) - throws SQLException, HibernateException + throws HibernateException { - Query q = sess.createQuery ( - "from acct in class org.jpos.gl.FinalAccount where code = :code and acct.root = :root" + TypedQuery q = sess.createQuery ( + "select fa from FinalAccount fa where fa.code = :code and fa.root = :root", + FinalAccount.class ); q.setParameter ("code", elem.getAttributeValue ("account")); - q.setParameter ("root", chart.getId()); - List l = q.getResultList(); - return l.size() == 1 ? ((FinalAccount) l.get (0)) : null; + q.setParameter ("root", chart); + List l = q.getResultList(); + return l.size() == 1 ? l.get (0) : null; } private CompositeAccount getChart (Session sess, String chartCode) throws SQLException, HibernateException { Query q = sess.createQuery ( - "from acct in class org.jpos.gl.CompositeAccount where code = :code and parent is null" + "select ca from CompositeAccount ca where ca.code = :code and ca.parent is null" ); q.setParameter ("code", chartCode); List l = q.getResultList(); @@ -341,7 +343,7 @@ private Journal getJournal (Session sess, String name) throws SQLException, HibernateException { Query q = sess.createQuery ( - "from journal in class org.jpos.gl.Journal where name = :name" + "SELECT journal from Journal journal where journal.name = :name" ); q.setParameter ("name", name); List l = q.getResultList(); diff --git a/modules/minigl/src/test/java/org/jpos/gl/TestBase.java b/modules/minigl/src/test/java/org/jpos/gl/TestBase.java index a6766984ce..8926dc4039 100644 --- a/modules/minigl/src/test/java/org/jpos/gl/TestBase.java +++ b/modules/minigl/src/test/java/org/jpos/gl/TestBase.java @@ -99,7 +99,8 @@ public static void setUpBase () throws Exception { } @AfterAll public static void tearDownBase () throws Exception { - gls.close(); + if (gls != null) + gls.close(); if (pg != null) { pg.close(); } From d8ce7ab70ea8f742ba755102809560ba87edef02 Mon Sep 17 00:00:00 2001 From: Arturo Volpe Date: Wed, 30 Nov 2022 09:33:59 -0300 Subject: [PATCH 04/12] fix: Queries and warnings on glsession Signed-off-by: Arturo Volpe --- .../src/main/java/org/jpos/gl/GLSession.java | 68 +++++++++---------- 1 file changed, 33 insertions(+), 35 deletions(-) diff --git a/modules/minigl/src/main/java/org/jpos/gl/GLSession.java b/modules/minigl/src/main/java/org/jpos/gl/GLSession.java index 5a28c5a37d..7a4a4cdde3 100644 --- a/modules/minigl/src/main/java/org/jpos/gl/GLSession.java +++ b/modules/minigl/src/main/java/org/jpos/gl/GLSession.java @@ -48,12 +48,12 @@ public class GLSession { private boolean strictAccountCodes = true; private NativeDialect nativeDialect = NativeDialect.ORM; - private static String POSTGRESQL_GET_BALANCES = + private static final String POSTGRESQL_GET_BALANCES = "SELECT SUM(CASE WHEN entry.credit='N' THEN entry.amount ELSE -entry.amount end) AS balance,\n" + " COUNT(entry.id) AS count\n" + " FROM transentry AS entry\n"; - private static String MYSQL_GET_BALANCES = + private static final String MYSQL_GET_BALANCES = "SELECT SUM(if(entry.credit='N',entry.amount,-entry.amount)) AS balance,\n" + " COUNT(entry.id) AS count\n" + " from transentry as entry\n"; @@ -408,13 +408,13 @@ public FinalAccount getFinalAccount (Account chart, String code) throws HibernateException, GLException { checkPermission (GLPermission.READ); - Query q = session.createQuery ( - "from FinalAccount acct where root=:chart and code=:code" + Query q = session.createQuery ( + "from FinalAccount acct where root=:chart and code=:code", FinalAccount.class ); - q.setParameter ("chart", chart.getId()); + q.setParameter ("chart", chart); q.setParameter ("code", code); - Iterator iter = q.list().iterator(); - return (FinalAccount) (iter.hasNext() ? iter.next() : null); + Iterator iter = q.list().iterator(); + return iter.hasNext() ? iter.next() : null; } /** * @param chart chart of accounts. @@ -494,13 +494,13 @@ public CompositeAccount getCompositeAccount (Account chart, String code) throws HibernateException, GLException { checkPermission (GLPermission.READ); - Query q = session.createQuery ( - "from CompositeAccount acct where root=:chart and code=:code" + Query q = session.createQuery ( + "from CompositeAccount acct where root=:chart and code=:code", CompositeAccount.class ); - q.setParameter ("chart", chart.getId()); + q.setParameter ("chart", chart); q.setParameter ("code", code); - Iterator iter = q.list().iterator(); - return (CompositeAccount) (iter.hasNext() ? iter.next() : null); + Iterator iter = q.list().iterator(); + return iter.hasNext() ? iter.next() : null; } /** * @param chartName chart of account's code. @@ -799,18 +799,18 @@ public GLTransaction getTransaction (Journal journal, long id) if (start != null) restrictions.add(criteriaBuilder.greaterThanOrEqualTo(root.get(dateField), start)); if (end != null) - restrictions.add(criteriaBuilder.lessThanOrEqualTo(root.get(dateField), start)); + restrictions.add(criteriaBuilder.lessThanOrEqualTo(root.get(dateField), end)); } if (searchString != null) restrictions.add(criteriaBuilder.like(root.get("detail"), "%" + searchString + "%")); - query = query.where(restrictions.toArray(new Predicate[] {})); + query.where(restrictions.toArray(new Predicate[] {})); Query toRet = db.session() .createQuery(query); - if (pageSize > 0 && firstResult > 0) { - toRet = toRet.setFirstResult(firstResult) + if (pageSize > 0 && firstResult > 0) { + toRet.setFirstResult(firstResult) .setMaxResults(pageSize); } return toRet; @@ -1519,12 +1519,11 @@ private String layersToString (short[] layers) { ands.add(criteriaBuilder.equal(root.get("journal"), journal)); ands.add(criteriaBuilder.equal(root.get("account"), acct)); - if (layers != null) ands.add(criteriaBuilder.equal(root.get("layers"), layersToString(layers))); - query = query.where(ands.toArray(new Predicate[]{})) - .orderBy(criteriaBuilder.desc(root.get("ref"))); + query.where(ands.toArray(new Predicate[]{})); + query.orderBy(criteriaBuilder.desc(root.get("ref"))); List caches = session.createQuery(query) .setMaxResults(1) @@ -2004,7 +2003,7 @@ private Collection getRules (GLTransaction txn) throws HibernateException, GLException { BigDecimal balance[] = { ZERO, ZERO }; - Iterator iter = ((CompositeAccount) acct).getChildren().iterator(); + Iterator iter = (acct).getChildren().iterator(); while (iter.hasNext()) { Account a = (Account) iter.next(); BigDecimal[] b = getBalances (journal, a, date, inclusive, layers, maxId); @@ -2025,16 +2024,14 @@ private Collection getRules (GLTransaction txn) } private Iterator findSummarizedGLEntries (Journal journal, Date start, Date end, boolean credit, short layer) - throws HibernateException, GLException + throws HibernateException { StringBuilder qs = new StringBuilder ( "select entry.account, sum(entry.amount)" + - " from org.jpos.gl.GLEntry entry," + - " org.jpos.gl.GLTransaction txn" + - " where txn.id = entry.transaction" + - " and credit = :credit" + - " and txn.journal = :journal" + - " and entry.layer = :layer" + " from GLEntry entry join entry.transaction txn" + + " where credit = :credit" + + " and txn.journal = :journal" + + " and entry.layer = :layer" ); boolean equalDate = start.equals (end); if (equalDate) { @@ -2044,9 +2041,9 @@ private Collection getRules (GLTransaction txn) qs.append (" and txn.postDate <= :end"); } qs.append (" group by entry.account"); - Query q = session.createNativeQuery(qs.toString()); - q.setParameter ("journal", journal.getId()); - q.setParameter ("credit", credit ? "Y" : "N"); + Query q = session.createQuery(qs.toString()); + q.setParameter ("journal", journal); + q.setParameter ("credit", credit); q.setParameter ("layer", layer); if (equalDate) q.setParameter ("date", start); @@ -2070,17 +2067,18 @@ private void deleteGLTransactions (Journal journal, Date start, Date end) qs.append (" and postDate >= :start"); qs.append (" and postDate <= :endDate"); } - Query q = session.createQuery (qs.toString()); - q.setParameter ("journal", journal.getId()); + Query q = session.createQuery (qs.toString(), GLTransaction.class); + q.setParameter ("journal", journal); if (equalDate) q.setParameter ("date", start); else { q.setParameter ("start", start); q.setParameter ("endDate", end); } - ScrollableResults sr = q.scroll(ScrollMode.FORWARD_ONLY); - while (sr.next()) { - session.delete (sr.get()); + try (ScrollableResults sr = q.scroll(ScrollMode.FORWARD_ONLY)) { + while (sr.next()) { + session.delete(sr.get()); + } } } From 9effb2508056ae801e22ea12ea9d3e7020a43f71 Mon Sep 17 00:00:00 2001 From: Arturo Volpe Date: Wed, 30 Nov 2022 09:34:15 -0300 Subject: [PATCH 05/12] feat: Disable rest modules until we can fix jetty Signed-off-by: Arturo Volpe --- settings.gradle | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/settings.gradle b/settings.gradle index cfa0ad84a1..707058f8f0 100644 --- a/settings.gradle +++ b/settings.gradle @@ -24,10 +24,10 @@ include ':modules:core', ':modules:quartz', ':modules:visitor', ':modules:rspace', - ':modules:rest-testbed', - ':modules:testbed', +// ':modules:rest-testbed', + //':modules:testbed', ':modules:eerest', - ':modules:eeresttest', +// ':modules:eeresttest', ':modules:fsdmsgx', ':modules:groovy', ':modules:qi-core', From 6c9893e2445558b4f05d59749cd98f42f24a89e2 Mon Sep 17 00:00:00 2001 From: Arturo Volpe Date: Wed, 30 Nov 2022 09:52:09 -0300 Subject: [PATCH 06/12] feat: Use typed set in CompositeAccount Signed-off-by: Arturo Volpe --- .../java/org/jpos/gl/CompositeAccount.java | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/modules/minigl/src/main/java/org/jpos/gl/CompositeAccount.java b/modules/minigl/src/main/java/org/jpos/gl/CompositeAccount.java index c621009aff..5edde68dbb 100644 --- a/modules/minigl/src/main/java/org/jpos/gl/CompositeAccount.java +++ b/modules/minigl/src/main/java/org/jpos/gl/CompositeAccount.java @@ -18,11 +18,12 @@ package org.jpos.gl; +import org.jdom2.Element; + +import java.text.ParseException; +import java.util.Iterator; import java.util.Set; import java.util.TreeSet; -import java.util.Iterator; -import java.text.ParseException; -import org.jdom2.Element; /** * Composite Account @@ -34,7 +35,7 @@ * @author Alejandro Revilla */ public class CompositeAccount extends Account { - Set children; + Set children; public CompositeAccount () { super (); } @@ -52,21 +53,21 @@ public CompositeAccount (Element elem, CompositeAccount parent) setParent (parent); fromXML (elem); } - public void setChildren (Set children) { + public void setChildren (Set children) { this.children = children; } - public Set getChildren () { + public Set getChildren () { if (children == null) - children = new TreeSet(); + children = new TreeSet<>(); return children; } public Element toXML () { String tagName = getParent() == null ? "chart-of-accounts" : "composite-account"; Element elem = super.toXML (new Element (tagName)); - Iterator iter = getChildren().iterator(); + Iterator iter = getChildren().iterator(); while (iter.hasNext()) { - Account acct = (Account) iter.next(); + Account acct = iter.next(); elem.addContent (acct.toXML ()); } return elem; From e95c32ada4329225795d3fe175dd5cc49f439de3 Mon Sep 17 00:00:00 2001 From: Arturo Volpe Date: Wed, 30 Nov 2022 09:52:29 -0300 Subject: [PATCH 07/12] fix: Predicate on balance cache calculation Signed-off-by: Arturo Volpe --- .../src/main/java/org/jpos/gl/GLSession.java | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/modules/minigl/src/main/java/org/jpos/gl/GLSession.java b/modules/minigl/src/main/java/org/jpos/gl/GLSession.java index 7a4a4cdde3..9a98355922 100644 --- a/modules/minigl/src/main/java/org/jpos/gl/GLSession.java +++ b/modules/minigl/src/main/java/org/jpos/gl/GLSession.java @@ -1133,18 +1133,16 @@ public BigDecimal getBalance (Journal journal, Account acct, Date date, String l throws HibernateException, GLException { checkPermission (GLPermission.READ, journal); - BigDecimal balance[] = { ZERO, Z }; + BigDecimal[] balance = { ZERO, Z }; short[] layersCopy = Arrays.copyOf(layers,layers.length); if (acct.getChildren() != null) { if (acct.isChart()) { return getChartBalances (journal, (CompositeAccount) acct, date, inclusive, layersCopy, maxId); } - Iterator iter = acct.getChildren().iterator(); - while (iter.hasNext()) { - Account a = (Account) iter.next(); - BigDecimal[] b = getBalancesORM (journal, a, date, inclusive, layersCopy, maxId); - balance[0] = balance[0].add (b[0]); + for (Account a : acct.getChildren()) { + BigDecimal[] b = getBalancesORM(journal, a, date, inclusive, layersCopy, maxId); + balance[0] = balance[0].add(b[0]); // session.evict (a); FIXME this conflicts with r251 (cascade=evict generating a failed to lazily initialize a collection } } @@ -1159,7 +1157,7 @@ else if (acct.isFinalAccount()) { predicates.add(root.get("layer").in(Arrays.asList(toShortArray(layersCopy)))); if (maxId > 0L) - predicates.add(criteriaBuilder.equal(root.get("id"), maxId)); + predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("id"), maxId)); Join joinTransaction = root.join("transaction"); predicates.add(criteriaBuilder.equal(joinTransaction.get("journal"), journal)); @@ -1580,10 +1578,8 @@ private String layersToString (short[] layers) { BalanceCache bc = null; if (acct.isCompositeAccount()) { balance = ZERO; - Iterator iter = ((CompositeAccount) acct).getChildren().iterator(); - while (iter.hasNext()) { - Account a = (Account) iter.next(); - balance = balance.add (createBalanceCache (journal, a, layers, maxId)); + for (Account a : acct.getChildren()) { + balance = balance.add(createBalanceCache(journal, a, layers, maxId)); } } else if (acct.isFinalAccount()) From aefc97079385e53c475fa163a387e0680fc040e3 Mon Sep 17 00:00:00 2001 From: Arturo Volpe Date: Wed, 30 Nov 2022 10:02:27 -0300 Subject: [PATCH 08/12] fix: Balance cache max id comparision Signed-off-by: Arturo Volpe --- .../src/main/java/org/jpos/gl/GLSession.java | 40 +++++++++---------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/modules/minigl/src/main/java/org/jpos/gl/GLSession.java b/modules/minigl/src/main/java/org/jpos/gl/GLSession.java index 9a98355922..72a93dd07d 100644 --- a/modules/minigl/src/main/java/org/jpos/gl/GLSession.java +++ b/modules/minigl/src/main/java/org/jpos/gl/GLSession.java @@ -427,11 +427,11 @@ public List getFinalAccounts (Account chart) throws HibernateException, GLException { checkPermission (GLPermission.READ); - Query q = session.createQuery ( - "from FinalAccount acct where root=:chart" + Query q = session.createQuery ( + "from FinalAccount acct where root=:chart", FinalAccount.class ); - q.setParameter ("chart", chart.getId()); - return (List) q.list(); + q.setParameter ("chart", chart); + return q.getResultList(); } /** * @param parent parent account. @@ -442,11 +442,11 @@ public List getFinalAccounts (Account chart) */ public List getCompositeChildren (Account parent) throws HibernateException, GLException { checkPermission (GLPermission.READ); - Query q = session.createQuery( - "from CompositeAccount acct where parent=:parent" + Query q = session.createQuery( + "from CompositeAccount acct where parent=:parent", CompositeAccount.class ); q.setParameter ("parent", parent); - return (List) q.list(); + return q.getResultList(); } /** * @param parent parent account. @@ -457,11 +457,11 @@ public List getCompositeChildren (Account parent) throws Hiber */ public List getFinalChildren (Account parent) throws HibernateException, GLException { checkPermission (GLPermission.READ); - Query q = session.createQuery( - "from FinalAccount acct where parent=:parent" + Query q = session.createQuery( + "from FinalAccount acct where parent=:parent", FinalAccount.class ); q.setParameter ("parent", parent); - return (List) q.list(); + return q.list(); } /** * @param chart chart of accounts. @@ -474,11 +474,11 @@ public List getAllAccounts (Account chart) throws HibernateException, GLException { checkPermission (GLPermission.READ); - Query q = session.createQuery ( - "from Account acct where root=:chart" + Query q = session.createQuery ( + "from Account acct where root=:chart", Account.class ); q.setParameter ("chart", chart.getId()); - return (List) q.list(); + return q.list(); } /** @@ -890,7 +890,7 @@ public GLTransaction getTransaction (Journal journal, long id) predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get(dateField), end)); } if (searchString != null) - predicates.add(criteriaBuilder.equal(root.get("detail"), "%" + searchString + "%")); + predicates.add(criteriaBuilder.like(root.get("detail"), "%" + searchString + "%")); query = query.select(root.get("id")) .where(predicates.toArray(new Predicate[]{})); @@ -1150,16 +1150,16 @@ else if (acct.isFinalAccount()) { CriteriaBuilder criteriaBuilder = db.session().getCriteriaBuilder(); CriteriaQuery query = criteriaBuilder.createQuery(GLEntry.class); - Root root = query.from(GLEntry.class); + Root entry = query.from(GLEntry.class); List predicates = new ArrayList<>(); - predicates.add(criteriaBuilder.equal(root.get("account"), acct)); - predicates.add(root.get("layer").in(Arrays.asList(toShortArray(layersCopy)))); + predicates.add(criteriaBuilder.equal(entry.get("account"), acct)); + predicates.add(entry.get("layer").in(Arrays.asList(toShortArray(layersCopy)))); if (maxId > 0L) - predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("id"), maxId)); + predicates.add(criteriaBuilder.lessThanOrEqualTo(entry.get("id"), maxId)); - Join joinTransaction = root.join("transaction"); + Join joinTransaction = entry.join("transaction"); predicates.add(criteriaBuilder.equal(joinTransaction.get("journal"), journal)); if (date != null) { if (inclusive) { @@ -1178,7 +1178,7 @@ else if (acct.isFinalAccount()) { BalanceCache bcache = getBalanceCache (journal, acct, layersCopy); if (bcache != null && (maxId == 0 || bcache.getRef() <= maxId)) { balance[0] = bcache.getBalance(); - predicates.add(criteriaBuilder.greaterThan(joinTransaction.get("id"), bcache.getRef())); + predicates.add(criteriaBuilder.greaterThan(entry.get("id"), bcache.getRef())); } } query = query.where(predicates.toArray(new Predicate[] {})); From a87db3a024316f3996657267db354ebb3799f8bb Mon Sep 17 00:00:00 2001 From: Arturo Volpe Date: Wed, 30 Nov 2022 10:16:58 -0300 Subject: [PATCH 09/12] fix: End date comparision on glsession Signed-off-by: Arturo Volpe --- .../src/main/java/org/jpos/gl/GLSession.java | 28 +++++++------------ 1 file changed, 10 insertions(+), 18 deletions(-) diff --git a/modules/minigl/src/main/java/org/jpos/gl/GLSession.java b/modules/minigl/src/main/java/org/jpos/gl/GLSession.java index 72a93dd07d..63f9e94a6e 100644 --- a/modules/minigl/src/main/java/org/jpos/gl/GLSession.java +++ b/modules/minigl/src/main/java/org/jpos/gl/GLSession.java @@ -1506,22 +1506,19 @@ private String layersToString (short[] layers) { throws HibernateException, GLException { checkPermission (GLPermission.CHECKPOINT, journal); - CriteriaBuilder criteriaBuilder = db.session().getCriteriaBuilder(); + CriteriaBuilder criteriaBuilder = db.session().getCriteriaBuilder(); CriteriaQuery query = criteriaBuilder.createQuery(BalanceCache.class); - Root root = query.from(BalanceCache.class); - - query = query - .select(root); + Root bc = query.from(BalanceCache.class); List ands = new ArrayList<>(); - ands.add(criteriaBuilder.equal(root.get("journal"), journal)); - ands.add(criteriaBuilder.equal(root.get("account"), acct)); + ands.add(criteriaBuilder.equal(bc.get("journal"), journal)); + ands.add(criteriaBuilder.equal(bc.get("account"), acct)); if (layers != null) - ands.add(criteriaBuilder.equal(root.get("layers"), layersToString(layers))); + ands.add(criteriaBuilder.equal(bc.get("layers"), layersToString(layers))); query.where(ands.toArray(new Predicate[]{})); - query.orderBy(criteriaBuilder.desc(root.get("ref"))); + query.orderBy(criteriaBuilder.desc(bc.get("ref"))); List caches = session.createQuery(query) .setMaxResults(1) @@ -1683,9 +1680,7 @@ public GLUser getUser (String nick) throws HibernateException CriteriaQuery query = criteriaBuilder.createQuery(GLUser.class); Root root = query.from(GLUser.class); - query = query - .where(criteriaBuilder.equal(root.get("nick"), nick)) - .select(root); + query.where(criteriaBuilder.equal(root.get("nick"), nick)); return session.createQuery(query).uniqueResult(); } @@ -1739,9 +1734,7 @@ public GLTransactionGroup findTransactionGroup(String name) { CriteriaQuery query = criteriaBuilder.createQuery(GLTransactionGroup.class); Root root = query.from(GLTransactionGroup.class); - query = query - .where(criteriaBuilder.equal(root.get("name"), name)) - .select(root); + query.where(criteriaBuilder.equal(root.get("name"), name)); return db.session().createQuery(query) .setMaxResults(1) @@ -1893,7 +1886,7 @@ private void invalidateCheckpoints (GLTransaction txn) else { predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("date"), start)); if (end != null) { - predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("date"), end)); + predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("date"), end)); } } List checkPoints = session @@ -2093,8 +2086,7 @@ private long getMaxGLEntryId () { CriteriaQuery query = criteriaBuilder.createQuery(Long.class); Root root = query.from(GLEntry.class); - query = query - .orderBy(criteriaBuilder.desc(root.get("id"))) + query.orderBy(criteriaBuilder.desc(root.get("id"))) .select(root.get("id")); return db.session() From 6e6b5b5e3e7fb0395ec67ae3c8dc817f5f45c299 Mon Sep 17 00:00:00 2001 From: Arturo Volpe Date: Wed, 30 Nov 2022 10:23:38 -0300 Subject: [PATCH 10/12] fix: Account detail balance calculation Signed-off-by: Arturo Volpe --- modules/minigl/src/main/java/org/jpos/gl/GLSession.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/minigl/src/main/java/org/jpos/gl/GLSession.java b/modules/minigl/src/main/java/org/jpos/gl/GLSession.java index 63f9e94a6e..78943d579e 100644 --- a/modules/minigl/src/main/java/org/jpos/gl/GLSession.java +++ b/modules/minigl/src/main/java/org/jpos/gl/GLSession.java @@ -1426,7 +1426,7 @@ private String layersToString (short[] layers) { maxEntry = entries.get(0).getId(); } - initialBalance = getBalances(journal, acct, end, inclusive, layers, maxEntry); + initialBalance = getBalances(journal, acct, inclusive ? end : start, inclusive, layers, maxEntry); return new AccountDetail(journal, acct, initialBalance[0], start, end, entries, layers, ascendingOrder); From 3a994f20e196465b2bd93fbc40dc75d1cb4b5ead Mon Sep 17 00:00:00 2001 From: Arturo Volpe Date: Wed, 7 Dec 2022 13:09:46 -0300 Subject: [PATCH 11/12] feat: remove dom4j dependency Signed-off-by: Arturo Volpe --- libraries.gradle | 4 +- modules/dbsupport/build.gradle | 1 - .../src/main/java/org/jpos/ee/DB.java | 54 ++++++++++--------- 3 files changed, 29 insertions(+), 30 deletions(-) diff --git a/libraries.gradle b/libraries.gradle index 3603b0df0b..d33da162a6 100644 --- a/libraries.gradle +++ b/libraries.gradle @@ -28,7 +28,6 @@ ext { orgjsonVersion = '20200518' postgresqlEmbeddedVersion = '1.2.8' postgresqlBinVersion = '12.3.0' - dom4jVersion = '2.1.3' libraries = [ //jUnit (Tests) @@ -135,8 +134,7 @@ ext { liquibase: "org.liquibase:liquibase-core:${liquibaseVersion}", elk: "org.elasticsearch.client:elasticsearch-rest-high-level-client:${elkVersion}", - orgJson: "org.json:json:${orgjsonVersion}", - dom4j: "org.dom4j:dom4j:${dom4jVersion}" + orgJson: "org.json:json:${orgjsonVersion}" ] jsonSchemaValidatorLibs = [ diff --git a/modules/dbsupport/build.gradle b/modules/dbsupport/build.gradle index 95b122b795..6741a6bda1 100644 --- a/modules/dbsupport/build.gradle +++ b/modules/dbsupport/build.gradle @@ -8,7 +8,6 @@ dependencies { api libraries.hibernate_ant api libraries.c3p0 // force c3p0 version (temporary fix un Hibernate bumps up version) api libraries.jta - api libraries.dom4j api libraries.jacksonDatabind } diff --git a/modules/dbsupport/src/main/java/org/jpos/ee/DB.java b/modules/dbsupport/src/main/java/org/jpos/ee/DB.java index 3f07274200..0675408a90 100644 --- a/modules/dbsupport/src/main/java/org/jpos/ee/DB.java +++ b/modules/dbsupport/src/main/java/org/jpos/ee/DB.java @@ -18,10 +18,6 @@ package org.jpos.ee; -import org.dom4j.Document; -import org.dom4j.DocumentException; -import org.dom4j.Element; -import org.dom4j.io.SAXReader; import org.hibernate.*; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; @@ -37,6 +33,10 @@ import org.hibernate.stat.SessionStatistics; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.schema.TargetType; +import org.jdom2.Document; +import org.jdom2.Element; +import org.jdom2.JDOMException; +import org.jdom2.input.SAXBuilder; import org.jpos.core.ConfigurationException; import org.jpos.core.Environment; import org.jpos.ee.support.ModuleUtils; @@ -152,7 +152,7 @@ public SessionFactory getSessionFactory() { if (sf instanceof SessionFactoryImpl) { dialect = ((SessionFactoryImpl) sf).getJdbcServices().getDialect(); } - } catch (IOException | ConfigurationException | DocumentException | InterruptedException e) { + } catch (IOException | ConfigurationException | InterruptedException | JDOMException e) { throw new RuntimeException("Could not configure session factory", e); } finally { sfSem.release(); @@ -178,7 +178,7 @@ public static synchronized void invalidateSessionFactories() { sessionFactories.clear(); } - private SessionFactory newSessionFactory() throws IOException, ConfigurationException, DocumentException, InterruptedException { + private SessionFactory newSessionFactory() throws IOException, ConfigurationException, InterruptedException, JDOMException { Metadata md = getMetadata(); try { newSessionSem.acquireUninterruptibly(); @@ -204,19 +204,17 @@ private void configureMappings(Configuration cfg) throws ConfigurationException, for (String moduleConfig : moduleConfigs) { addMappings(cfg, moduleConfig); } - } catch (DocumentException e) { + } catch (JDOMException e) { throw new ConfigurationException("Could not parse mappings document", e); } } - private void addMappings(Configuration cfg, String moduleConfig) throws ConfigurationException, DocumentException - { + private void addMappings(Configuration cfg, String moduleConfig) throws ConfigurationException, IOException, JDOMException { Element module = readMappingElements(moduleConfig); if (module != null) { - for (Iterator l = module.elementIterator("mapping"); l.hasNext(); ) + for (Element mapping: module.getChildren("mapping")) { - Element mapping = (Element) l.next(); parseMapping(cfg, mapping, moduleConfig); } } @@ -224,8 +222,8 @@ private void addMappings(Configuration cfg, String moduleConfig) throws Configur private void parseMapping(Configuration cfg, Element mapping, String moduleName) throws ConfigurationException { - final String resource = mapping.attributeValue("resource"); - final String clazz = mapping.attributeValue("class"); + final String resource = mapping.getAttributeValue("resource"); + final String clazz = mapping.getAttributeValue("class"); if (resource != null) { @@ -248,14 +246,20 @@ else if (clazz != null) } } - private Element readMappingElements(String moduleConfig) throws DocumentException - { - SAXReader reader = new SAXReader(); + private Element readMappingElements(String moduleConfig) throws IOException, JDOMException { + SAXBuilder builder = createSAXBuilder(); final URL url = getClass().getClassLoader().getResource(moduleConfig); assert url != null; - final Document doc = reader.read(url); - return doc.getRootElement().element("mappings"); + final Document doc = builder.build(url); + return doc.getRootElement().getChild("mappings"); + } + + private SAXBuilder createSAXBuilder () { + SAXBuilder builder = new SAXBuilder (); + builder.setFeature("http://xml.org/sax/features/namespaces", true); + builder.setFeature("http://apache.org/xml/features/xinclude", true); + return builder; } private Properties loadProperties(String filename) throws IOException { @@ -276,7 +280,7 @@ private Properties loadProperties(String filename) throws IOException { * @param outputFile optional output file (may be null) * @param create true to actually issue the create statements */ - public void createSchema(String outputFile, boolean create) throws HibernateException, DocumentException { + public void createSchema(String outputFile, boolean create) throws HibernateException, JDOMException { try { // SchemaExport export = new SchemaExport(getMetadata()); SchemaExport export = new SchemaExport(); @@ -521,7 +525,7 @@ public String toString() { return "DB{" + (configModifier != null ? configModifier : "") + '}'; } - private Metadata getMetadata() throws IOException, ConfigurationException, DocumentException, InterruptedException { + private Metadata getMetadata() throws IOException, ConfigurationException, InterruptedException, JDOMException { Semaphore mdSem = mdSems.get(configModifier); if (!mdSem.tryAcquire(60, TimeUnit.SECONDS)) throw new RuntimeException ("Unable to acquire lock"); @@ -596,14 +600,12 @@ private Metadata getMetadata() throws IOException, ConfigurationException, Docum return md; } - private void addMappings(MetadataSources mds, String moduleConfig) throws ConfigurationException, DocumentException - { + private void addMappings(MetadataSources mds, String moduleConfig) throws ConfigurationException, IOException, JDOMException { Element module = readMappingElements(moduleConfig); if (module != null) { - for (Iterator l = module.elementIterator("mapping"); l.hasNext(); ) + for (Element mapping : module.getChildren("mapping")) { - Element mapping = (Element) l.next(); parseMapping(mds, mapping, moduleConfig); } } @@ -611,8 +613,8 @@ private void addMappings(MetadataSources mds, String moduleConfig) throws Config private void parseMapping (MetadataSources mds, Element mapping, String moduleName) throws ConfigurationException { - final String resource = mapping.attributeValue("resource"); - final String clazz = mapping.attributeValue("class"); + final String resource = mapping.getAttributeValue("resource"); + final String clazz = mapping.getAttributeValue("class"); if (resource != null) mds.addResource(resource); else if (clazz != null) From 63d48daab68d50e78e699b1e3a00808f9b4d92ed Mon Sep 17 00:00:00 2001 From: Arturo Volpe Date: Wed, 7 Dec 2022 13:22:43 -0300 Subject: [PATCH 12/12] fix: Remove dom4j from related modules Signed-off-by: Arturo Volpe --- modules/minigl/src/main/java/org/jpos/gl/tools/Import.java | 5 ++--- modules/seqno/src/test/java/org/jpos/ee/SeqNoTest.java | 3 +-- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/modules/minigl/src/main/java/org/jpos/gl/tools/Import.java b/modules/minigl/src/main/java/org/jpos/gl/tools/Import.java index c71ad00314..222bab9275 100644 --- a/modules/minigl/src/main/java/org/jpos/gl/tools/Import.java +++ b/modules/minigl/src/main/java/org/jpos/gl/tools/Import.java @@ -22,7 +22,6 @@ import jakarta.persistence.TypedQuery; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.dom4j.DocumentException; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; @@ -86,7 +85,7 @@ public static void usage () { System.exit (0); } - private void createSchema () throws HibernateException, DocumentException { + private void createSchema () throws HibernateException, JDOMException { DB db = new DB(configModifier); db.open(); db.beginTransaction(); @@ -370,7 +369,7 @@ public InputSource resolveEntity (String publicId, String systemId) { } public void parse (String file) throws JDOMException, SQLException, HibernateException, - ParseException, IOException, GLException, DocumentException { + ParseException, IOException, GLException { SAXBuilder builder = new SAXBuilder (true); builder.setEntityResolver (this); diff --git a/modules/seqno/src/test/java/org/jpos/ee/SeqNoTest.java b/modules/seqno/src/test/java/org/jpos/ee/SeqNoTest.java index 9d938a856e..ac6ecaec86 100644 --- a/modules/seqno/src/test/java/org/jpos/ee/SeqNoTest.java +++ b/modules/seqno/src/test/java/org/jpos/ee/SeqNoTest.java @@ -18,7 +18,6 @@ package org.jpos.ee; -import org.dom4j.DocumentException; import org.jpos.iso.ISOUtil; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -31,7 +30,7 @@ public class SeqNoTest { @BeforeAll - public static void setUp() throws DocumentException { + public static void setUp() throws Exception { System.setProperty("db.create.enabled", "YES"); try (DB db = new DB()) { db.createSchema(null, true);