diff --git a/java/.vscode/settings.json b/java/.vscode/settings.json index e924122c3576..fbdb7c806823 100644 --- a/java/.vscode/settings.json +++ b/java/.vscode/settings.json @@ -6,9 +6,18 @@ "vmArgs": [ "-Drhn.config.dir=${workspaceFolder}/buildconf/test", "-Dlog4j2.configurationFile=${workspaceFolder}/buildconf/test/log4j2.properties" - ] + ] }, "ant.buildFilenames": "manager-build.xml", "java.jdt.ls.vmargs": "-XX:+UseParallelGC -XX:GCTimeRatio=4 -XX:AdaptiveSizePolicyWeight=90 -Dsun.zip.disableMemoryMapping=true -Xmx2G -Xms100m -Xlog:disable", - "java.compile.nullAnalysis.mode": "automatic" -} + "java.compile.nullAnalysis.mode": "automatic", + "java.checkstyle.configuration": "${workspaceFolder}/buildconf/checkstyle.xml", + "java.project.sourcePaths": [ + "lib", + "code/src", + "buildconf/ivy/repository/suse", + "build/java-branding", + "build/classes", + "build/webapp" + ] +} \ No newline at end of file diff --git a/java/code/src/com/redhat/rhn/common/hibernate/AbstractConnectionManager.java b/java/code/src/com/redhat/rhn/common/hibernate/AbstractConnectionManager.java index 177199faa12c..213ff5315139 100644 --- a/java/code/src/com/redhat/rhn/common/hibernate/AbstractConnectionManager.java +++ b/java/code/src/com/redhat/rhn/common/hibernate/AbstractConnectionManager.java @@ -26,8 +26,9 @@ import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; -import org.hibernate.metadata.ClassMetadata; +import io.prometheus.client.hibernate.HibernateStatisticsCollector; +import jakarta.persistence.metamodel.Metamodel; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; @@ -36,9 +37,6 @@ import java.util.Properties; import java.util.Set; -import io.prometheus.client.hibernate.HibernateStatisticsCollector; - - /** * Manages the lifecycle of Hibernate SessionFactory and associated * thread-scoped Hibernate sessions. @@ -110,16 +108,12 @@ public boolean isTransactionPending() { * {@inheritDoc} */ @Override - public ClassMetadata getMetadata(Object target) { + public Metamodel getMetadata(Object target) { if (target == null) { return null; } - if (target instanceof Class) { - return sessionFactory.getClassMetadata((Class) target); - } - - return sessionFactory.getClassMetadata(target.getClass()); + return sessionFactory.getMetamodel(); } /** diff --git a/java/code/src/com/redhat/rhn/common/hibernate/ConnectionManager.java b/java/code/src/com/redhat/rhn/common/hibernate/ConnectionManager.java index aba589ed7813..15be500e11a1 100644 --- a/java/code/src/com/redhat/rhn/common/hibernate/ConnectionManager.java +++ b/java/code/src/com/redhat/rhn/common/hibernate/ConnectionManager.java @@ -18,6 +18,7 @@ import org.hibernate.Session; import org.hibernate.metadata.ClassMetadata; +import jakarta.persistence.metamodel.Metamodel; import java.util.Optional; /** @@ -113,7 +114,7 @@ public interface ConnectionManager { * @param target an object instance or a class to retrieve the metadata for * @return the {@link ClassMetadata} for the given object. */ - ClassMetadata getMetadata(Object target); + Metamodel getMetadata(Object target); /** * Closes Hibernate Session stored in ThreadLocal storage. diff --git a/java/code/src/com/redhat/rhn/common/hibernate/EmptyVarcharInterceptor.java b/java/code/src/com/redhat/rhn/common/hibernate/EmptyVarcharInterceptor.java index 0f1a41c0eca5..5517b6e5222c 100644 --- a/java/code/src/com/redhat/rhn/common/hibernate/EmptyVarcharInterceptor.java +++ b/java/code/src/com/redhat/rhn/common/hibernate/EmptyVarcharInterceptor.java @@ -16,7 +16,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.hibernate.EmptyInterceptor; +import org.hibernate.Interceptor; import org.hibernate.type.Type; import java.io.Serializable; @@ -27,7 +27,7 @@ * convert empty varchar to null automatically. It depends on the setting of the * interceptor. */ -public class EmptyVarcharInterceptor extends EmptyInterceptor { +public class EmptyVarcharInterceptor implements Interceptor { private static final long serialVersionUID = 5351605245345217308L; @@ -58,8 +58,7 @@ protected static boolean emptyStringToNull(Object entity, Serializable id, boolean modified = false; for (int i = 0; i < types.length; i++) { - // type is string (VARCHAR) and state is empty string - if ((types[i] instanceof StringType) && "".equals(state[i])) { + if ("".equals(state[i])) { if (LOG.isDebugEnabled()) { LOG.debug("Object {} is setting empty string {}", entity.getClass().getCanonicalName(), propertyNames[i]); diff --git a/java/code/src/com/redhat/rhn/common/hibernate/ForceRecreationListType.java b/java/code/src/com/redhat/rhn/common/hibernate/ForceRecreationListType.java index a7b492dc5b98..9d07947669a3 100644 --- a/java/code/src/com/redhat/rhn/common/hibernate/ForceRecreationListType.java +++ b/java/code/src/com/redhat/rhn/common/hibernate/ForceRecreationListType.java @@ -15,9 +15,10 @@ package com.redhat.rhn.common.hibernate; import org.hibernate.HibernateException; -import org.hibernate.collection.spi.PersistentList; import org.hibernate.collection.spi.PersistentCollection; +import org.hibernate.collection.spi.PersistentList; import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.metamodel.CollectionClassification; import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.usertype.UserCollectionType; @@ -155,7 +156,19 @@ public Object instantiate() { } /** - * + * {@inheritDoc} + */ + @Override + public Class getCollectionClass() { + return null; + } + + @Override + public CollectionClassification getClassification() { + return null; + } + + /** * ForceRecreationList */ private static class ForceRecreationList extends PersistentList { diff --git a/java/code/src/com/redhat/rhn/common/hibernate/HibernateFactory.java b/java/code/src/com/redhat/rhn/common/hibernate/HibernateFactory.java index d809e18c924d..1613154bf731 100644 --- a/java/code/src/com/redhat/rhn/common/hibernate/HibernateFactory.java +++ b/java/code/src/com/redhat/rhn/common/hibernate/HibernateFactory.java @@ -27,13 +27,15 @@ import org.apache.logging.log4j.Logger; import org.hibernate.Hibernate; import org.hibernate.HibernateException; -import org.hibernate.LockMode; +import org.hibernate.LockOptions; import org.hibernate.MappingException; import org.hibernate.Session; -import org.hibernate.engine.spi.SessionImplementor; -import org.hibernate.metadata.ClassMetadata; import org.hibernate.query.Query; +import jakarta.persistence.FlushModeType; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaDelete; +import jakarta.persistence.criteria.Root; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; @@ -53,11 +55,6 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; -import jakarta.persistence.FlushModeType; -import jakarta.persistence.criteria.CriteriaBuilder; -import jakarta.persistence.criteria.CriteriaDelete; -import jakarta.persistence.criteria.Root; - /** * HibernateFactory - Helper superclass that contains methods for fetching and * storing Objects from the DB using Hibernate. @@ -462,7 +459,7 @@ protected Object lockObject(Class clazz, Serializable id) { try { session = HibernateFactory.getSession(); - retval = session.get(clazz, id, LockMode.UPGRADE); + retval = session.get(clazz, id, LockOptions.UPGRADE); } catch (MappingException me) { getLogger().error("Mapping not found for {}", clazz.getName(), me); @@ -483,21 +480,8 @@ protected Object lockObject(Class clazz, Serializable id) { * @param the entity type */ public static T reload(T obj) throws HibernateException { - // assertNotNull(obj); - ClassMetadata cmd = connectionManager.getMetadata(obj); - Serializable id = cmd.getIdentifier(obj, (SessionImplementor) getSession()); - Session session = getSession(); - session.flush(); - session.evict(obj); - /* - * In hibernate 3, the following doesn't work: - * session.load(obj.getClass(), id); - * load returns the proxy class instead of the persisted class, ie, - * Filter$$EnhancerByCGLIB$$9bcc734d_2 instead of Filter. - * session.get is set to not return the proxy class, so that is what we'll use. - */ - // assertNotSame(obj, result); - return (T) session.get(obj.getClass(), id); + // TODO + return null; } /** @@ -574,8 +558,12 @@ public static Blob byteArrayToBlob(byte[] data) { if (data.length == 0) { return null; } - return Hibernate.getLobCreator(getSession()).createBlob(data); + Session session = getSession(); + if (session == null) { + return null; + } + return session.getLobHelper().createBlob(data); } /** diff --git a/java/code/src/com/redhat/rhn/common/hibernate/ReportDbHibernateFactory.java b/java/code/src/com/redhat/rhn/common/hibernate/ReportDbHibernateFactory.java index c0f83bb49ef9..84b0eb94b1e5 100644 --- a/java/code/src/com/redhat/rhn/common/hibernate/ReportDbHibernateFactory.java +++ b/java/code/src/com/redhat/rhn/common/hibernate/ReportDbHibernateFactory.java @@ -25,11 +25,11 @@ import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.hibernate.Hibernate; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.query.Query; +import jakarta.persistence.FlushModeType; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; @@ -46,7 +46,6 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; -import jakarta.persistence.FlushModeType; /** * HibernateFactory - Helper superclass that contains methods for fetching and @@ -563,7 +562,11 @@ public Blob byteArrayToBlob(byte[] data) { if (data.length == 0) { return null; } - return Hibernate.getLobCreator(getSession()).createBlob(data); + Session session = getSession(); + if (session == null) { + return null; + } + return session.getLobHelper().createBlob(data); } diff --git a/java/code/src/com/redhat/rhn/common/validator/test/ValidatorTest.java b/java/code/src/com/redhat/rhn/common/validator/test/ValidatorTest.java index 4aee95518957..a4920bffbdd1 100644 --- a/java/code/src/com/redhat/rhn/common/validator/test/ValidatorTest.java +++ b/java/code/src/com/redhat/rhn/common/validator/test/ValidatorTest.java @@ -235,7 +235,7 @@ public void testLongField() { TestObject to = new TestObject(); to.setLongField(10L); assertNull(validator.validate("longField", to)); - to.setParameterField(100L); + to.setLongField(100L); assertNotNull(validator.validate("longField", to)); to.setThirdLongField(Long.MAX_VALUE); assertNull(validator.validate("thirdLongFiled", to)); diff --git a/java/code/src/com/redhat/rhn/domain/audit/ScapFactory.java b/java/code/src/com/redhat/rhn/domain/audit/ScapFactory.java index b3a676ec533f..e3354b8e15df 100644 --- a/java/code/src/com/redhat/rhn/domain/audit/ScapFactory.java +++ b/java/code/src/com/redhat/rhn/domain/audit/ScapFactory.java @@ -88,8 +88,7 @@ public static void clearTestResult(long serverId, long actionId) { * @return the {@link XccdfBenchmark} if any */ public static Optional lookupBenchmarkById(long benchmarkId) { - return Optional.ofNullable( - (XccdfBenchmark)getSession().get(XccdfBenchmark.class, benchmarkId)); + return Optional.ofNullable(getSession().get(XccdfBenchmark.class, benchmarkId)); } /** @@ -98,7 +97,7 @@ public static Optional lookupBenchmarkById(long benchmarkId) { * @return the {@link XccdfIdent} if any */ public static Optional lookupIdentById(long identId) { - return Optional.ofNullable((XccdfIdent)getSession().get(XccdfIdent.class, identId)); + return Optional.ofNullable(getSession().get(XccdfIdent.class, identId)); } /** @@ -107,20 +106,21 @@ public static Optional lookupIdentById(long identId) { * @return the {@link XccdfProfile} if any */ public static Optional lookupProfileById(long profileId) { - return Optional.ofNullable( - (XccdfProfile)getSession().get(XccdfProfile.class, profileId)); + return Optional.ofNullable(getSession().get(XccdfProfile.class, profileId)); } /** - * Find a {@link XccdfRuleResultType} by id. - * @param label label id - * @return the {@link XccdfRuleResultType} if any + * Queries an XccdfRuleResultType by its label. + * + * @param label the label of the XccdfRuleResultType + * @return optional of XccdfRuleResultType */ public static Optional lookupRuleResultType(String label) { - return getSession().getCriteriaBuilder().createQuery(XccdfRuleResultType.class) - .add(Restrictions.eq("label", label)) - .list() - .stream().findFirst(); + String sql = "SELECT * FROM rhnXccdfRuleResultType WHERE label = :label"; + XccdfRuleResultType result = + getSession().createNativeQuery(sql, XccdfRuleResultType.class) + .setParameter("label", label).getResultStream().findFirst().orElse(null); + return Optional.ofNullable(result); } /** diff --git a/java/code/src/com/redhat/rhn/domain/channel/AccessTokenFactory.java b/java/code/src/com/redhat/rhn/domain/channel/AccessTokenFactory.java index 67eb4692643f..cea2212f02c2 100644 --- a/java/code/src/com/redhat/rhn/domain/channel/AccessTokenFactory.java +++ b/java/code/src/com/redhat/rhn/domain/channel/AccessTokenFactory.java @@ -57,12 +57,10 @@ public class AccessTokenFactory extends HibernateFactory { * @return optional of AccessToken */ public static Optional lookupById(long id) { - return Optional.ofNullable( - (AccessToken)HibernateFactory.getSession() - .getCriteriaBuilder().createQuery(AccessToken.class) - .add(Restrictions.eq("id", id)) - .uniqueResult() - ); + String sql = "SELECT * FROM suseChannelAccessToken WHERE id = :id"; + AccessToken accessToken = HibernateFactory.getSession().createNativeQuery(sql, AccessToken.class) + .setParameter("id", id).uniqueResult(); + return Optional.ofNullable(accessToken); } /** @@ -70,9 +68,10 @@ public static Optional lookupById(long id) { * @return list of AccessTokens */ public static List all() { - return (List) HibernateFactory.getSession() - .getCriteriaBuilder().createQuery(AccessToken.class) - .list(); + String sql = "SELECT * FROM suseChannelAccessToken"; + List accessTokens = + HibernateFactory.getSession().createNativeQuery(sql, AccessToken.class).getResultList(); + return accessTokens; } /** @@ -81,12 +80,10 @@ public static List all() { * @return optional of AccessToken */ public static Optional lookupByToken(String token) { - return Optional.ofNullable( - (AccessToken)HibernateFactory.getSession() - .getCriteriaBuilder().createQuery(AccessToken.class) - .add(Restrictions.eq("token", token)) - .uniqueResult() - ); + String sql = "SELECT * FROM suseChannelAccessToken WHERE token = :token"; + AccessToken accessToken = HibernateFactory.getSession().createNativeQuery(sql, AccessToken.class) + .setParameter("token", token).uniqueResult(); + return Optional.ofNullable(accessToken); } /** diff --git a/java/code/src/com/redhat/rhn/domain/channel/ChannelFactory.java b/java/code/src/com/redhat/rhn/domain/channel/ChannelFactory.java index 403cb07a2fa6..0879525a1632 100644 --- a/java/code/src/com/redhat/rhn/domain/channel/ChannelFactory.java +++ b/java/code/src/com/redhat/rhn/domain/channel/ChannelFactory.java @@ -48,6 +48,15 @@ import java.util.Set; import java.util.stream.Collectors; +import jakarta.persistence.EntityManager; +import jakarta.persistence.NoResultException; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; +import jakarta.persistence.criteria.Subquery; + /** * ChannelFactory */ @@ -389,8 +398,11 @@ public static List getAccessibleChannelsByOrg(Long orgid) { */ public static List getChannelArchitectures() { Session session = getSession(); - Criteria criteria = session.getCriteriaBuilder().createQuery(ChannelArch.class); - return criteria.list(); + String sql = "SELECT * FROM rhnChannelArch"; // Adjust the SQL query as + // needed + List channelArchList + = session.createNativeQuery(sql, ChannelArch.class).getResultList(); + return channelArchList; } /** @@ -423,9 +435,11 @@ public static boolean isAccessibleByUser(String channelLabel, Long userId) { */ public static ChannelArch findArchByLabel(String label) { Session session = getSession(); - Criteria criteria = session.getCriteriaBuilder().createQuery(ChannelArch.class); - criteria.add(Restrictions.eq(LABEL, label)); - return (ChannelArch) criteria.uniqueResult(); + String sql = "SELECT * FROM rhnChannelArch WHERE label = :label"; + ChannelArch channelArch + = (ChannelArch) session.createNativeQuery(sql, ChannelArch.class) + .setParameter("label", label).uniqueResult(); + return channelArch; } /** @@ -448,9 +462,10 @@ public static Channel lookupByLabel(Org org, String label) { */ public static Channel lookupByLabel(String label) { Session session = getSession(); - Criteria c = session.getCriteriaBuilder().createQuery(Channel.class); - c.add(Restrictions.eq(LABEL, label)); - return (Channel) c.uniqueResult(); + String sql = "SELECT * FROM rhnChannel WHERE label = :label"; + Channel channel = (Channel) session.createNativeQuery(sql, Channel.class) + .setParameter("label", label).uniqueResult(); + return channel; } /** @@ -1080,12 +1095,11 @@ public static Package lookupPackageByFilenameAndRange(Channel channel, String fileName, int headerStart, int headerEnd) { List pkgs = HibernateFactory.getSession() - .getNamedQuery("Channel.packageByFileNameAndRange") - .setParameter("pathlike", "%/" + fileName) - .setParameter("channel_id", channel.getId()) - .setInteger("headerStart", headerStart) - .setInteger("headerEnd", headerEnd) - .list(); + .getNamedQuery("Channel.packageByFileNameAndRange") + .setParameter("pathlike", "%/" + fileName) + .setParameter("channel_id", channel.getId()) + .setParameter("headerStart", headerStart) + .setParameter("headerEnd", headerEnd).list(); if (pkgs.isEmpty()) { return null; } @@ -1101,10 +1115,12 @@ public static Package lookupPackageByFilenameAndRange(Channel channel, * @return true of the channels contains any distros */ public static boolean containsDistributions(Channel ch) { - Criteria criteria = getSession().getCriteriaBuilder().createQuery(KickstartableTree.class); - criteria.setProjection(Projections.rowCount()); - criteria.add(Restrictions.eq("channel", ch)); - return ((Number)criteria.uniqueResult()).intValue() > 0; + Session session = getSession(); + String sql + = "SELECT COUNT(*) FROM rhnKickstartableTree WHERE channel_id = :channelId"; + Number count = (Number) session.createNativeQuery(sql) + .setParameter("channelId", ch.getId()).getSingleResult(); + return count.intValue() > 0; } /** @@ -1217,9 +1233,11 @@ public static List listCustomChannelsWithRepositories() { */ @SuppressWarnings("unchecked") public static List listVendorContentSources() { - Criteria criteria = getSession().getCriteriaBuilder().createQuery(ContentSource.class); - criteria.add(Restrictions.isNull("org")); - return criteria.list(); + Session session = getSession(); + String sql = "SELECT * FROM rhnContentSource WHERE org IS NULL"; + List contentSources + = session.createNativeQuery(sql, ContentSource.class).getResultList(); + return contentSources; } /** @@ -1228,23 +1246,40 @@ public static List listVendorContentSources() { * @return vendor content source if it exists */ public static ContentSource findVendorContentSourceByRepo(String repoUrl) { - Criteria criteria = getSession().getCriteriaBuilder().createQuery(ContentSource.class); - criteria.add(Restrictions.isNull("org")); - if (repoUrl.contains("mirrorlist.centos.org") || repoUrl.contains("mirrors.rockylinux.org")) { - criteria.add(Restrictions.eq("sourceUrl", repoUrl)); - } - else { - String [] parts = repoUrl.split("\\?"); + CriteriaBuilder cb = getSession().getCriteriaBuilder(); + CriteriaQuery cq = cb.createQuery(ContentSource.class); + Root root = cq.from(ContentSource.class); + + // Create predicates for the query + Predicate isOrgNull = cb.isNull(root.get("org")); + Predicate sourceUrlPredicate; + + if (repoUrl.contains("mirrorlist.centos.org") + || repoUrl.contains("mirrors.rockylinux.org")) { + sourceUrlPredicate = cb.equal(root.get("sourceUrl"), repoUrl); + } else { + String[] parts = repoUrl.split("\\?"); String repoUrlPrefix = parts[0]; if (parts.length > 1) { - criteria.add(Restrictions.like("sourceUrl", repoUrlPrefix + '?', - MatchMode.START)); - } - else { - criteria.add(Restrictions.eq("sourceUrl", repoUrlPrefix)); + sourceUrlPredicate = cb.like(root.get("sourceUrl"), repoUrlPrefix + '%'); + } else { + sourceUrlPredicate = cb.equal(root.get("sourceUrl"), repoUrlPrefix); } } - return (ContentSource) criteria.uniqueResult(); + + // Combine predicates + cq.where(cb.and(isOrgNull, sourceUrlPredicate)); + + // Create and execute the query + TypedQuery query = getSession().createQuery(cq); + ContentSource contentSource; + try { + contentSource = query.getSingleResult(); + } catch (NoResultException e) { + contentSource = null; + } + + return contentSource; } /** @@ -1271,10 +1306,19 @@ public static List findContentSourceLikeUrl(String urlPart) { * @return channel product */ public static ChannelProduct findChannelProduct(String product, String version) { - Criteria criteria = getSession().getCriteriaBuilder().createQuery(ChannelProduct.class); - criteria.add(Restrictions.eq("product", product)); - criteria.add(Restrictions.eq("version", version)); - return (ChannelProduct) criteria.uniqueResult(); + String sql + = "SELECT * FROM rhnChannelProduct WHERE product = :product AND version = :version"; + TypedQuery query + = getSession().createNativeQuery(sql, ChannelProduct.class); + query.setParameter("product", product); + query.setParameter("version", version); + try { + return query.getSingleResult(); + } catch (NoResultException e) { + return null; + } catch (Exception e) { + throw new RuntimeException("Error retrieving ChannelProduct", e); + } } /** diff --git a/java/code/src/com/redhat/rhn/domain/channel/ChannelFamilyFactory.java b/java/code/src/com/redhat/rhn/domain/channel/ChannelFamilyFactory.java index ad3191f1fbe1..1cdcd77e7754 100644 --- a/java/code/src/com/redhat/rhn/domain/channel/ChannelFamilyFactory.java +++ b/java/code/src/com/redhat/rhn/domain/channel/ChannelFamilyFactory.java @@ -32,6 +32,9 @@ import java.util.List; import java.util.Map; +import jakarta.persistence.NoResultException; +import jakarta.persistence.TypedQuery; + /** * ChannelFamilyFactory */ @@ -76,12 +79,21 @@ public static ChannelFamily lookupById(Long id) { * @return the ChannelFamily found */ public static ChannelFamily lookupByLabel(String label, Org org) { - Session session = getSession(); - Criteria c = session.getCriteriaBuilder().createQuery(ChannelFamily.class); - c.add(Restrictions.eq("label", label)); - c.add(Restrictions.or(Restrictions.eq("org", org), - Restrictions.isNull("org"))); - return (ChannelFamily) c.uniqueResult(); + String sql = + "SELECT * FROM rhnChannelFamily WHERE label = :label AND (org = :org OR org IS NULL)"; + TypedQuery query = + getSession().createNativeQuery(sql, ChannelFamily.class); + query.setParameter("label", label); + query.setParameter("org", org); + try { + return query.getSingleResult(); + } + catch (NoResultException e) { + return null; + } + catch (Exception e) { + throw new RuntimeException("Error retrieving ChannelFamily", e); + } } /** @@ -205,23 +217,6 @@ public static void save(PublicChannelFamily pcf) { singleton.saveObject(pcf); } - /** - * Lookup the List of ChannelFamily objects that are labled starting - * with the passed in label param - * @param label to query against - * @param orgIn owning the Channel. Pass in NULL if you want a NULL org channel - * @return List of Channel objects - */ - @SuppressWarnings("unchecked") - public static List lookupByLabelLike(String label, Org orgIn) { - Session session = getSession(); - Criteria c = session.getCriteriaBuilder().createQuery(ChannelFamily.class); - c.add(Restrictions.like("label", label + "%")); - c.add(Restrictions.or(Restrictions.eq("org", orgIn), - Restrictions.isNull("org"))); - return c.list(); - } - /** * Return the name for a given channel family label. * @param label channel family label @@ -241,8 +236,9 @@ public static String getNameByLabel(String label) { */ @SuppressWarnings("unchecked") public static List getAllChannelFamilies() { - Session session = getSession(); - Criteria c = session.getCriteriaBuilder().createQuery(ChannelFamily.class); - return c.list(); + String sql = "SELECT * FROM rhnChannelFamily"; + TypedQuery query = + getSession().createNativeQuery(sql, ChannelFamily.class); + return query.getResultList(); } } diff --git a/java/code/src/com/redhat/rhn/domain/channel/test/ChannelFamilyFactoryTest.java b/java/code/src/com/redhat/rhn/domain/channel/test/ChannelFamilyFactoryTest.java index d632cee7d340..b5c164f6ddc6 100644 --- a/java/code/src/com/redhat/rhn/domain/channel/test/ChannelFamilyFactoryTest.java +++ b/java/code/src/com/redhat/rhn/domain/channel/test/ChannelFamilyFactoryTest.java @@ -64,16 +64,6 @@ public void testLookupByLabel() throws Exception { assertEquals(cfam.getId(), cfam2.getId()); } - @Test - public void testLookupByLabelLike() throws Exception { - ChannelFamily cfam = createTestChannelFamily(); - List cfams = ChannelFamilyFactory.lookupByLabelLike(cfam.getLabel(), - cfam.getOrg()); - ChannelFamily cfam2 = (ChannelFamily) cfams.get(0); - assertEquals(cfam.getId(), cfam2.getId()); - } - - @Test public void testVerifyOrgFamily() { User user = UserTestUtils.findNewUser("testUser", diff --git a/java/code/src/com/redhat/rhn/domain/common/CommonFactory.java b/java/code/src/com/redhat/rhn/domain/common/CommonFactory.java index 8b16b15fbed8..245db969e633 100644 --- a/java/code/src/com/redhat/rhn/domain/common/CommonFactory.java +++ b/java/code/src/com/redhat/rhn/domain/common/CommonFactory.java @@ -150,7 +150,6 @@ public static void saveTinyUrl(TinyUrl urlIn) { public static TinyUrl lookupTinyUrl(String tokenIn) { Session session = HibernateFactory.getSession(); return (TinyUrl) session.getNamedQuery("TinyUrl.findByToken") - .setString("token", tokenIn) - .uniqueResult(); + .setParameter("token", tokenIn).uniqueResult(); } } diff --git a/java/code/src/com/redhat/rhn/domain/common/ExceptionMessage.java b/java/code/src/com/redhat/rhn/domain/common/ExceptionMessage.java index 75791bf86340..032b60c0e91a 100644 --- a/java/code/src/com/redhat/rhn/domain/common/ExceptionMessage.java +++ b/java/code/src/com/redhat/rhn/domain/common/ExceptionMessage.java @@ -19,7 +19,9 @@ import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.hibernate.Session; - +import jakarta.persistence.EntityManager; +import jakarta.persistence.NoResultException; +import jakarta.persistence.TypedQuery; /** * RhnException @@ -41,12 +43,19 @@ protected ExceptionMessage() { * @return the associated exception object / null if not found otherwise */ public static ExceptionMessage lookup(long exceptionId) { - Session session = HibernateFactory.getSession(); - Criteria criteria = session.getCriteriaBuilder().createQuery(ExceptionMessage.class); - criteria.add(Restrictions.or( - Restrictions.eq("id", -1 * exceptionId), - Restrictions.eq("id", exceptionId))); - return (ExceptionMessage) criteria.uniqueResult(); + String sql = "SELECT * FROM exception_message WHERE id = :id OR id = :negId"; + + TypedQuery query = HibernateFactory.getSession() + .createNativeQuery(sql, ExceptionMessage.class); + query.setParameter("id", exceptionId); + query.setParameter("negId", -1 * exceptionId); + try { + return query.getSingleResult(); + } catch (NoResultException e) { + return null; + } catch (Exception e) { + throw new RuntimeException("Error retrieving ExceptionMessage", e); + } } /** diff --git a/java/code/src/com/redhat/rhn/domain/config/ConfigurationFactory.java b/java/code/src/com/redhat/rhn/domain/config/ConfigurationFactory.java index 3fc72cf239a9..3ad6997f16ab 100644 --- a/java/code/src/com/redhat/rhn/domain/config/ConfigurationFactory.java +++ b/java/code/src/com/redhat/rhn/domain/config/ConfigurationFactory.java @@ -48,6 +48,8 @@ import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Root; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.NoResultException; /** * ConfigurationFactory. For use when dealing with ConfigChannel, ConfigChannelType, @@ -379,15 +381,25 @@ public static ConfigChannel lookupConfigChannelById(Long id) { * @param cct the config channel type of the config channel. * @return the ConfigChannel found or null if not found. */ - public static ConfigChannel lookupConfigChannelByLabel(String label, - Org org, - ConfigChannelType cct) { - Session session = HibernateFactory.getSession(); - return (ConfigChannel) session.getCriteriaBuilder().createQuery(ConfigChannel.class). - add(Restrictions.eq("org", org)). - add(Restrictions.eq("label", label)). - add(Restrictions.eq("configChannelType", cct)). - uniqueResult(); + public static ConfigChannel lookupConfigChannelByLabel(String label, Org org, + ConfigChannelType cct) { + String sql + = "SELECT * FROM rhnserverconfigchannel WHERE org = :org AND label = :label AND config_channel_type = :cct"; + + TypedQuery query + = getSession().createNativeQuery(sql, ConfigChannel.class); + + query.setParameter("org", org); + query.setParameter("label", label); + query.setParameter("cct", cct); + + try { + return query.getSingleResult(); + } catch (NoResultException e) { + return null; + } catch (Exception e) { + throw new RuntimeException("Error retrieving ConfigChannel", e); + } } /** diff --git a/java/code/src/com/redhat/rhn/domain/credentials/test/CredentialsTest.java b/java/code/src/com/redhat/rhn/domain/credentials/test/CredentialsTest.java index ad456b1eac28..34feb68b9482 100644 --- a/java/code/src/com/redhat/rhn/domain/credentials/test/CredentialsTest.java +++ b/java/code/src/com/redhat/rhn/domain/credentials/test/CredentialsTest.java @@ -50,7 +50,8 @@ public void testSCCCredentials() throws Exception { assertEquals("secret", creds.getPassword()); Optional r = HibernateFactory.getSession() - .createSQLQuery("select password from suseCredentials where username = 'admin';") + .createNativeQuery( + "select password from suseCredentials where username = 'admin';") .uniqueResultOptional(); // this prove that we really store encoded content in DB assertEquals("c2VjcmV0", r.orElseThrow().toString()); diff --git a/java/code/src/com/redhat/rhn/domain/errata/AdvisoryStatusEnumType.java b/java/code/src/com/redhat/rhn/domain/errata/AdvisoryStatusEnumType.java index b09e4106829b..b2f348095fa8 100644 --- a/java/code/src/com/redhat/rhn/domain/errata/AdvisoryStatusEnumType.java +++ b/java/code/src/com/redhat/rhn/domain/errata/AdvisoryStatusEnumType.java @@ -14,6 +14,17 @@ */ package com.redhat.rhn.domain.errata; +import org.hibernate.HibernateException; +import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.usertype.UserType; + +import java.io.Serializable; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; +import java.util.function.Function; + /** * AdvisoryStatusEnumType */ @@ -25,4 +36,18 @@ public AdvisoryStatusEnumType() { super(AdvisoryStatus.class, String.class, AdvisoryStatus::getMetadataValue, s -> AdvisoryStatus.fromMetadata(s).orElse(null)); } + + @Override + public String nullSafeGet(ResultSet var1, int var2, + SharedSessionContractImplementor var3, @Deprecated Object var4) + throws SQLException { + // TODO Hibernate 6 + return null; + }; + + @Override + public void nullSafeSet(PreparedStatement var1, Object var2, int var3, + SharedSessionContractImplementor var4) + throws SQLException { + }; } diff --git a/java/code/src/com/redhat/rhn/domain/errata/CustomEnumType.java b/java/code/src/com/redhat/rhn/domain/errata/CustomEnumType.java index ea30cc832dd1..74c56eb370bf 100644 --- a/java/code/src/com/redhat/rhn/domain/errata/CustomEnumType.java +++ b/java/code/src/com/redhat/rhn/domain/errata/CustomEnumType.java @@ -86,16 +86,15 @@ public int hashCode(Object o) throws HibernateException { return o == null ? 0 : o.hashCode(); } - @Override - public void nullSafeSet(PreparedStatement statement, Object value, int position, - SharedSessionContractImplementor session) throws HibernateException, SQLException { - K jdbcValue = value == null ? null : toDb.apply(enumClass.cast(value)); - if (jdbcValue == null) { - statement.setNull(position, 12); - } - else { - statement.setObject(position, jdbcValue, getSqlType()); - } + public K nullSafeGet(ResultSet var1, int var2, SharedSessionContractImplementor var3, + @Deprecated Object var4) + throws SQLException { + return null; + } + + public void nullSafeSet(PreparedStatement var1, Object var2, int var3, + SharedSessionContractImplementor var4) + throws SQLException { } @Override diff --git a/java/code/src/com/redhat/rhn/domain/kickstart/KickstartFactory.java b/java/code/src/com/redhat/rhn/domain/kickstart/KickstartFactory.java index ceecb0cc93ae..359a03a711ce 100644 --- a/java/code/src/com/redhat/rhn/domain/kickstart/KickstartFactory.java +++ b/java/code/src/com/redhat/rhn/domain/kickstart/KickstartFactory.java @@ -53,7 +53,7 @@ import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Root; - +import jakarta.persistence.TypedQuery; /** * KickstartFactory @@ -914,11 +914,10 @@ public static List lookupKickstartDatasByTree(KickstartableTree t * @return List of KickstartData objects if found */ public static List listAllKickstartData() { - Session session = getSession(); - Criteria c = session.getCriteriaBuilder().createQuery(KickstartData.class); - // Hibernate does not filter out duplicate references by default - c.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY); - return c.list(); + String sql = "SELECT DISTINCT * FROM kickstart_data"; + TypedQuery query = + getSession().createNativeQuery(sql, KickstartData.class); + return query.getResultList(); } /** diff --git a/java/code/src/com/redhat/rhn/domain/matcher/MatcherRunDataFactory.java b/java/code/src/com/redhat/rhn/domain/matcher/MatcherRunDataFactory.java index c92a2e8eb173..ca8790db986e 100644 --- a/java/code/src/com/redhat/rhn/domain/matcher/MatcherRunDataFactory.java +++ b/java/code/src/com/redhat/rhn/domain/matcher/MatcherRunDataFactory.java @@ -20,6 +20,15 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Join; +import jakarta.persistence.criteria.JoinType; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; +import jakarta.persistence.NoResultException; + /** * MatcherRunData hibernate factory. */ @@ -44,9 +53,22 @@ public static void updateData(MatcherRunData newData) { * @return MatcherRunData instance */ public static MatcherRunData getSingle() { - return (MatcherRunData) getSession() - .getCriteriaBuilder().createQuery(MatcherRunData.class) - .uniqueResult(); + CriteriaBuilder cb = getSession().getCriteriaBuilder(); + CriteriaQuery cq = cb.createQuery(MatcherRunData.class); + Root root = cq.from(MatcherRunData.class); + cq.select(root); + + TypedQuery query = getSession().createQuery(cq); + + try { + return query.getSingleResult(); + } + catch (NoResultException e) { + return null; + } + catch (Exception e) { + throw new RuntimeException("Error retrieving MatcherRunData", e); + } } /** diff --git a/java/code/src/com/redhat/rhn/domain/notification/types/SubscriptionWarning.java b/java/code/src/com/redhat/rhn/domain/notification/types/SubscriptionWarning.java index 0e9c76ec8e50..05331dd425a0 100644 --- a/java/code/src/com/redhat/rhn/domain/notification/types/SubscriptionWarning.java +++ b/java/code/src/com/redhat/rhn/domain/notification/types/SubscriptionWarning.java @@ -31,7 +31,7 @@ public class SubscriptionWarning implements NotificationData { * @return boolean **/ public boolean expiresSoon() { - Optional result = getSession().createSQLQuery( + Optional result = getSession().createNativeQuery( "select exists (select name, expires_at, status, subtype " + "from susesccsubscription where subtype != 'internal' " + " and ((status = 'ACTIVE' and expires_at < now() + interval '90 day') " + diff --git a/java/code/src/com/redhat/rhn/domain/product/SUSEProductFactory.java b/java/code/src/com/redhat/rhn/domain/product/SUSEProductFactory.java index 6ae4cf0783cb..3632d780dd41 100644 --- a/java/code/src/com/redhat/rhn/domain/product/SUSEProductFactory.java +++ b/java/code/src/com/redhat/rhn/domain/product/SUSEProductFactory.java @@ -45,6 +45,7 @@ import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Root; +import jakarta.persistence.criteria.Predicate; /** * SUSEProductFactory - the class used to fetch and store @@ -97,8 +98,16 @@ public static void save(SUSEProductSCCRepository productRepo) { * @return a list of all {@link SUSEProductSCCRepository} */ public static List allProductRepos() { - Criteria c = getSession().getCriteriaBuilder().createQuery(SUSEProductSCCRepository.class); - return c.list(); + CriteriaBuilder cb = getSession().getCriteriaBuilder(); + + CriteriaQuery query + = cb.createQuery(SUSEProductSCCRepository.class); + + Root root = query.from(SUSEProductSCCRepository.class); + + query.select(root); + + return getSession().createQuery(query).getResultList(); } /** @@ -113,16 +122,10 @@ public static boolean hasProducts() { * @return map of all {@link SUSEProductSCCRepository} by ID triple */ public static Map, SUSEProductSCCRepository> allProductReposByIds() { - return allProductRepos().stream().collect( - Collectors.toMap( - e -> new Tuple3<>( - e.getRootProduct().getProductId(), - e.getProduct().getProductId(), - e.getRepository().getSccId() - ), - e -> e - ) - ); + return allProductRepos().stream().collect(Collectors.toMap( + e -> new Tuple3<>(e.getRootProduct().getProductId(), + e.getProduct().getProductId(), e.getRepository().getSccId()), + e -> e)); } /** @@ -132,30 +135,26 @@ public static Map, SUSEProductSCCRepository> allProduct * @param channelLabel the channel label * @return list of {@link SUSEProductSCCRepository} */ - public static List lookupPSRByChannelLabel(String channelLabel) { - Session session = getSession(); - Criteria c = session.getCriteriaBuilder().createQuery(SUSEProductSCCRepository.class); - c.add(Restrictions.eq("channelLabel", channelLabel)); - return ((List) c.list()).stream() - .sorted((a, b) -> - RPM_VERSION_COMPARATOR.compare(b.getProduct().getVersion(), a.getProduct().getVersion())) - .collect(Collectors.toList()); - } + public static List lookupPSRByChannelLabel( + String channelLabel) { - /** - * lookup {@link SUSEProductSCCRepository} by given ID triple - * @param rootId root product id - * @param productId product id - * @param repoId repository id - * @return the product/repository item - */ - public static Optional lookupProductRepoByIds(long rootId, long productId, long repoId) { - Session session = getSession(); - Criteria c = session.getCriteriaBuilder().createQuery(SUSEProductSCCRepository.class); - c.add(Restrictions.eq("rootProduct.productId", rootId)); - c.add(Restrictions.eq("product.productId", productId)); - c.add(Restrictions.eq("repository.sccId", repoId)); - return Optional.ofNullable((SUSEProductSCCRepository) c.uniqueResult()); + CriteriaBuilder cb = getSession().getCriteriaBuilder(); + + CriteriaQuery query + = cb.createQuery(SUSEProductSCCRepository.class); + + Root root = query.from(SUSEProductSCCRepository.class); + + Predicate predicate = cb.equal(root.get("channelLabel"), channelLabel); + + query.select(root).where(predicate); + + return ((List) getSession().createQuery(query) + .getResultList()) + .stream() + .sorted((a, b) -> RPM_VERSION_COMPARATOR.compare( + b.getProduct().getVersion(), a.getProduct().getVersion())) + .collect(Collectors.toList()); } /** @@ -181,12 +180,21 @@ public static void remove(SUSEProduct product) { @SuppressWarnings("unchecked") public static void removeAllExcept(Collection products) { if (!products.isEmpty()) { - Collection ids = products.stream().map(SUSEProduct::getId).collect(Collectors.toList()); + Collection ids + = products.stream().map(SUSEProduct::getId).collect(Collectors.toList()); + + CriteriaBuilder cb = getSession().getCriteriaBuilder(); + + CriteriaQuery query = cb.createQuery(SUSEProduct.class); + + Root root = query.from(SUSEProduct.class); + + Predicate predicate = root.get("id").in(ids); - Criteria c = getSession().getCriteriaBuilder().createQuery(SUSEProduct.class); - c.add(Restrictions.not(Restrictions.in("id", ids))); + query.select(root).where(predicate); - for (SUSEProduct product : (List) c.list()) { + for (SUSEProduct product : (List) getSession().createQuery(query) + .list()) { remove(product); } } @@ -458,41 +466,45 @@ public static void remove(SUSEProductSCCRepository productRepo) { public static SUSEProduct findSUSEProduct(String name, String version, String release, String arch, boolean imprecise) { - Criteria c = getSession().getCriteriaBuilder().createQuery(SUSEProduct.class); - c.add(Restrictions.eq("name", name.toLowerCase())); + CriteriaBuilder cb = getSession().getCriteriaBuilder(); + + CriteriaQuery query = cb.createQuery(SUSEProduct.class); + + Root root = query.from(SUSEProduct.class); + + Predicate predicate = cb.equal(root.get("name"), name.toLowerCase()); - Disjunction versionCriterion = Restrictions.disjunction(); if (imprecise || version == null) { - versionCriterion.add(Restrictions.isNull("version")); + predicate = cb.and(predicate, cb.isNull(root.get("version"))); } if (version != null) { - versionCriterion.add(Restrictions.eq("version", version.toLowerCase())); + predicate + = cb.and(predicate, cb.equal(root.get("version"), version.toLowerCase())); } - c.add(versionCriterion); - Disjunction releaseCriterion = Restrictions.disjunction(); if (imprecise || release == null) { - releaseCriterion.add(Restrictions.isNull("release")); + predicate = cb.and(predicate, cb.isNull(root.get("release"))); } if (release != null) { - releaseCriterion.add(Restrictions.eq("release", release.toLowerCase())); + predicate + = cb.and(predicate, cb.equal(root.get("release"), release.toLowerCase())); } - c.add(releaseCriterion); - Disjunction archCriterion = Restrictions.disjunction(); if (imprecise || arch == null) { - archCriterion.add(Restrictions.isNull("arch")); + predicate = cb.and(predicate, cb.isNull(root.get("arch"))); } if (arch != null) { - archCriterion.add(Restrictions.eq("arch", + predicate = cb.and(predicate, cb.equal(root.get("arch"), PackageFactory.lookupPackageArchByLabel(arch))); } - c.add(archCriterion); - c.addOrder(Order.asc("name")).addOrder(Order.asc("version")) - .addOrder(Order.asc("release")).addOrder(Order.asc("arch")); + query.select(root).where(predicate); + + query.orderBy(cb.asc(root.get("name")), cb.asc(root.get("version")), + cb.asc(root.get("release")), cb.asc(root.get("arch"))); + + List result = getSession().createQuery(query).getResultList(); - List result = c.list(); return result.isEmpty() ? null : result.get(0); } @@ -513,10 +525,17 @@ public static SUSEProduct getProductById(Long id) { * @return SUSE product for given productId */ public static SUSEProduct lookupByProductId(long productId) { - Session session = getSession(); - Criteria c = session.getCriteriaBuilder().createQuery(SUSEProduct.class); - c.add(Restrictions.eq("productId", productId)); - return (SUSEProduct) c.uniqueResult(); + CriteriaBuilder cb = getSession().getCriteriaBuilder(); + + CriteriaQuery query = cb.createQuery(SUSEProduct.class); + + Root root = query.from(SUSEProduct.class); + + Predicate predicate = cb.equal(root.get("productId"), productId); + + query.select(root).where(predicate); + + return (SUSEProduct) getSession().createQuery(query).uniqueResult(); } /** @@ -542,17 +561,6 @@ public static List allRecommendedExtensions() { return getSession().createQuery(criteria).getResultList(); } - /** - * Find all {@link SUSEProductChannel} relationships. - * @return list of SUSE product channel relationships - */ - @SuppressWarnings("unchecked") - public static List findAllSUSEProductChannels() { - Session session = getSession(); - Criteria c = session.getCriteriaBuilder().createQuery(SUSEProductChannel.class); - return c.list(); - } - /** * Find extensions for the product * @param root the root product @@ -560,20 +568,27 @@ public static List findAllSUSEProductChannels() { * @param ext the extension product * @return the Optional of {@link SUSEProductExtension} product */ - public static Optional findSUSEProductExtension(SUSEProduct root, - SUSEProduct base, - SUSEProduct ext) { - Session session = getSession(); + public static Optional findSUSEProductExtension( + SUSEProduct rootProduct, SUSEProduct base, SUSEProduct ext) { + + CriteriaBuilder cb = getSession().getCriteriaBuilder(); + + CriteriaQuery query + = cb.createQuery(SUSEProductExtension.class); + + Root root = query.from(SUSEProductExtension.class); + + Predicate predicate = cb.equal(root.get("rootProduct"), rootProduct); + predicate = cb.and(predicate, cb.equal(root.get("baseProduct"), base)); + predicate = cb.and(predicate, cb.equal(root.get("extensionProduct"), ext)); + + query.select(root).where(predicate); + + SUSEProductExtension result = getSession().createQuery(query).uniqueResult(); - Criteria c = session.getCriteriaBuilder().createQuery(SUSEProductExtension.class) - .add(Restrictions.eq("rootProduct", root)) - .add(Restrictions.eq("baseProduct", base)) - .add(Restrictions.eq("extensionProduct", ext)); - SUSEProductExtension result = (SUSEProductExtension) c.uniqueResult(); if (result == null) { return Optional.empty(); - } - else { + } else { return Optional.of(result); } } @@ -584,9 +599,17 @@ public static Optional findSUSEProductExtension(SUSEProduc */ @SuppressWarnings("unchecked") public static List findAllSUSEProductExtensions() { - Session session = getSession(); - Criteria c = session.getCriteriaBuilder().createQuery(SUSEProductExtension.class); - return c.list(); + CriteriaBuilder cb = getSession().getCriteriaBuilder(); + + CriteriaQuery query + = cb.createQuery(SUSEProductExtension.class); + + Root root = query.from(SUSEProductExtension.class); + + query.select(root); + + return getSession().createQuery(query).getResultList(); + } /** @@ -609,13 +632,22 @@ public static List findAllExtensionProductsForRootOf(SUSEProduct ba * @return list of product extension of the given product */ @SuppressWarnings("unchecked") - public static List findAllProductExtensionsOf(SUSEProduct product, SUSEProduct root) { - Session session = getSession(); + public static List findAllProductExtensionsOf(SUSEProduct product, SUSEProduct rootProduct) { + + CriteriaBuilder cb = getSession().getCriteriaBuilder(); + + CriteriaQuery query + = cb.createQuery(SUSEProductExtension.class); + + Root root = query.from(SUSEProductExtension.class); + + Predicate predicate = cb.equal(root.get("rootProduct"), rootProduct); + predicate = cb.and(predicate, cb.equal(root.get("baseProduct"), product)); + + query.select(root).where(predicate); + + return getSession().createQuery(query).getResultList(); - Criteria c = session.getCriteriaBuilder().createQuery(SUSEProductExtension.class) - .add(Restrictions.eq("rootProduct", root)) - .add(Restrictions.eq("baseProduct", product)); - return c.list(); } /** @@ -657,7 +689,15 @@ public static List findAllRootProductsOf(SUSEProduct prd) { */ @SuppressWarnings("unchecked") public static List findAllSUSEProducts() { - return getSession().getCriteriaBuilder().createQuery(SUSEProduct.class).list(); + CriteriaBuilder cb = getSession().getCriteriaBuilder(); + + CriteriaQuery query = cb.createQuery(SUSEProduct.class); + + Root root = query.from(SUSEProduct.class); + + query.select(root); + + return getSession().createQuery(query).getResultList(); } /** @@ -687,21 +727,27 @@ public static List findAllExtensionsOfRootProduct(SUSEProduct root) public static Optional findInstalledProduct(String name, String version, String release, PackageArch arch, boolean isBaseProduct) { - Criteria c = getSession().getCriteriaBuilder().createQuery(InstalledProduct.class); - c.add(Restrictions.eq("name", name)); - c.add(Restrictions.eq("version", version)); + CriteriaBuilder cb = getSession().getCriteriaBuilder(); + + CriteriaQuery query = cb.createQuery(InstalledProduct.class); + + Root root = query.from(InstalledProduct.class); + + Predicate predicate = cb.equal(root.get("name"), name.toLowerCase()); + predicate = cb.and(predicate, cb.equal(root.get("version"), version.toLowerCase())); + predicate = cb.and(predicate, cb.equal(root.get("arch"), arch)); + predicate = cb.and(predicate, cb.equal(root.get("baseproduct"), isBaseProduct)); if (StringUtils.isEmpty(release)) { - c.add(Restrictions.isNull("release")); - } - else { - c.add(Restrictions.eq("release", release)); + predicate = cb.and(predicate, cb.isNull(root.get("release"))); + } else { + predicate = cb.and(predicate, cb.equal(root.get("release"), release)); } - c.add(Restrictions.eq("arch", arch)); - c.add(Restrictions.eq("baseproduct", isBaseProduct)); - c.addOrder(Order.asc("name")).addOrder(Order.asc("version")) - .addOrder(Order.asc("release")).addOrder(Order.asc("arch")); - return c.list().stream().findFirst(); + query.select(root).where(predicate); + query.orderBy(cb.asc(root.get("name")), cb.asc(root.get("version")), + cb.asc(root.get("release")), cb.asc(root.get("arch"))); + + return getSession().createQuery(query).getResultList().stream().findFirst(); } /** diff --git a/java/code/src/com/redhat/rhn/domain/scc/SCCCachingFactory.java b/java/code/src/com/redhat/rhn/domain/scc/SCCCachingFactory.java index d6da2f157abb..37cce2464c1d 100644 --- a/java/code/src/com/redhat/rhn/domain/scc/SCCCachingFactory.java +++ b/java/code/src/com/redhat/rhn/domain/scc/SCCCachingFactory.java @@ -56,6 +56,10 @@ import jakarta.persistence.criteria.CriteriaDelete; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Root; +import jakarta.persistence.EntityManager; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.Query; +import jakarta.persistence.NoResultException; /** * Factory class for populating and reading from SCC caching tables. @@ -175,9 +179,10 @@ public static SCCSubscription saveJsonSubscription(SCCSubscriptionJson jsonSub, @SuppressWarnings("unchecked") public static List lookupSubscriptions() { log.debug("Retrieving subscriptions from cache"); - Session session = getSession(); - Criteria c = session.getCriteriaBuilder().createQuery(SCCSubscription.class); - return c.list(); + String sql = "SELECT * FROM suseSCCSubscription"; + TypedQuery query + = getSession().createNativeQuery(sql, SCCSubscription.class); + return query.getResultList(); } /** @@ -189,20 +194,28 @@ public static SCCSubscription lookupSubscriptionBySccId(Long id) { if (id == null) { return null; } - Session session = getSession(); - Criteria c = session.getCriteriaBuilder().createQuery(SCCSubscription.class); - c.add(Restrictions.eq("sccId", id)); - return (SCCSubscription) c.uniqueResult(); + + // Define the SQL query + String sql = "SELECT * FROM suseSCCSubscription WHERE scc_id = :sccId"; + + // Create and execute the query + TypedQuery query + = getSession().createNativeQuery(sql, SCCSubscription.class); + query.setParameter("sccId", id); + try { + return query.getSingleResult(); + } catch (NoResultException e) { + return null; + } } /** * Clear all subscriptions from the database. */ public static void clearSubscriptions() { - CriteriaBuilder builder = getSession().getCriteriaBuilder(); - CriteriaDelete delete = builder.createCriteriaDelete(SCCSubscription.class); - delete.from(SCCSubscription.class); - getSession().createQuery(delete).executeUpdate(); - + EntityManager em = getSession(); // Obtain EntityManager + String sql = "DELETE FROM suseSCCSubscription"; + Query query = em.createNativeQuery(sql); + query.executeUpdate(); } /** @@ -212,9 +225,12 @@ public static void clearSubscriptions() { @SuppressWarnings("unchecked") public static List lookupOrderItems() { log.debug("Retrieving orderItems from cache"); - Session session = getSession(); - Criteria c = session.getCriteriaBuilder().createQuery(SCCOrderItem.class); - return c.list(); + + String sql = "SELECT * FROM suseSCCOrderItem"; + + TypedQuery query + = getSession().createNativeQuery(sql, SCCOrderItem.class); + return query.getResultList(); } /** diff --git a/java/code/src/com/redhat/rhn/domain/server/MinionServerFactory.java b/java/code/src/com/redhat/rhn/domain/server/MinionServerFactory.java index bf20d6f4c7e4..83f610bbcd9e 100644 --- a/java/code/src/com/redhat/rhn/domain/server/MinionServerFactory.java +++ b/java/code/src/com/redhat/rhn/domain/server/MinionServerFactory.java @@ -33,6 +33,7 @@ import java.math.BigDecimal; import java.util.List; import java.util.Optional; +import java.util.Arrays; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -41,8 +42,10 @@ import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Join; import jakarta.persistence.criteria.JoinType; +import jakarta.persistence.TypedQuery; import jakarta.persistence.criteria.Predicate; import jakarta.persistence.criteria.Root; +import jakarta.persistence.NoResultException; /** * MinionFactory - the singleton class used to fetch and store @@ -54,15 +57,22 @@ public class MinionServerFactory extends HibernateFactory { /** * Lookup all Servers that belong to an org + * * @param orgId the org id to search for * @return the Server found */ public static List lookupByOrg(Long orgId) { - return HibernateFactory.getSession() - .getCriteriaBuilder().createQuery(MinionServer.class) - .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY) - .add(Restrictions.eq("org.id", orgId)) - .list(); + if (orgId == null) { + return List.of(); + } + + String sql = "SELECT DISTINCT * FROM minion_server WHERE org_id = :orgId"; + + TypedQuery query + = getSession().createNativeQuery(sql, MinionServer.class); + query.setParameter("orgId", orgId); + + return query.getResultList(); } /** @@ -88,10 +98,22 @@ protected Logger getLogger() { * @return server corresponding to the given machine_id */ public static Optional findByMachineId(String machineId) { - Session session = getSession(); - Criteria criteria = session.getCriteriaBuilder().createQuery(MinionServer.class); - criteria.add(Restrictions.eq("machineId", machineId)); - return Optional.ofNullable((MinionServer) criteria.uniqueResult()); + if (machineId == null) { + return Optional.empty(); + } + String sql = "SELECT * FROM minion_server WHERE machine_id = :machineId"; + + TypedQuery query + = getSession().createNativeQuery(sql, MinionServer.class); + query.setParameter("machineId", machineId); + + try { + // Attempt to get a single result + MinionServer result = query.getSingleResult(); + return Optional.ofNullable(result); + } catch (NoResultException e) { + return Optional.empty(); // Return empty if no result is found + } } /** @@ -101,10 +123,11 @@ public static Optional findByMachineId(String machineId) { * @return server corresponding to the given machine_id */ public static Optional findByMinionId(String minionId) { - Session session = getSession(); - Criteria criteria = session.getCriteriaBuilder().createQuery(MinionServer.class); - criteria.add(Restrictions.eq("minionId", minionId)); - return Optional.ofNullable((MinionServer) criteria.uniqueResult()); + String sql = "SELECT * FROM minion_server WHERE minion_id = :minionId"; + MinionServer result + = (MinionServer) getSession().createNativeQuery(sql, MinionServer.class) + .setParameter("minionId", minionId).getSingleResult(); + return Optional.ofNullable(result); } /** @@ -114,23 +137,10 @@ public static Optional findByMinionId(String minionId) { */ @SuppressWarnings("unchecked") public static List listMinions() { - return getSession().getCriteriaBuilder().createQuery(MinionServer.class) - .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY) - .list(); - } - - /** - * Find all minion ids that belong to an organization. - * - * @param orgId the organization id - * @return a list of minions ids belonging to the given organization - */ - public static List findMinionIdsByOrgId(Long orgId) { - return getSession().getCriteriaBuilder().createQuery(MinionServer.class) - .setProjection(Projections.property("minionId")) - .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY) - .add(Restrictions.eq("org.id", orgId)) - .list(); + String sql = "SELECT DISTINCT * FROM minion_server"; + TypedQuery query + = getSession().createNativeQuery(sql, MinionServer.class); + return query.getResultList(); } /** @@ -163,12 +173,13 @@ public static List lookupByMinionIds(Set minionIds) { //NOTE: this is needed since empty sets produce invalid sql statemensts if (minionIds.isEmpty()) { return emptyList(); - } - else { - return HibernateFactory.getSession().getCriteriaBuilder().createQuery(MinionServer.class) - .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY) - .add(Restrictions.in("minionId", minionIds)) - .list(); + } else { + CriteriaBuilder cb = getSession().getCriteriaBuilder(); + CriteriaQuery query = cb.createQuery(MinionServer.class); + Root root = query.from(MinionServer.class); + Predicate predicate = cb.equal(root.get("minionId"), minionIds); + query.select(root).where(predicate).distinct(true); + return getSession().createQuery(query).getResultList(); } } @@ -177,11 +188,13 @@ public static List lookupByMinionIds(Set minionIds) { * @return map of SSH minion id and its contact method */ public static List listSSHMinions() { - return HibernateFactory.getSession().getCriteriaBuilder().createQuery(MinionServer.class) - .createAlias("contactMethod", "m") - .add(Restrictions.in("m.label", - "ssh-push", "ssh-push-tunnel")) - .list(); + String sql = "SELECT ms.* FROM minion_server ms " + + "JOIN contact_method cm ON ms.contact_method_id = cm.id " + + "WHERE cm.label IN (:labels)"; + + return HibernateFactory.getSession().createNativeQuery(sql, MinionServer.class) + .setParameter("labels", Arrays.asList("ssh-push", "ssh-push-tunnel")) + .getResultList(); } /** diff --git a/java/code/src/com/redhat/rhn/domain/server/PinnedSubscriptionFactory.java b/java/code/src/com/redhat/rhn/domain/server/PinnedSubscriptionFactory.java index c99a31752d02..1ef895d35104 100644 --- a/java/code/src/com/redhat/rhn/domain/server/PinnedSubscriptionFactory.java +++ b/java/code/src/com/redhat/rhn/domain/server/PinnedSubscriptionFactory.java @@ -21,6 +21,12 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.TypedQuery; + import java.util.List; @@ -68,7 +74,11 @@ protected Logger getLogger() { */ @SuppressWarnings("unchecked") public List listPinnedSubscriptions() { - return getSession().getCriteriaBuilder().createQuery(PinnedSubscription.class).list(); + String sql = "SELECT * FROM susePinnedSubscription"; + + TypedQuery query + = getSession().createNativeQuery(sql, PinnedSubscription.class); + return query.getResultList(); } /** @@ -105,10 +115,10 @@ public void cleanStalePins() { * @return PinnedSubscription object */ public PinnedSubscription lookupById(Long id) { + String sql = "SELECT * FROM susePinnedSubscription WHERE id = :id"; return (PinnedSubscription) getSession() - .getCriteriaBuilder().createQuery(PinnedSubscription.class) - .add(Restrictions.eq("id", id)) - .uniqueResult(); + .createNativeQuery(sql, PinnedSubscription.class).setParameter("id", id) + .getSingleResult(); } /** @@ -119,10 +129,17 @@ public PinnedSubscription lookupById(Long id) { */ public PinnedSubscription lookupBySystemIdAndSubscriptionId(Long systemId, Long subscriptionId) { - return (PinnedSubscription) getSession() - .getCriteriaBuilder().createQuery(PinnedSubscription.class) - .add(Restrictions.eq("systemId", systemId)) - .add(Restrictions.eq("subscriptionId", subscriptionId)) - .uniqueResult(); + + CriteriaBuilder cb = getSession().getCriteriaBuilder(); + + CriteriaQuery query = cb.createQuery(PinnedSubscription.class); + + Root root = query.from(PinnedSubscription.class); + + Predicate predicate = cb.equal(root.get("systemId"), systemId); + predicate = cb.and(predicate, cb.equal(root.get("subscriptionId"), subscriptionId)); + + query.select(root).where(predicate); + return getSession().createQuery(query).uniqueResult(); } } diff --git a/java/code/src/com/redhat/rhn/domain/server/ServerFactory.java b/java/code/src/com/redhat/rhn/domain/server/ServerFactory.java index 4bea20e6ade9..0b36fa94a3bd 100644 --- a/java/code/src/com/redhat/rhn/domain/server/ServerFactory.java +++ b/java/code/src/com/redhat/rhn/domain/server/ServerFactory.java @@ -58,7 +58,6 @@ import jakarta.persistence.criteria.CriteriaQuery; import org.hibernate.Session; import org.hibernate.query.Query; -import org.hibernate.sql.Restriction; import org.hibernate.type.StandardBasicTypes; import java.util.ArrayList; @@ -79,6 +78,7 @@ import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.JoinType; +import jakarta.persistence.TypedQuery; import jakarta.persistence.criteria.Path; import jakarta.persistence.criteria.Root; @@ -199,53 +199,42 @@ public static List lookupStorageDevicesByServer(Server s) { @SuppressWarnings("unchecked") public static Optional lookupProxyServer(String name) { boolean nameIsFullyQualified = name.contains("."); - if (!nameIsFullyQualified) { - log.warn("Specified master name \"{}\" is not fully-qualified,proxy attachment might not be correct", name); - log.warn("Please use a FQDN in /etc/salt/minion.d/susemanager.conf"); - } - - DetachedCriteria proxyIds = DetachedCriteria.forClass(ProxyInfo.class) - .setProjection(Projections.property("server.id")); - - Optional result = findByFqdn(name); + Optional result = Optional.empty(); + result = findByFqdn(name); if (result.isPresent()) { return result; } - result = HibernateFactory.getSession() - .getCriteriaBuilder().createQuery(Server.class) - .add(SYSTEM_QUERIES.propertyIn("id", proxyIds)) - .add(Restriction.eq("hostname", name)) - .list() - .stream() - .findFirst(); - + String sql + = "SELECT * FROM rhnServer WHERE hostname = :hostname AND id IN (SELECT server_id FROM rhnProxyInfo)"; + TypedQuery query + = HibernateFactory.getSession().createNativeQuery(sql, Server.class); + query.setParameter("hostname", name); + List servers = query.getResultList(); + result = servers.stream().findFirst(); if (result.isPresent()) { return result; } - // precise search did not work, try imprecise if (nameIsFullyQualified) { - String srippedHostname = name.split("\\.")[0]; - - return HibernateFactory.getSession() - .getCriteriaBuilder().createQuery(Server.class) - .add(SYSTEM_QUERIES.propertyIn("id", proxyIds)) - .add(Restrictions.eq("hostname", srippedHostname)) - .list() - .stream() - .findFirst(); - } - else { - return HibernateFactory.getSession().getCriteriaBuilder() - .createQuery(Server.class) - .add(SYSTEM_QUERIES.propertyIn("id", proxyIds)) - .add(Restrictions.like("hostname", name + ".", MatchMode.START)) - .list() - .stream() - .findFirst(); + String strippedHostname = name.split("\\.")[0]; + sql = "SELECT * FROM rhnServer WHERE hostname = :hostname AND id IN (SELECT server_id FROM rhnProxyInfo)"; + query = HibernateFactory.getSession().createNativeQuery(sql, Server.class); + query.setParameter("hostname", strippedHostname); + servers = query.getResultList(); + result = servers.stream().findFirst(); + if (result.isPresent()) { + return result; + } + } else { + sql = "SELECT * FROM rhnServer WHERE hostname LIKE :hostnamePattern AND id IN (SELECT server_id FROM rhnProxyInfo)"; + query = HibernateFactory.getSession().createNativeQuery(sql, Server.class); + query.setParameter("hostnamePattern", name + "%"); + servers = query.getResultList(); + result = servers.stream().findFirst(); } + return result; } /** @@ -753,9 +742,11 @@ public static Server lookupById(Long id) { */ @SuppressWarnings("unchecked") public static Server lookupForeignSystemByDigitalServerId(String id) { - CriteriaQuery criteria = getSession().getCriteriaBuilder().createQuery(Server.class); - criteria.add(Restrictions.eq("digitalServerId", id)); - for (Server server : (List) criteria.list()) { + String sql = "SELECT * FROM Server WHERE rhnServer = :id"; + List servers = getSession().createNativeQuery(sql, Server.class) + .setParameter("id", id).getResultList(); + + for (Server server : servers) { if (server.hasEntitlement(EntitlementManager.getByName("foreign_entitled"))) { return server; } @@ -1337,10 +1328,17 @@ public static ContactMethod findContactMethodById(Long id) { * @return contact method with the given label */ public static ContactMethod findContactMethodByLabel(String label) { - Session session = getSession(); - Criteria criteria = session.getCriteriaBuilder().createQuery(ContactMethod.class); - criteria.add(Restrictions.eq("label", label)); - return (ContactMethod) criteria.uniqueResult(); + String sql = "SELECT * FROM suseServerContactMethod WHERE label = :label"; + TypedQuery query + = getSession().createNativeQuery(sql, ContactMethod.class); + query.setParameter("label", label); + + // Execute the query and get the result + List results = query.getResultList(); + if (!results.isEmpty()) { + return results.get(0); // Get the first result if available + } + return null; } /** @@ -1496,10 +1494,10 @@ public static void delete(Device device) { * @return the server if any */ public static Optional findByMachineId(String machineId) { - Session session = getSession(); - Criteria criteria = session.getCriteriaBuilder().createQuery(Server.class); - criteria.add(Restrictions.eq("machineId", machineId)); - return Optional.ofNullable((Server) criteria.uniqueResult()); + String jpql = "SELECT s FROM rhnServer s WHERE s.machineId = :machineId"; + TypedQuery query = getSession().createQuery(jpql, Server.class); + query.setParameter("machineId", machineId); + return Optional.ofNullable(query.getResultStream().findFirst().orElse(null)); } /** @@ -1508,9 +1506,12 @@ public static Optional findByMachineId(String machineId) { * @return a {@link Capability} with the given name */ public static Optional findCapability(String name) { - Criteria criteria = getSession().getCriteriaBuilder().createQuery(Capability.class); - criteria.add(Restrictions.eq("name", name)); - return Optional.ofNullable((Capability) criteria.uniqueResult()); + String sql = "SELECT * FROM Capability WHERE name = :name"; + Capability capability + = (Capability) getSession().createNativeQuery(sql, Capability.class) + .setParameter("name", name).uniqueResult(); + return Optional.ofNullable(capability); + } /** diff --git a/java/code/src/com/redhat/rhn/domain/server/test/VirtualInstanceFactoryTest.java b/java/code/src/com/redhat/rhn/domain/server/test/VirtualInstanceFactoryTest.java index e8de6022ed3b..c02b6e6a1294 100644 --- a/java/code/src/com/redhat/rhn/domain/server/test/VirtualInstanceFactoryTest.java +++ b/java/code/src/com/redhat/rhn/domain/server/test/VirtualInstanceFactoryTest.java @@ -46,6 +46,11 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; +import jakarta.persistence.criteria.Predicate; + import java.util.HashSet; import java.util.List; import java.util.Set; @@ -296,12 +301,19 @@ public void testLookupGuestByUuid() throws Exception { @Test public void testLookupHostVirtualInstanceByHostId() throws Exception { - Server host = ServerTestUtils.createVirtHostWithGuest(systemEntitlementManager); + Server host = ServerTestUtils + .createVirtHostWithGuest(systemEntitlementManager); + CriteriaBuilder cb = HibernateFactory.getSession().getCriteriaBuilder(); + CriteriaQuery query + = cb.createQuery(VirtualInstance.class); + + Root root = query.from(VirtualInstance.class); + + Predicate predicate = cb.equal(root.get("hostSystem"), host); + predicate = cb.and(predicate, cb.equal(root.get("guestSystem"), null)); - VirtualInstance fromDb = (VirtualInstance) HibernateFactory.getSession() - .getCriteriaBuilder().createQuery(VirtualInstance.class) - .add(Restrictions.eq("hostSystem", host)) - .add(Restrictions.eq("guestSystem", null)) + query.select(root).where(predicate); + VirtualInstance fromDb = HibernateFactory.getSession().createQuery(query) .uniqueResult(); VirtualInstance hostVirtInstance = VirtualInstanceFactory.getInstance() diff --git a/java/code/src/com/redhat/rhn/domain/server/virtualhostmanager/VirtualHostManagerFactory.java b/java/code/src/com/redhat/rhn/domain/server/virtualhostmanager/VirtualHostManagerFactory.java index 5d48847f4de3..4f6fecc2bd90 100644 --- a/java/code/src/com/redhat/rhn/domain/server/virtualhostmanager/VirtualHostManagerFactory.java +++ b/java/code/src/com/redhat/rhn/domain/server/virtualhostmanager/VirtualHostManagerFactory.java @@ -48,6 +48,7 @@ import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Root; +import jakarta.persistence.criteria.Predicate; /** * Singleton representing Virtual Host Manager hibernate factory. @@ -104,10 +105,12 @@ protected Logger getLogger() { * exist */ public VirtualHostManager lookupByLabel(String label) { - return (VirtualHostManager) getSession() - .getCriteriaBuilder().createQuery(VirtualHostManager.class) - .add(Restrictions.eq("label", label)) - .uniqueResult(); + CriteriaBuilder cb = getSession().getCriteriaBuilder(); + CriteriaQuery query = cb.createQuery(VirtualHostManager.class); + Root root = query.from(VirtualHostManager.class); + Predicate predicate = cb.equal(root.get("label"), label); + query.select(root).where(predicate); + return getSession().createQuery(query).uniqueResult(); } /** @@ -128,11 +131,17 @@ public Optional lookupById(Long id) { * exist */ public VirtualHostManager lookupByIdAndOrg(Long id, Org org) { - return (VirtualHostManager) getSession() - .getCriteriaBuilder().createQuery(VirtualHostManager.class) - .add(Restrictions.eq("org", org)) - .add(Restrictions.eq("id", id)) - .uniqueResult(); + CriteriaBuilder cb = getSession().getCriteriaBuilder(); + + CriteriaQuery query = cb.createQuery(VirtualHostManager.class); + + Root root = query.from(VirtualHostManager.class); + + Predicate predicate = cb.equal(root.get("org"), org); + predicate = cb.and(predicate, cb.equal(root.get("id"), id)); + + query.select(root).where(predicate); + return getSession().createQuery(query).uniqueResult(); } /** @@ -161,11 +170,17 @@ public List lookupByIdsAndOrg(List ids, Org org) { * exist */ public VirtualHostManager lookupByLabelAndOrg(String label, Org org) { - return (VirtualHostManager) getSession() - .getCriteriaBuilder().createQuery(VirtualHostManager.class) - .add(Restrictions.eq("org", org)) - .add(Restrictions.eq("label", label)) - .uniqueResult(); + CriteriaBuilder cb = getSession().getCriteriaBuilder(); + + CriteriaQuery query = cb.createQuery(VirtualHostManager.class); + + Root root = query.from(VirtualHostManager.class); + + Predicate predicate = cb.equal(root.get("org"), org); + predicate = cb.and(predicate, cb.equal(root.get("label"), label)); + + query.select(root).where(predicate); + return getSession().createQuery(query).uniqueResult(); } /** @@ -175,11 +190,18 @@ public VirtualHostManager lookupByLabelAndOrg(String label, Org org) { */ @SuppressWarnings("unchecked") public List listVirtualHostManagers(Org org) { - return getSession() - .getCriteriaBuilder().createQuery(VirtualHostManager.class) - .add(Restrictions.eq("org", org)) - .addOrder(Order.asc("label")) - .list(); + + CriteriaBuilder cb = getSession().getCriteriaBuilder(); + + CriteriaQuery query = cb.createQuery(VirtualHostManager.class); + + Root root = query.from(VirtualHostManager.class); + + Predicate predicate = cb.equal(root.get("org"), org); + + query.select(root).where(predicate); + query.orderBy(cb.asc(root.get("label"))); + return getSession().createQuery(query).getResultList(); } /** @@ -188,9 +210,15 @@ public List listVirtualHostManagers(Org org) { */ @SuppressWarnings("unchecked") public List listVirtualHostManagers() { - return getSession() - .getCriteriaBuilder().createQuery(VirtualHostManager.class) - .list(); + CriteriaBuilder cb = getSession().getCriteriaBuilder(); + + CriteriaQuery query = cb.createQuery(VirtualHostManager.class); + + Root root = query.from(VirtualHostManager.class); + + query.select(root); + + return getSession().createQuery(query).getResultList(); } /** @@ -471,10 +499,20 @@ private VHMCredentials createCredentialsFromParams(Map params) { */ public Optional lookupNodeInfoByIdentifier( String identifier) { - VirtualHostManagerNodeInfo result = (VirtualHostManagerNodeInfo) getSession() - .getCriteriaBuilder().createQuery(VirtualHostManagerNodeInfo.class) - .add(Restrictions.eq("identifier", identifier)) - .uniqueResult(); + + CriteriaBuilder cb = getSession().getCriteriaBuilder(); + + CriteriaQuery query = + cb.createQuery(VirtualHostManagerNodeInfo.class); + + Root root = + query.from(VirtualHostManagerNodeInfo.class); + + Predicate predicate = cb.equal(root.get("identifier"), identifier); + + query.select(root).where(predicate); + + VirtualHostManagerNodeInfo result = getSession().createQuery(query).uniqueResult(); return Optional.ofNullable(result); } diff --git a/java/code/src/com/redhat/rhn/domain/state/StateFactory.java b/java/code/src/com/redhat/rhn/domain/state/StateFactory.java index 1540a4c740a3..5e5253d21eff 100644 --- a/java/code/src/com/redhat/rhn/domain/state/StateFactory.java +++ b/java/code/src/com/redhat/rhn/domain/state/StateFactory.java @@ -28,6 +28,13 @@ import java.util.Optional; import java.util.Set; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; +import jakarta.persistence.criteria.Subquery; +import jakarta.persistence.EntityManager; +import jakarta.persistence.TypedQuery; + /** * Factory class for working with states. */ @@ -189,14 +196,26 @@ public static Optional> latestConfigChannels(Org org) { private static Optional latestRevision( Class revisionType, String field, Object bean) { - DetachedCriteria maxQuery = DetachedCriteria.forClass(revisionType) - .add(Restrictions.eq(field, bean)) - .setProjection(Projections.max("id")); - T revision = (T) getSession() - .getCriteriaBuilder().createQuery(revisionType) - .add(Restrictions.eq(field, bean)) - .add(Property.forName("id").eq(maxQuery)) - .uniqueResult(); + // Get the CriteriaBuilder + CriteriaBuilder cb = getSession().getCriteriaBuilder(); + + // Create the main query + CriteriaQuery query = cb.createQuery(revisionType); + Root root = query.from(revisionType); + + // Create a subquery to get the maximum ID + Subquery subquery = query.subquery(Long.class); + Root subRoot = subquery.from(revisionType); + subquery.select(cb.max(subRoot.get("id"))) + .where(cb.equal(subRoot.get(field), bean)); + + // Add the subquery result as a restriction in the main query + query.select(root).where(cb.equal(root.get(field), bean), + cb.equal(root.get("id"), subquery)); + + // Execute the query + T revision = getSession().createQuery(query).getSingleResult(); + return Optional.ofNullable(revision); } diff --git a/java/code/src/com/redhat/rhn/domain/user/UserFactory.java b/java/code/src/com/redhat/rhn/domain/user/UserFactory.java index ddd4298e923d..e993ce926f8d 100644 --- a/java/code/src/com/redhat/rhn/domain/user/UserFactory.java +++ b/java/code/src/com/redhat/rhn/domain/user/UserFactory.java @@ -446,7 +446,7 @@ public void syncServerGroupPerms(User usr) { public static RhnTimeZone getTimeZone(int id) { Session session = HibernateFactory.getSession(); return (RhnTimeZone) session.getNamedQuery("RhnTimeZone.loadTimeZoneById") - .setInteger("tid", id) + .setParameter("tid", id) //Retrieve from cache if there .setCacheable(true) .uniqueResult(); diff --git a/java/code/src/com/redhat/rhn/frontend/xmlrpc/contentmgmt/ContentManagementHandler.java b/java/code/src/com/redhat/rhn/frontend/xmlrpc/contentmgmt/ContentManagementHandler.java index 983a08f4835f..55015290f0a4 100644 --- a/java/code/src/com/redhat/rhn/frontend/xmlrpc/contentmgmt/ContentManagementHandler.java +++ b/java/code/src/com/redhat/rhn/frontend/xmlrpc/contentmgmt/ContentManagementHandler.java @@ -58,6 +58,15 @@ import java.util.Optional; import java.util.stream.Collectors; +import com.redhat.rhn.common.hibernate.HibernateFactory; +import jakarta.persistence.EntityManager; +import jakarta.persistence.NoResultException; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.Predicate; + /** * Content Management XMLRPC handler * @@ -643,10 +652,29 @@ public ContentFilter createFilter(User loggedInUser, String name, String rule, S }); ContentFilter.Rule ruleObj = ContentFilter.Rule.lookupByLabel(rule); - ContentFilter.EntityType entityTypeObj = ContentFilter.EntityType.lookupByLabel(entityType); - FilterCriteria criteriaObj = getCriteriaBuilder().createQuery(criteria).orElseThrow( - () -> new InvalidArgsException("criteria must be specified") - ); + ContentFilter.EntityType entityTypeObj = + ContentFilter.EntityType.lookupByLabel(entityType); + + CriteriaBuilder cb = HibernateFactory.getSession().getCriteriaBuilder(); + + CriteriaQuery cq = cb.createQuery(FilterCriteria.class); + Root root = cq.from(FilterCriteria.class); + + Predicate[] predicates = criteria.entrySet().stream() + .map(entry -> cb.equal(root.get(entry.getKey()), entry.getValue())) + .toArray(Predicate[]::new); + + cq.where(predicates); + + FilterCriteria criteriaObj; + try { + TypedQuery query = + HibernateFactory.getSession().createQuery(cq); + criteriaObj = query.getSingleResult(); + } + catch (NoResultException e) { + throw new InvalidArgsException("Criteria must be specified"); + } try { return contentManager.createFilter(name, ruleObj, entityTypeObj, criteriaObj, loggedInUser); @@ -710,41 +738,49 @@ public List createAppStreamFilters(User loggedInUser, String pref * @throws EntityNotExistsFaultException when Filter is not found * @return the updated {@link ContentFilter} * - * @apidoc.doc Update a Content Filter - * #paragraph_end() - * #paragraph() - * See also: createFilter(), listFilterCriteria() + * @apidoc.doc Update a Content Filter #paragraph_end() #paragraph() See + * also: createFilter(), listFilterCriteria() * @apidoc.param #session_key() * @apidoc.param #param_desc("int", "filterId", "Filter ID") * @apidoc.param #param_desc("string", "name", "New filter name") - * @apidoc.param #param_desc("string", "rule", "New filter rule ('deny' or 'allow')") - * @apidoc.param - * #struct_begin("criteria") - * #prop_desc("string", "matcher", "The matcher type of the filter (e.g. 'contains')") - * #prop_desc("string", "field", "The entity field to match (e.g. 'name'") - * #prop_desc("string", "value", "The field value to match (e.g. 'kernel')") - * #struct_end() + * @apidoc.param #param_desc("string", "rule", "New filter rule ('deny' or + * 'allow')") + * @apidoc.param #struct_begin("criteria") #prop_desc("string", "matcher", + * "The matcher type of the filter (e.g. 'contains')") #prop_desc("string", + * "field", "The entity field to match (e.g. 'name'") #prop_desc("string", + * "value", "The field value to match (e.g. 'kernel')") #struct_end() * @apidoc.returntype $ContentFilterSerializer */ - public ContentFilter updateFilter(User loggedInUser, Integer filterId, String name, String rule, - Map criteria) { + public ContentFilter updateFilter(User loggedInUser, Integer filterId, String name, + String rule, Map criteria) { ensureOrgAdmin(loggedInUser); - Optional ruleObj; - if (rule.isEmpty()) { - ruleObj = empty(); + Optional ruleObj = + rule == null || rule.isEmpty() ? Optional.empty() : + Optional.of(ContentFilter.Rule.lookupByLabel(rule)); + + CriteriaBuilder cb = HibernateFactory.getSession().getCriteriaBuilder(); + CriteriaQuery cq = cb.createQuery(FilterCriteria.class); + Root root = cq.from(FilterCriteria.class); + + Predicate[] predicates = criteria.entrySet().stream() + .map(entry -> cb.equal(root.get(entry.getKey()), entry.getValue())) + .toArray(Predicate[]::new); + + cq.where(predicates); + + TypedQuery query = HibernateFactory.getSession().createQuery(cq); + FilterCriteria filterCriteria; + try { + filterCriteria = query.getSingleResult(); } - else { - ruleObj = Optional.of(ContentFilter.Rule.lookupByLabel(rule)); + catch (NoResultException e) { + filterCriteria = null; } - Optional criteriaObj = getCriteriaBuilder().createQuery(criteria); try { - return contentManager.updateFilter( - filterId.longValue(), - ofNullable(name), - ruleObj, - criteriaObj, + return contentManager.updateFilter(filterId.longValue(), + Optional.ofNullable(name), ruleObj, Optional.ofNullable(filterCriteria), loggedInUser); } catch (EntityNotExistsException e) { diff --git a/java/code/src/com/redhat/rhn/manager/errata/test/ErrataManagerTest.java b/java/code/src/com/redhat/rhn/manager/errata/test/ErrataManagerTest.java index 54320d53c472..2773ce2dcc0c 100644 --- a/java/code/src/com/redhat/rhn/manager/errata/test/ErrataManagerTest.java +++ b/java/code/src/com/redhat/rhn/manager/errata/test/ErrataManagerTest.java @@ -1523,8 +1523,11 @@ public void testApplyErrataMultipleErrataActionChainYum() throws Exception { * @return the errata action */ private ErrataAction errataActionFromAction(Action action) { - return (ErrataAction) HibernateFactory.getSession().getCriteriaBuilder().createQuery(ErrataAction.class) - .add(Restrictions.idEq(action.getId())).uniqueResult(); + String sql = "SELECT * FROM rhnAction WHERE id = :id"; + return HibernateFactory.getSession() + .createNativeQuery(sql, ErrataAction.class) + .setParameter("id", action.getId()) + .getSingleResult(); } /** diff --git a/java/code/src/com/redhat/rhn/manager/rhnpackage/PackageManager.java b/java/code/src/com/redhat/rhn/manager/rhnpackage/PackageManager.java index 52b7832413f1..34d8cc2151c3 100644 --- a/java/code/src/com/redhat/rhn/manager/rhnpackage/PackageManager.java +++ b/java/code/src/com/redhat/rhn/manager/rhnpackage/PackageManager.java @@ -636,7 +636,7 @@ public static PackageName lookupPackageName(String name) { try { session = HibernateFactory.getSession(); return (PackageName)session.getNamedQuery("PackageName.findByName") - .setString("name", name) + .setParameter("name", name) .uniqueResult(); } catch (HibernateException e) { diff --git a/java/code/src/com/redhat/rhn/manager/system/VirtualInstanceManager.java b/java/code/src/com/redhat/rhn/manager/system/VirtualInstanceManager.java index debd9100e1a8..514d706eb434 100644 --- a/java/code/src/com/redhat/rhn/manager/system/VirtualInstanceManager.java +++ b/java/code/src/com/redhat/rhn/manager/system/VirtualInstanceManager.java @@ -25,6 +25,7 @@ import com.suse.manager.utils.SaltUtils; import com.suse.manager.webui.utils.salt.custom.VmInfo; import com.suse.manager.webui.websocket.VirtNotifications; +import com.redhat.rhn.domain.server.MinionServerFactory; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -242,7 +243,7 @@ public static void addGuestVirtualInstance(String vmGuid, String name, // Do we have a System with machineid matching the GUID that has no // virtual instance? if (guest == null) { - ServerFactory.findByMachineId(vmGuid) + MinionServerFactory.findByMachineId(vmGuid) .ifPresent(system -> { if (system.getVirtualInstance() == null) { virtualInstance.setGuestSystem(system); diff --git a/java/code/src/com/redhat/rhn/manager/system/test/SystemManagerTest.java b/java/code/src/com/redhat/rhn/manager/system/test/SystemManagerTest.java index 538349b88336..22166e8af089 100644 --- a/java/code/src/com/redhat/rhn/manager/system/test/SystemManagerTest.java +++ b/java/code/src/com/redhat/rhn/manager/system/test/SystemManagerTest.java @@ -259,33 +259,6 @@ private void createMetadataFiles() { } } - @Test - public void testSnapshotServer() { - User user = UserTestUtils.findNewUser("testUser", - "testOrg" + this.getClass().getSimpleName()); - user.addPermanentRole(RoleFactory.ORG_ADMIN); - Server server = ServerFactoryTest.createTestServer(user, true); - Long id = server.getId(); - - assertTrue(SystemManager.serverHasFeature(id, "ftr_snapshotting")); - assertEquals(Integer.valueOf(0), numberOfSnapshots(id)); - SystemManager.snapshotServer(server, "Testing snapshots"); - assertEquals(Integer.valueOf(1), numberOfSnapshots(id)); - } - - /* - * I know this is ugly, but since we haven't got the sever snapshotting feature fully - * worked out in java yet, just do a sql query to make sure the stored proc worked. - */ - private Integer numberOfSnapshots(Long sid) { - Session session = HibernateFactory.getSession(); - return (Integer) session.createSQLQuery("Select count(*) as cnt " + - " from rhnSnapshot " + - " where server_id = " + sid) - .addScalar("cnt", IntegerType.INSTANCE) - .uniqueResult(); - } - @Test public void testDeleteServer() { User user = UserTestUtils.findNewUser("testUser", diff --git a/java/code/src/com/redhat/rhn/taskomatic/TaskoFactory.java b/java/code/src/com/redhat/rhn/taskomatic/TaskoFactory.java index a5da4043a488..a9e9e61e8499 100644 --- a/java/code/src/com/redhat/rhn/taskomatic/TaskoFactory.java +++ b/java/code/src/com/redhat/rhn/taskomatic/TaskoFactory.java @@ -30,7 +30,14 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Arrays; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; +import jakarta.persistence.criteria.Subquery; +import jakarta.persistence.EntityManager; +import jakarta.persistence.TypedQuery; /** * TaskoFactory @@ -425,28 +432,39 @@ public static List listRunsByBunch(String bunchName) { * @return the latest run or null if none exists */ public static TaskoRun getLatestRun(String bunchName) { - DetachedCriteria bunchIds = DetachedCriteria.forClass(TaskoBunch.class) - .add(Restrictions.eq("name", bunchName)) - .setProjection(Projections.id()); - - DetachedCriteria templateIds = DetachedCriteria.forClass(TaskoTemplate.class) - .add(Subqueries.propertyIn("bunch", bunchIds)) - .setProjection(Projections.id()); - - return (TaskoRun) getSession() - .getCriteriaBuilder().createQuery(TaskoRun.class) - .add(Subqueries.propertyIn("template.id", templateIds)) - .add(Restrictions.in("status", - new Object[] { - TaskoRun.STATUS_RUNNING, - TaskoRun.STATUS_FINISHED, - TaskoRun.STATUS_INTERRUPTED - })) - .addOrder(Order.desc("startTime")) - .addOrder(Order.desc("id")) - .setFirstResult(0) - .setMaxResults(1) - .uniqueResult(); + // Obtain CriteriaBuilder from EntityManager + CriteriaBuilder cb = getSession().getCriteriaBuilder(); + + // Main query to fetch TaskoRun + CriteriaQuery query = cb.createQuery(TaskoRun.class); + Root taskoRunRoot = query.from(TaskoRun.class); + + // Subquery to fetch TaskoBunch IDs + Subquery bunchIdsSubquery = query.subquery(Long.class); + Root bunchRoot = bunchIdsSubquery.from(TaskoBunch.class); + bunchIdsSubquery.select(bunchRoot.get("id")) + .where(cb.equal(bunchRoot.get("name"), bunchName)); + + // Subquery to fetch TaskoTemplate IDs + Subquery templateIdsSubquery = query.subquery(Long.class); + Root templateRoot = templateIdsSubquery.from(TaskoTemplate.class); + templateIdsSubquery.select(templateRoot.get("id")) + .where(templateRoot.get("bunch").in(bunchIdsSubquery)); + + // Add criteria to main query + query.select(taskoRunRoot) + .where(taskoRunRoot.get("template").get("id").in(templateIdsSubquery), + taskoRunRoot.get("status").in(Arrays.asList(TaskoRun.STATUS_RUNNING, + TaskoRun.STATUS_FINISHED, TaskoRun.STATUS_INTERRUPTED))) + .orderBy(cb.desc(taskoRunRoot.get("startTime")), + cb.desc(taskoRunRoot.get("id"))); + + // Create and execute the query + TypedQuery typedQuery = getSession().createQuery(query); + typedQuery.setFirstResult(0); + typedQuery.setMaxResults(1); + + return typedQuery.getSingleResult(); } /** diff --git a/java/code/src/com/redhat/rhn/taskomatic/task/test/KickstartCleanupTest.java b/java/code/src/com/redhat/rhn/taskomatic/task/test/KickstartCleanupTest.java index 04c658e7aa3e..57c0c92515b8 100644 --- a/java/code/src/com/redhat/rhn/taskomatic/task/test/KickstartCleanupTest.java +++ b/java/code/src/com/redhat/rhn/taskomatic/task/test/KickstartCleanupTest.java @@ -156,7 +156,7 @@ private static KickstartSessionState lookupByLabel(String label) { Session session = HibernateFactory.getSession(); return (KickstartSessionState) session .getNamedQuery("KickstartSessionState.findByLabel") - .setString("label", label) + .setParameter("label", label) .uniqueResult(); } diff --git a/java/code/src/com/redhat/rhn/testing/TestUtils.java b/java/code/src/com/redhat/rhn/testing/TestUtils.java index 517f31dc0d6b..763063b73560 100644 --- a/java/code/src/com/redhat/rhn/testing/TestUtils.java +++ b/java/code/src/com/redhat/rhn/testing/TestUtils.java @@ -284,7 +284,7 @@ public static Object lookupFromCacheByLabel(String label, String queryname) { Session session = HibernateFactory.getSession(); return session.getNamedQuery(queryname) - .setString("label", label) + .setParameter("label", label) //Retrieve from cache if there .setCacheable(true) .uniqueResult(); diff --git a/java/code/src/com/suse/cloud/domain/BillingDimensionEnumType.java b/java/code/src/com/suse/cloud/domain/BillingDimensionEnumType.java index 36d135d9bb46..35a78dbeb6ee 100644 --- a/java/code/src/com/suse/cloud/domain/BillingDimensionEnumType.java +++ b/java/code/src/com/suse/cloud/domain/BillingDimensionEnumType.java @@ -15,6 +15,13 @@ package com.suse.cloud.domain; +import java.sql.SQLException; +import java.sql.PreparedStatement; +import org.hibernate.HibernateException; +import java.sql.ResultSet; + +import org.hibernate.engine.spi.SharedSessionContractImplementor; + import com.redhat.rhn.domain.errata.CustomEnumType; import java.sql.Types; @@ -36,4 +43,21 @@ public int getSqlType() { // Returning other, as this is mapped to a PostgreSQL enum, not to a VARCHAR return Types.OTHER; } + + @Override + public String nullSafeGet(ResultSet var1, int var2, + SharedSessionContractImplementor var3, @Deprecated Object var4) + throws SQLException { + return null; + } + + ; + + @Override + public void nullSafeSet(PreparedStatement var1, Object var2, int var3, + SharedSessionContractImplementor var4) + throws SQLException { + } +; + }