From ca4e1e369d6d2f3fa29784da14b10c9afc85714f Mon Sep 17 00:00:00 2001 From: Pavol Mederly Date: Wed, 8 Mar 2017 14:00:49 +0100 Subject: [PATCH] Fixed searching by enums in extensions: MID-3801 (ActivationStatusType cannot be cast to java.lang.String) Now respecting indexed=false for all extension data types --- .../midpoint/prism/SimpleTypeDefinition.java | 9 + .../prism/SimpleTypeDefinitionImpl.java | 19 +- .../prism/schema/SchemaDefinitionFactory.java | 20 +- .../midpoint/repo/sql/BaseSQLRepoTest.java | 67 +- .../repo/sql/QueryInterpreter2Test.java | 31 + .../src/test/resources/schema/extension.xsd | 7 + .../repo/sql/SqlRepositoryFactory.java | 10 - .../sql/data/common/any/RAnyConverter.java | 211 +++--- .../repo/sql/helpers/ObjectRetriever.java | 28 +- .../midpoint/repo/sql/query/QueryContext.java | 168 ----- .../sql/query/QueryDefinitionRegistry.java | 111 ---- .../midpoint/repo/sql/query/QueryEngine.java | 66 -- .../repo/sql/query/QueryException.java | 2 +- .../repo/sql/query/QueryInterpreter.java | 292 --------- .../repo/sql/query/RQueryCriteriaImpl.java | 57 -- .../repo/sql/query/custom/CustomQuery.java | 58 -- .../repo/sql/query/custom/OrgFilterQuery.java | 111 ---- .../custom/ShadowQueryWithDisjunction.java | 268 -------- .../sql/query/matcher/DefaultMatcher.java | 34 - .../repo/sql/query/matcher/Matcher.java | 93 --- .../sql/query/matcher/PolyStringMatcher.java | 82 --- .../repo/sql/query/matcher/StringMatcher.java | 40 -- .../sql/query/restriction/AndRestriction.java | 53 -- .../restriction/AnyPropertyRestriction.java | 132 ---- .../restriction/CollectionRestriction.java | 74 --- .../query/restriction/InOidRestriction.java | 50 -- .../query/restriction/ItemRestriction.java | 599 ------------------ .../restriction/ItemRestrictionOperation.java | 25 - .../query/restriction/LogicalRestriction.java | 45 -- .../restriction/NaryLogicalRestriction.java | 78 --- .../sql/query/restriction/NotRestriction.java | 52 -- .../sql/query/restriction/OrRestriction.java | 56 -- .../sql/query/restriction/OrgRestriction.java | 103 --- .../restriction/PropertyRestriction.java | 83 --- .../restriction/ReferenceRestriction.java | 156 ----- .../sql/query/restriction/Restriction.java | 95 --- .../query/restriction/TypeRestriction.java | 98 --- .../restriction/UnaryLogicalRestriction.java | 48 -- .../sql/query2/QueryDefinitionRegistry2.java | 67 +- .../repo/sql/query2/QueryInterpreter2.java | 9 +- .../definition/JpaAnyContainerDefinition.java | 5 +- .../definition/JpaDataNodeDefinition.java | 7 +- .../definition/JpaEntityDefinition.java | 14 +- .../JpaEntityPointerDefinition.java | 6 +- .../definition/JpaPropertyDefinition.java | 3 +- .../definition/JpaReferenceDefinition.java | 3 +- .../resolution/ItemPathResolutionState.java | 7 +- .../query2/resolution/ItemPathResolver.java | 10 +- 48 files changed, 271 insertions(+), 3391 deletions(-) delete mode 100644 repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/QueryContext.java delete mode 100644 repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/QueryDefinitionRegistry.java delete mode 100644 repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/QueryEngine.java delete mode 100644 repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/QueryInterpreter.java delete mode 100644 repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/RQueryCriteriaImpl.java delete mode 100644 repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/custom/CustomQuery.java delete mode 100644 repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/custom/OrgFilterQuery.java delete mode 100644 repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/custom/ShadowQueryWithDisjunction.java delete mode 100644 repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/matcher/DefaultMatcher.java delete mode 100644 repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/matcher/Matcher.java delete mode 100644 repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/matcher/PolyStringMatcher.java delete mode 100644 repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/matcher/StringMatcher.java delete mode 100644 repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/AndRestriction.java delete mode 100644 repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/AnyPropertyRestriction.java delete mode 100644 repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/CollectionRestriction.java delete mode 100644 repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/InOidRestriction.java delete mode 100644 repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/ItemRestriction.java delete mode 100644 repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/ItemRestrictionOperation.java delete mode 100644 repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/LogicalRestriction.java delete mode 100644 repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/NaryLogicalRestriction.java delete mode 100644 repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/NotRestriction.java delete mode 100644 repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/OrRestriction.java delete mode 100644 repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/OrgRestriction.java delete mode 100644 repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/PropertyRestriction.java delete mode 100644 repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/ReferenceRestriction.java delete mode 100644 repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/Restriction.java delete mode 100644 repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/TypeRestriction.java delete mode 100644 repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/UnaryLogicalRestriction.java diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/SimpleTypeDefinition.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/SimpleTypeDefinition.java index 444246c7b1c..47f85059019 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/SimpleTypeDefinition.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/SimpleTypeDefinition.java @@ -16,6 +16,8 @@ package com.evolveum.midpoint.prism; +import javax.xml.namespace.QName; + /** * Primarily for enums. (Experimental.) * @@ -25,4 +27,11 @@ */ public interface SimpleTypeDefinition extends TypeDefinition { + enum DerivationMethod { + EXTENSION, RESTRICTION, SUBSTITUTION + } + + QName getBaseTypeName(); + + DerivationMethod getDerivationMethod(); } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/SimpleTypeDefinitionImpl.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/SimpleTypeDefinitionImpl.java index 589602da0cf..be9dea88d9e 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/SimpleTypeDefinitionImpl.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/SimpleTypeDefinitionImpl.java @@ -25,8 +25,14 @@ */ public class SimpleTypeDefinitionImpl extends TypeDefinitionImpl implements SimpleTypeDefinition { - public SimpleTypeDefinitionImpl(QName typeName, PrismContext prismContext) { + private QName baseTypeName; + private DerivationMethod derivationMethod; // usually RESTRICTION + + public SimpleTypeDefinitionImpl(QName typeName, QName baseTypeName, DerivationMethod derivationMethod, + PrismContext prismContext) { super(typeName, prismContext); + this.baseTypeName = baseTypeName; + this.derivationMethod = derivationMethod; } @Override @@ -43,10 +49,19 @@ public String getDocClassName() { return "simple type"; } + public QName getBaseTypeName() { + return baseTypeName; + } + + @Override + public DerivationMethod getDerivationMethod() { + return derivationMethod; + } + @NotNull @Override public SimpleTypeDefinitionImpl clone() { - SimpleTypeDefinitionImpl clone = new SimpleTypeDefinitionImpl(typeName, prismContext); + SimpleTypeDefinitionImpl clone = new SimpleTypeDefinitionImpl(typeName, baseTypeName, derivationMethod, prismContext); super.copyDefinitionData(clone); return clone; } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/SchemaDefinitionFactory.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/SchemaDefinitionFactory.java index 0b19a6b8033..416354bde72 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/SchemaDefinitionFactory.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/SchemaDefinitionFactory.java @@ -20,14 +20,15 @@ import javax.xml.namespace.QName; import com.evolveum.midpoint.prism.*; -import com.sun.xml.xsom.XSSimpleType; +import com.sun.xml.xsom.*; import org.w3c.dom.Element; import com.evolveum.midpoint.util.DisplayableValue; import com.evolveum.midpoint.util.exception.SchemaException; -import com.sun.xml.xsom.XSAnnotation; -import com.sun.xml.xsom.XSComplexType; -import com.sun.xml.xsom.XSParticle; + +import static com.evolveum.midpoint.prism.SimpleTypeDefinition.DerivationMethod.EXTENSION; +import static com.evolveum.midpoint.prism.SimpleTypeDefinition.DerivationMethod.RESTRICTION; +import static com.evolveum.midpoint.prism.SimpleTypeDefinition.DerivationMethod.SUBSTITUTION; /** * @author semancik @@ -46,7 +47,16 @@ public SimpleTypeDefinition createSimpleTypeDefinition(XSSimpleType simpleType, PrismContext prismContext, XSAnnotation annotation) throws SchemaException { QName typeName = new QName(simpleType.getTargetNamespace(), simpleType.getName()); - return new SimpleTypeDefinitionImpl(typeName, prismContext); + XSType baseType = simpleType.getBaseType(); + QName baseTypeName = baseType != null ? new QName(baseType.getTargetNamespace(), baseType.getName()) : null; + SimpleTypeDefinition.DerivationMethod derivationMethod; + switch (simpleType.getDerivationMethod()) { + case XSSimpleType.EXTENSION: derivationMethod = EXTENSION; break; + case XSSimpleType.RESTRICTION: derivationMethod = RESTRICTION; break; + case XSSimpleType.SUBSTITUTION: derivationMethod = SUBSTITUTION; break; + default: derivationMethod = null; // TODO are combinations allowed? e.g. EXTENSION+SUBSTITUTION? + } + return new SimpleTypeDefinitionImpl(typeName, baseTypeName, derivationMethod, prismContext); } public PrismPropertyDefinition createPropertyDefinition(QName elementName, QName typeName, ComplexTypeDefinition complexTypeDefinition, diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/BaseSQLRepoTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/BaseSQLRepoTest.java index a53a0affdba..6c2f64185db 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/BaseSQLRepoTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/BaseSQLRepoTest.java @@ -18,28 +18,17 @@ import com.evolveum.midpoint.audit.api.AuditService; import com.evolveum.midpoint.prism.PrismContext; -import com.evolveum.midpoint.prism.query.ObjectQuery; -import com.evolveum.midpoint.prism.query.QueryJaxbConvertor; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.repo.api.RepositoryService; import com.evolveum.midpoint.repo.sql.helpers.BaseHelper; -import com.evolveum.midpoint.repo.sql.query.QueryEngine; -import com.evolveum.midpoint.repo.sql.query.RQuery; -import com.evolveum.midpoint.repo.sql.query.RQueryCriteriaImpl; -import com.evolveum.midpoint.repo.sql.query.RQueryImpl; import com.evolveum.midpoint.repo.sql.util.HibernateToSqlTranslator; import com.evolveum.midpoint.repo.sql.util.RUtil; import com.evolveum.midpoint.schema.MidPointPrismContextFactory; import com.evolveum.midpoint.schema.constants.MidPointConstants; -import com.evolveum.midpoint.schema.util.ObjectQueryUtil; import com.evolveum.midpoint.util.PrettyPrinter; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; -import com.evolveum.prism.xml.ns._public.query_3.QueryType; - -import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.dialect.H2Dialect; @@ -47,11 +36,7 @@ import org.springframework.orm.hibernate4.LocalSessionFactoryBean; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.AssertJUnit; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.BeforeSuite; +import org.testng.annotations.*; import org.xml.sax.SAXException; import java.io.File; @@ -84,7 +69,7 @@ public class BaseSQLRepoTest extends AbstractTestNGSpringContextTests { @Autowired protected SessionFactory factory; - protected static Set initializedClasses = new HashSet(); + protected static Set initializedClasses = new HashSet<>(); @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { @@ -171,56 +156,8 @@ protected void close(Session session) { session.close(); } - protected String getInterpretedQuery(Session session, Class type, ObjectQuery query) - throws Exception { - return getInterpretedQuery(session, type, query, false); - } - - protected String getInterpretedQuery(Session session, Class type, ObjectQuery query, - boolean interpretCount) throws Exception { - - LOGGER.info("QUERY TYPE TO CONVERT : {}", (query.getFilter() != null ? query.getFilter().debugDump(3) : null)); - - QueryEngine engine = new QueryEngine(baseHelper.getConfiguration(), prismContext); - RQuery rQuery = engine.interpret(query, type, null, interpretCount, session); - //just test if DB will handle it or throws some exception - if (interpretCount) { - rQuery.uniqueResult(); - } else { - rQuery.list(); - } - - if (rQuery instanceof RQueryCriteriaImpl) { - Criteria criteria = ((RQueryCriteriaImpl) rQuery).getCriteria(); - return HibernateToSqlTranslator.toSql(criteria); - } - - return HibernateToSqlTranslator.toSql(factory, ((RQueryImpl) rQuery).getQuery().getQueryString()); - } - protected String hqlToSql(String hql) { return HibernateToSqlTranslator.toSql(factory, hql); } - protected String getInterpretedQuery(Session session, Class type, File file) throws - Exception { - return getInterpretedQuery(session, type, file, false); - } - - protected String getInterpretedQuery(Session session, Class type, File file, - boolean interpretCount) throws Exception { - - QueryType queryType = PrismTestUtil.parseAtomicValue(file, QueryType.COMPLEX_TYPE); - - LOGGER.info("QUERY TYPE TO CONVERT : {}", ObjectQueryUtil.dump(queryType, prismContext)); - - ObjectQuery query = null; - try { - query = QueryJaxbConvertor.createObjectQuery(type, queryType, prismContext); - } catch (Exception ex) { - LOGGER.info("error while converting query: " + ex.getMessage(), ex); - } - - return getInterpretedQuery(session, type, query, interpretCount); - } } diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/QueryInterpreter2Test.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/QueryInterpreter2Test.java index 61fcbb64d63..20429f0ef71 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/QueryInterpreter2Test.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/QueryInterpreter2Test.java @@ -2614,6 +2614,37 @@ public void test640queryAssignmentExtensionBoolean() throws Exception { } } + @Test + public void test650QueryExtensionEnum() throws Exception { + Session session = open(); + try { + ObjectQuery query = QueryBuilder.queryFor(UserType.class, prismContext) + .item(F_EXTENSION, new QName("overrideActivation")).eq(ActivationStatusType.ENABLED) + .build(); + String real = getInterpretedQuery2(session, UserType.class, query); + String expected = "select\n" + + " u.fullObject,\n" + + " u.stringsCount,\n" + + " u.longsCount,\n" + + " u.datesCount,\n" + + " u.referencesCount,\n" + + " u.polysCount,\n" + + " u.booleansCount\n" + + "from\n" + + " RUser u\n" + + " left join u.strings s with (\n" + + " s.ownerType = :ownerType and\n" + + " s.name = :name\n" + + ")\n" + + "where\n" + + " s.value = :value\n"; + assertEqualsIgnoreWhitespace(expected, real); + } finally { + close(session); + } + } + + @Test public void test700QueryCertCaseAll() throws Exception { Session session = open(); diff --git a/repo/repo-sql-impl-test/src/test/resources/schema/extension.xsd b/repo/repo-sql-impl-test/src/test/resources/schema/extension.xsd index 56fe2e97126..ad4ae1f0f60 100644 --- a/repo/repo-sql-impl-test/src/test/resources/schema/extension.xsd +++ b/repo/repo-sql-impl-test/src/test/resources/schema/extension.xsd @@ -170,6 +170,13 @@ + + + + true + + + diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/SqlRepositoryFactory.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/SqlRepositoryFactory.java index 2aa80e17a11..fa289ded705 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/SqlRepositoryFactory.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/SqlRepositoryFactory.java @@ -19,10 +19,8 @@ import com.evolveum.midpoint.repo.api.RepositoryService; import com.evolveum.midpoint.repo.api.RepositoryServiceFactory; import com.evolveum.midpoint.repo.api.RepositoryServiceFactoryException; -import com.evolveum.midpoint.repo.sql.query.QueryDefinitionRegistry; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; - import org.apache.commons.configuration.Configuration; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; @@ -32,7 +30,6 @@ import org.hibernate.dialect.H2Dialect; import java.io.File; -import java.io.FilenameFilter; import java.io.IOException; import java.net.BindException; import java.net.ServerSocket; @@ -138,13 +135,6 @@ public synchronized void init(Configuration configuration) throws RepositoryServ LOGGER.info("Repository is not running in embedded mode."); } - try { - QueryDefinitionRegistry.getInstance(); - } catch (Exception ex) { - throw new RepositoryServiceFactoryException("Couldn't initialize query registry, reason: " - + ex.getMessage(), ex); - } - performanceMonitor = new SqlPerformanceMonitor(); performanceMonitor.initialize(this); diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/data/common/any/RAnyConverter.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/data/common/any/RAnyConverter.java index 1f78e65102e..6bcf226ecd8 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/data/common/any/RAnyConverter.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/data/common/any/RAnyConverter.java @@ -28,7 +28,6 @@ import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; import org.apache.commons.lang.Validate; import org.w3c.dom.Element; @@ -45,7 +44,7 @@ */ public class RAnyConverter { - private static enum ValueType { + private enum ValueType { BOOLEAN, LONG, STRING, DATE, POLY_STRING; } @@ -79,83 +78,66 @@ public Set convertToRValue(Item item, boolean assignment) throws DtoT Validate.notNull(item, "Object for converting must not be null."); Validate.notNull(item.getDefinition(), "Item '" + item.getElementName() + "' without definition can't be saved."); + ItemDefinition definition = item.getDefinition(); Set rValues = new HashSet<>(); - try { - ItemDefinition definition = item.getDefinition(); + if (!isIndexed(definition, prismContext)) { + return rValues; + } - RAnyValue rValue = null; + try { + RAnyValue rValue; List values = item.getValues(); for (PrismValue value : values) { - if (value instanceof PrismContainerValue) { - continue; - } else if (value instanceof PrismPropertyValue) { + if (value instanceof PrismPropertyValue) { PrismPropertyValue propertyValue = (PrismPropertyValue) value; - Object realValue = propertyValue.getValue(); - if (realValue.getClass().isEnum()) { - PrismBeanInspector inspector = new PrismBeanInspector(prismContext); - String enumToString = inspector.findEnumFieldValueUncached(realValue.getClass(), realValue.toString()); - rValue = new ROExtString(enumToString); - - } else { - //todo omg, do something with this!!! [lazyman] - switch (getValueType(definition.getTypeName())) { - case BOOLEAN: - if (assignment) { - RAExtBoolean booleanValue = new RAExtBoolean(); - booleanValue.setValue(extractValue(propertyValue, Boolean.class)); - rValue = booleanValue; - } else { - ROExtBoolean booleanValue = new ROExtBoolean(); - booleanValue.setValue(extractValue(propertyValue, Boolean.class)); - rValue = booleanValue; - } - break; - case LONG: - if (assignment) { - RAExtLong longValue = new RAExtLong(); - longValue.setValue(extractValue(propertyValue, Long.class)); - rValue = longValue; - } else { - ROExtLong longValue = new ROExtLong(); - longValue.setValue(extractValue(propertyValue, Long.class)); - rValue = longValue; - } - break; - case DATE: - if (assignment) { - RAExtDate dateValue = new RAExtDate(); - dateValue.setValue(extractValue(propertyValue, Timestamp.class)); - rValue = dateValue; - } else { - ROExtDate dateValue = new ROExtDate(); - dateValue.setValue(extractValue(propertyValue, Timestamp.class)); - rValue = dateValue; - } - break; - case POLY_STRING: - if (assignment) { - rValue = new RAExtPolyString(extractValue(propertyValue, PolyString.class)); - } else { - rValue = new ROExtPolyString(extractValue(propertyValue, PolyString.class)); - } - break; - case STRING: - default: - if (isIndexable(definition)) { - if (assignment) { - RAExtString strValue = new RAExtString(); - strValue.setValue(extractValue(propertyValue, String.class)); - rValue = strValue; - } else { - ROExtString strValue = new ROExtString(); - strValue.setValue(extractValue(propertyValue, String.class)); - rValue = strValue; - } - } else { - continue; - } - } - } + //todo omg, do something with this!!! [lazyman] + switch (getValueType(definition.getTypeName())) { + case BOOLEAN: { + Boolean repoValue = extractValue(propertyValue, Boolean.class); + if (assignment) { + rValue = new RAExtBoolean(repoValue); + } else { + rValue = new ROExtBoolean(repoValue); + } + break; + } + case LONG: { + Long repoValue = extractValue(propertyValue, Long.class); + if (assignment) { + rValue = new RAExtLong(repoValue); + } else { + rValue = new ROExtLong(repoValue); + } + break; + } + case DATE: { + Timestamp repoValue = extractValue(propertyValue, Timestamp.class); + if (assignment) { + rValue = new RAExtDate(repoValue); + } else { + rValue = new ROExtDate(repoValue); + } + break; + } + case POLY_STRING: { + PolyString repoValue = extractValue(propertyValue, PolyString.class); + if (assignment) { + rValue = new RAExtPolyString(repoValue); + } else { + rValue = new ROExtPolyString(repoValue); + } + break; + } + case STRING: + default: { + String repoValue = extractValue(propertyValue, String.class); + if (assignment) { + rValue = new RAExtString(repoValue); + } else { + rValue = new ROExtString(repoValue); + } + } + } } else if (value instanceof PrismReferenceValue) { if (assignment) { PrismReferenceValue referenceValue = (PrismReferenceValue) value; @@ -164,7 +146,12 @@ public Set convertToRValue(Item item, boolean assignment) throws DtoT PrismReferenceValue referenceValue = (PrismReferenceValue) value; rValue = ROExtReference.createReference(referenceValue); } - } + } else if (value == null) { + continue; // shouldn't occur anyway + } else { + // shouldn't get here because if isIndexed test above + throw new AssertionError("Wrong value type: " + value); + } rValue.setName(RUtil.qnameToString(definition.getName())); rValue.setType(RUtil.qnameToString(definition.getTypeName())); @@ -180,11 +167,18 @@ public Set convertToRValue(Item item, boolean assignment) throws DtoT return rValues; } - private static boolean isIndexable(ItemDefinition definition) { - if (definition instanceof PrismContainerDefinition) { - return false; - } - if (!(definition instanceof PrismPropertyDefinition)) { + private static String getEnumStringValue(Enum realValue) { + return PrismBeanInspector.findEnumFieldValueUncached(realValue.getClass(), realValue.toString()); + } + + private static boolean isIndexed(ItemDefinition definition, PrismContext prismContext) { + if (definition instanceof PrismContainerDefinition) { + return false; + } + if (definition instanceof PrismReferenceDefinition) { + return true; // TODO make reference indexing configurable + } + if (!(definition instanceof PrismPropertyDefinition)) { throw new UnsupportedOperationException("Unknown definition type '" + definition + "', can't say if it's indexed or not."); } @@ -194,12 +188,12 @@ private static boolean isIndexable(ItemDefinition definition) { return pDefinition.isIndexed(); } - QName type = definition.getTypeName(); - return isIndexable(type); + return isIndexedByDefault(definition, prismContext); } - private static boolean isIndexable(QName type) { - return DOMUtil.XSD_DATETIME.equals(type) + private static boolean isIndexedByDefault(ItemDefinition definition, PrismContext prismContext) { + QName type = definition.getTypeName(); + if (DOMUtil.XSD_DATETIME.equals(type) || DOMUtil.XSD_INT.equals(type) || DOMUtil.XSD_LONG.equals(type) || DOMUtil.XSD_SHORT.equals(type) @@ -208,8 +202,24 @@ private static boolean isIndexable(QName type) { || DOMUtil.XSD_FLOAT.equals(type) || DOMUtil.XSD_STRING.equals(type) || DOMUtil.XSD_DECIMAL.equals(type) - || DOMUtil.XSD_BOOLEAN.equals(type); - } + || DOMUtil.XSD_BOOLEAN.equals(type) + || PolyStringType.COMPLEX_TYPE.equals(type)) { + return true; + } + Collection typeDefinitions = prismContext.getSchemaRegistry() + .findTypeDefinitionsByType(definition.getTypeName()); + if (typeDefinitions.isEmpty() || typeDefinitions.size() > 1) { + return false; // shouldn't occur + } + TypeDefinition typeDef = typeDefinitions.iterator().next(); + if (typeDef instanceof SimpleTypeDefinition) { + SimpleTypeDefinition simpleTypeDef = (SimpleTypeDefinition) typeDef; + return DOMUtil.XSD_STRING.equals(simpleTypeDef.getBaseTypeName()) + && simpleTypeDef.getDerivationMethod() == SimpleTypeDefinition.DerivationMethod.RESTRICTION; + } else { + return false; + } + } private RValueType getValueType(Itemable itemable) { Validate.notNull(itemable, "Value parent must not be null."); @@ -354,11 +364,15 @@ private Object createRealValue(RAnyValue rValue, QName type) throws SchemaExcept * defined as parameters. * * @param definition - * @return One of "strings", "longs", "dates", "clobs" + * @param prismContext + * @return One of "strings", "longs", "dates", "clobs" * @throws SchemaException */ - public static String getAnySetType(ItemDefinition definition) throws + public static String getAnySetType(ItemDefinition definition, PrismContext prismContext) throws SchemaException, QueryException { + if (!isIndexed(definition, prismContext)) { + throw new QueryException("Can't query non-indexed value, definition " + definition); + } QName typeName = definition.getTypeName(); ValueType valueType = getValueType(typeName); @@ -371,11 +385,7 @@ public static String getAnySetType(ItemDefinition definit return "longs"; case STRING: default: - if (isIndexable(definition)) { - return "strings"; - } else { - throw new QueryException("Can't query CLOB (non indexed string) value, definition " + definition); - } + return "strings"; } } @@ -426,14 +436,13 @@ public static Object getRealRepoValue(ItemDefinition definition, Element value) public static Object getAggregatedRepoObject(Object object) { //check float/double to string if (object instanceof Float) { - object = ((Float) object).toString(); + object = object.toString(); } else if (object instanceof Double) { - object = ((Double) object).toString(); + object = object.toString(); } else if (object instanceof BigInteger) { - object = ((BigInteger) object).toString(); - } else if (object instanceof BigDecimal) { - object = ((BigDecimal) object).toString(); - } + object = object.toString(); + } else if (object instanceof BigDecimal) + object = object.toString(); //check short/integer to long if (object instanceof Short) { @@ -455,6 +464,10 @@ public static Object getAggregatedRepoObject(Object object) { //if object instance of boolean, nothing to do + if (object instanceof Enum) { + object = getEnumStringValue((Enum) object); + } + return object; } } diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/helpers/ObjectRetriever.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/helpers/ObjectRetriever.java index 9efa50db631..a507fdd5c55 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/helpers/ObjectRetriever.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/helpers/ObjectRetriever.java @@ -34,7 +34,6 @@ import com.evolveum.midpoint.repo.sql.data.common.any.RAnyValue; import com.evolveum.midpoint.repo.sql.data.common.any.RValueType; import com.evolveum.midpoint.repo.sql.data.common.type.RObjectExtensionType; -import com.evolveum.midpoint.repo.sql.query.QueryEngine; import com.evolveum.midpoint.repo.sql.query.QueryException; import com.evolveum.midpoint.repo.sql.query.RQuery; import com.evolveum.midpoint.repo.sql.query2.QueryEngine2; @@ -339,13 +338,8 @@ public int countObjectsAttempt(Class type, ObjectQuery longCount = (Number) sqlQuery.uniqueResult(); } else { RQuery rQuery; - if (isUseNewQueryInterpreter(query)) { - QueryEngine2 engine = new QueryEngine2(getConfiguration(), prismContext); - rQuery = engine.interpret(query, type, options, true, session); - } else { - QueryEngine engine = new QueryEngine(getConfiguration(), prismContext); - rQuery = engine.interpret(query, type, null, true, session); - } + QueryEngine2 engine = new QueryEngine2(getConfiguration(), prismContext); + rQuery = engine.interpret(query, type, options, true, session); longCount = (Number) rQuery.uniqueResult(); } @@ -372,13 +366,8 @@ public SearchResultList> searchObjectsAtte session = baseHelper.beginReadOnlyTransaction(); RQuery rQuery; - if (isUseNewQueryInterpreter(query)) { - QueryEngine2 engine = new QueryEngine2(getConfiguration(), prismContext); - rQuery = engine.interpret(query, type, options, false, session); - } else { - QueryEngine engine = new QueryEngine(getConfiguration(), prismContext); - rQuery = engine.interpret(query, type, options, false, session); - } + QueryEngine2 engine = new QueryEngine2(getConfiguration(), prismContext); + rQuery = engine.interpret(query, type, options, false, session); List queryResult = rQuery.list(); LOGGER.trace("Found {} objects, translating to JAXB.", new Object[]{(queryResult != null ? queryResult.size() : 0)}); @@ -652,13 +641,8 @@ public void searchObjectsIterativeAttempt(Class type, try { session = baseHelper.beginReadOnlyTransaction(); RQuery rQuery; - if (isUseNewQueryInterpreter(query)) { - QueryEngine2 engine = new QueryEngine2(getConfiguration(), prismContext); - rQuery = engine.interpret(query, type, options, false, session); - } else { - QueryEngine engine = new QueryEngine(getConfiguration(), prismContext); - rQuery = engine.interpret(query, type, options, false, session); - } + QueryEngine2 engine = new QueryEngine2(getConfiguration(), prismContext); + rQuery = engine.interpret(query, type, options, false, session); ScrollableResults results = rQuery.scroll(ScrollMode.FORWARD_ONLY); try { diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/QueryContext.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/QueryContext.java deleted file mode 100644 index 86829696339..00000000000 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/QueryContext.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Copyright (c) 2010-2013 Evolveum - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.evolveum.midpoint.repo.sql.query; - -import com.evolveum.midpoint.prism.PrismContext; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.prism.query.ObjectQuery; -import com.evolveum.midpoint.repo.sql.query.definition.Definition; -import com.evolveum.midpoint.repo.sql.query.definition.EntityDefinition; -import com.evolveum.midpoint.repo.sql.util.ClassMapper; -import com.evolveum.midpoint.schema.constants.ObjectTypes; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; - -import org.apache.commons.lang.StringUtils; -import org.hibernate.Criteria; -import org.hibernate.Session; - -import javax.xml.namespace.QName; - -import java.util.HashMap; -import java.util.Map; - -/** - * @author lazyman - */ -public class QueryContext { - - private QueryInterpreter interpreter; - private PrismContext prismContext; - private Session session; - - private ObjectQuery query; - - private Class type; - - private final Map criterias = new HashMap(); - private final Map aliases = new HashMap(); - - public QueryContext(QueryInterpreter interpreter, Class type, ObjectQuery query, - PrismContext prismContext, Session session) { - this.interpreter = interpreter; - this.type = type; - this.query = query; - this.prismContext = prismContext; - this.session = session; - - QueryDefinitionRegistry registry = QueryDefinitionRegistry.getInstance(); - - String alias = addAlias(null, registry.findDefinition(type, null, EntityDefinition.class)); - addCriteria(null, session.createCriteria(ClassMapper.getHQLTypeClass(type), alias)); - } - - public ObjectQuery getQuery() { - return query; - } - - public void setQuery(ObjectQuery query) { - this.query = query; - } - - public PrismContext getPrismContext() { - return prismContext; - } - - public Session getSession() { - return session; - } - - public QueryInterpreter getInterpreter() { - return interpreter; - } - - public Class getType() { - return type; - } - - public Criteria getCriteria(ItemPath path) { - return criterias.get(path); - } - - public void addCriteria(ItemPath path, Criteria criteria) { - criterias.put(path, criteria); - } - - public String getAlias(ItemPath path) { - return aliases.get(path); - } - - public void addAlias(ItemPath path, String alias) { - if (aliases.containsKey(path)) { - if (!StringUtils.equals(alias, aliases.get(path))) { - throw new IllegalArgumentException("Path '" + path + "' (" + alias - + ") is already defined in alias map with alias (" + aliases.get(path) + ")."); - } - - return; - } - - aliases.put(path, alias); - } - - public String addAlias(ItemPath path, Definition def) { - QName qname; - if (path == null) { - //get qname from class type - qname = ObjectTypes.getObjectType(type).getQName(); - } else { - if (!path.isEmpty()) { - //get last qname from path - qname = ItemPath.getName(path.last()); - } else { - throw new IllegalArgumentException("Item path must not be empty."); - } - } - - String alias = createAlias(def, qname); - aliases.put(path, alias); - - return alias; - } - - private String createAlias(Definition def, QName qname) { - String prefix; - if (def != null) { - //we want to skip 'R' prefix for entity definition names - int prefixIndex = (def instanceof EntityDefinition) ? 1 : 0; - prefix = Character.toString(def.getJpaName().charAt(prefixIndex)).toLowerCase(); - } else { - prefix = Character.toString(qname.getLocalPart().charAt(0)).toLowerCase(); - } - - int index = 1; - String alias = prefix; - while (hasAlias(alias)) { - alias = prefix + Integer.toString(index); - index++; - - if (index > 5) { - throw new IllegalStateException("Alias index for definition '" + def - + "' is more than 5? This probably should not happen."); - } - } - - return alias; - } - - private boolean hasAlias(String alias) { - return aliases.containsValue(alias); - } - - public boolean hasAlias(ItemPath path) { - return aliases.get(path) != null; - } -} diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/QueryDefinitionRegistry.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/QueryDefinitionRegistry.java deleted file mode 100644 index 1ae965c39ed..00000000000 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/QueryDefinitionRegistry.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (c) 2010-2014 Evolveum - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.evolveum.midpoint.repo.sql.query; - -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.repo.sql.data.common.RObject; -import com.evolveum.midpoint.repo.sql.data.common.other.RObjectType; -import com.evolveum.midpoint.repo.sql.query.definition.ClassDefinitionParser; -import com.evolveum.midpoint.repo.sql.query.definition.Definition; -import com.evolveum.midpoint.repo.sql.query.definition.EntityDefinition; -import com.evolveum.midpoint.repo.sql.util.ClassMapper; -import com.evolveum.midpoint.schema.constants.ObjectTypes; -import com.evolveum.midpoint.util.DebugDumpable; -import com.evolveum.midpoint.util.DebugUtil; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; - -import org.apache.commons.lang.Validate; - -import javax.xml.namespace.QName; - -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -/** - * @author lazyman - */ -public class QueryDefinitionRegistry implements DebugDumpable { - - private static final Trace LOGGER = TraceManager.getTrace(QueryDefinitionRegistry.class); - private static final Map definitions; - - private static QueryDefinitionRegistry registry; - - static { - LOGGER.trace("Initializing query definition registry."); - ClassDefinitionParser classDefinitionParser = new ClassDefinitionParser(); - - Map map = new HashMap(); - Collection types = ClassMapper.getKnownTypes(); - for (RObjectType type : types) { - Class clazz = type.getClazz(); - if (!RObject.class.isAssignableFrom(clazz)) { - continue; - } - - Definition definition = classDefinitionParser.parseObjectTypeClass(clazz); - if (definition == null) { - continue; - } - - ObjectTypes objectType = ClassMapper.getObjectTypeForHQLType(type); - map.put(objectType.getQName(), (EntityDefinition) definition); - } - - definitions = Collections.unmodifiableMap(map); - } - - private QueryDefinitionRegistry() { - } - - public static QueryDefinitionRegistry getInstance() { - if (registry == null) { - registry = new QueryDefinitionRegistry(); - } - - return registry; - } - - @Override - public String debugDump() { - return debugDump(0); - } - - @Override - public String debugDump(int indent) { - StringBuilder builder = new StringBuilder(); - DebugUtil.indentDebugDump(builder, indent); - Collection defCollection = definitions.values(); - for (Definition definition : defCollection) { - builder.append(definition.debugDump()).append('\n'); - } - - return builder.toString(); - } - - public D findDefinition(Class type, ItemPath path, Class definitionType) { - Validate.notNull(type, "Type must not be null."); - Validate.notNull(definitionType, "Definition type must not be null."); - - EntityDefinition entityDef = definitions.get(ObjectTypes.getObjectType(type).getQName()); - return entityDef.findDefinition(path, definitionType); - } -} diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/QueryEngine.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/QueryEngine.java deleted file mode 100644 index 5e7605298df..00000000000 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/QueryEngine.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.evolveum.midpoint.repo.sql.query; - -import com.evolveum.midpoint.prism.PrismContext; -import com.evolveum.midpoint.prism.query.ObjectQuery; -import com.evolveum.midpoint.repo.sql.SqlRepositoryConfiguration; -import com.evolveum.midpoint.repo.sql.query.custom.CustomQuery; -import com.evolveum.midpoint.repo.sql.query.custom.ShadowQueryWithDisjunction; -import com.evolveum.midpoint.repo.sql.util.GetObjectResult; -import com.evolveum.midpoint.schema.GetOperationOptions; -import com.evolveum.midpoint.schema.SelectorOptions; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; - -import org.hibernate.Criteria; -import org.hibernate.Session; -import org.hibernate.criterion.Projections; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -/** - * @author lazyman - */ -public class QueryEngine { - - private static final List queryLibrary = new ArrayList<>(); - - static { - queryLibrary.add(new ShadowQueryWithDisjunction()); -// queryLibrary.add(new OrgFilterQuery()); - } - - private SqlRepositoryConfiguration repoConfiguration; - private PrismContext prismContext; - - public QueryEngine(SqlRepositoryConfiguration config, PrismContext prismContext) { - this.repoConfiguration = config; - this.prismContext = prismContext; - } - - public RQuery interpret(ObjectQuery query, Class type, - Collection> options, - boolean countingObjects, Session session) throws QueryException { - - for (CustomQuery custom : queryLibrary) { - if (custom.match(query, type, options, countingObjects)) { - custom.init(repoConfiguration, prismContext); - - RQuery rQuery = custom.createQuery(query, type, options, countingObjects, session); - if (rQuery != null) { - return rQuery; - } - } - } - - QueryInterpreter interpreter = new QueryInterpreter(repoConfiguration); - Criteria criteria = interpreter.interpret(query, type, options, prismContext, countingObjects, session); - if (countingObjects) { - criteria.setProjection(Projections.rowCount()); - } else { - criteria.setResultTransformer(GetObjectResult.RESULT_TRANSFORMER); - } - - return new RQueryCriteriaImpl(criteria); - } -} diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/QueryException.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/QueryException.java index c50a9537840..340c85364c0 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/QueryException.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/QueryException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2013 Evolveum + * Copyright (c) 2010-2017 Evolveum * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/QueryInterpreter.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/QueryInterpreter.java deleted file mode 100644 index 72a9304c21e..00000000000 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/QueryInterpreter.java +++ /dev/null @@ -1,292 +0,0 @@ -/* - * Copyright (c) 2010-2013 Evolveum - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.evolveum.midpoint.repo.sql.query; - -import com.evolveum.midpoint.prism.PrismContext; -import com.evolveum.midpoint.prism.path.NameItemPathSegment; -import com.evolveum.midpoint.prism.polystring.PolyString; -import com.evolveum.midpoint.prism.query.ObjectFilter; -import com.evolveum.midpoint.prism.query.ObjectPaging; -import com.evolveum.midpoint.prism.query.ObjectQuery; -import com.evolveum.midpoint.repo.sql.ObjectPagingAfterOid; -import com.evolveum.midpoint.repo.sql.SqlRepositoryConfiguration; -import com.evolveum.midpoint.repo.sql.query.definition.Definition; -import com.evolveum.midpoint.repo.sql.query.definition.EntityDefinition; -import com.evolveum.midpoint.repo.sql.query.matcher.DefaultMatcher; -import com.evolveum.midpoint.repo.sql.query.matcher.Matcher; -import com.evolveum.midpoint.repo.sql.query.matcher.PolyStringMatcher; -import com.evolveum.midpoint.repo.sql.query.matcher.StringMatcher; -import com.evolveum.midpoint.repo.sql.query.restriction.Restriction; -import com.evolveum.midpoint.repo.sql.util.ClassMapper; -import com.evolveum.midpoint.schema.GetOperationOptions; -import com.evolveum.midpoint.schema.SelectorOptions; -import com.evolveum.midpoint.util.ClassPathUtil; -import com.evolveum.midpoint.util.exception.SystemException; -import com.evolveum.midpoint.util.logging.LoggingUtils; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; -import org.apache.commons.lang.Validate; -import org.apache.commons.lang.reflect.ConstructorUtils; -import org.hibernate.Criteria; -import org.hibernate.Session; -import org.hibernate.criterion.Criterion; -import org.hibernate.criterion.Order; -import org.hibernate.criterion.ProjectionList; -import org.hibernate.criterion.Projections; -import org.hibernate.criterion.Restrictions; - -import java.lang.reflect.Modifier; -import java.util.*; - -/** - * @author lazyman - */ -public class QueryInterpreter { - - private static final Trace LOGGER = TraceManager.getTrace(QueryInterpreter.class); - private static final Set AVAILABLE_RESTRICTIONS; - private static final Map AVAILABLE_MATCHERS; - - static { - Set restrictions = new HashSet(); - - String packageName = Restriction.class.getPackage().getName(); - Set classes = ClassPathUtil.listClasses(packageName); - LOGGER.debug("Found {} classes in package {}.", new Object[]{classes.size(), packageName}); - for (Class clazz : classes) { - if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) { - //we don't need interfaces and abstract classes - continue; - } - - if (!Restriction.class.isAssignableFrom(clazz)) { - //we don't need classes that don't inherit from Restriction - continue; - } - - try { - Restriction restriction = (Restriction) ConstructorUtils.invokeConstructor(clazz, null); - restrictions.add(restriction); - - LOGGER.debug("Added '{}' instance to available restrictions.", - new Object[]{restriction.getClass().getName()}); - } catch (Exception ex) { - LoggingUtils.logException(LOGGER, "Error occurred during query interpreter initialization", ex); - if (ex instanceof SystemException) { - throw (SystemException) ex; - } - throw new SystemException(ex.getMessage(), ex); - } - } - - AVAILABLE_RESTRICTIONS = Collections.unmodifiableSet(restrictions); - } - - static { - Map matchers = new HashMap(); - //default matcher with null key - matchers.put(null, new DefaultMatcher()); - matchers.put(PolyString.class, new PolyStringMatcher()); - matchers.put(String.class, new StringMatcher()); - - - AVAILABLE_MATCHERS = Collections.unmodifiableMap(matchers); - } - - private SqlRepositoryConfiguration repoConfiguration; - - public QueryInterpreter(SqlRepositoryConfiguration repoConfiguration) { - this.repoConfiguration = repoConfiguration; - } - - public SqlRepositoryConfiguration getRepoConfiguration() { - return repoConfiguration; - } - - public Criteria interpret(ObjectQuery query, Class type, - Collection> options, PrismContext prismContext, - boolean countingObjects, Session session) throws QueryException { - Validate.notNull(type, "Type must not be null."); - Validate.notNull(session, "Session must not be null."); - Validate.notNull(prismContext, "Prism context must not be null."); - - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("Interpreting query for type '{}', query:\n{}", new Object[]{type, query}); - } - - Criteria criteria; - if (query != null && query.getFilter() != null) { - criteria = interpretQuery(query, type, prismContext, session); - } else { - criteria = session.createCriteria(ClassMapper.getHQLTypeClass(type)); - } - - if (query != null && query.getPaging() instanceof ObjectPagingAfterOid) { - ObjectPagingAfterOid paging = (ObjectPagingAfterOid) query.getPaging(); - if (paging.getOidGreaterThan() != null) { - criteria = criteria.add(Restrictions.gt("oid", paging.getOidGreaterThan())); - } - } - - if (!countingObjects && query != null && query.getPaging() != null) { - if (query.getPaging() instanceof ObjectPagingAfterOid) { - criteria = updatePagingAndSortingByOid(criteria, query); // very special case - ascending ordering by OID (nothing more) - } else { - criteria = updatePagingAndSorting(criteria, type, query.getPaging()); - } - } - - if (!countingObjects) { - ProjectionList projections = Projections.projectionList(); - projections.add(Projections.property("fullObject")); - - projections.add(Projections.property("stringsCount")); - projections.add(Projections.property("longsCount")); - projections.add(Projections.property("datesCount")); - projections.add(Projections.property("referencesCount")); - projections.add(Projections.property("polysCount")); - projections.add(Projections.property("booleansCount")); - - criteria.setProjection(projections); - } - - return criteria; - } - - private Criteria interpretQuery(ObjectQuery query, Class type, PrismContext prismContext, - Session session) throws QueryException { - ObjectFilter filter = query.getFilter(); - try { - QueryContext context = new QueryContext(this, type, query, prismContext, session); - - Criterion criterion = interpretFilter(filter, context, null); - - Criteria criteria = context.getCriteria(null); - criteria.add(criterion); - - return criteria; - } catch (QueryException ex) { - throw ex; - } catch (Exception ex) { - LOGGER.trace(ex.getMessage(), ex); - throw new QueryException(ex.getMessage(), ex); - } - } - - public Criterion interpretFilter(ObjectFilter filter, QueryContext context, Restriction parent) throws QueryException { - Restriction restriction = findAndCreateRestriction(filter, context, parent); - Criterion criterion = restriction.interpret(); - return criterion; - } - - public Criteria updatePagingAndSorting(Criteria query, Class type, ObjectPaging paging) { - if (paging == null) { - return query; - } - if (paging.getOffset() != null) { - query = query.setFirstResult(paging.getOffset()); - } - if (paging.getMaxSize() != null) { - query = query.setMaxResults(paging.getMaxSize()); - } - - if (paging.getDirection() == null && (paging.getOrderBy() == null || paging.getOrderBy().isEmpty())) { - return query; - } - - QueryDefinitionRegistry registry = QueryDefinitionRegistry.getInstance(); - if (paging.getOrderBy() == null || paging.getOrderBy().isEmpty() || paging.getOrderBy().size() > 1 || !(paging.getOrderBy().first() instanceof NameItemPathSegment)) { - LOGGER.warn("Ordering by property path with size not equal 1 is not supported '" + paging.getOrderBy() - + "'."); - return query; - } - EntityDefinition definition = registry.findDefinition(type, null, EntityDefinition.class); - Definition def = definition.findDefinition(paging.getOrderBy(), Definition.class); - if (def == null) { - LOGGER.warn("Unknown path '" + paging.getOrderBy() + "', couldn't find definition for it, " - + "list will not be ordered by it."); - return query; - } - - String propertyName = def.getJpaName(); - if (PolyString.class.equals(def.getJaxbType())) { - propertyName += ".orig"; - } - - if (paging.getDirection() != null) { - switch (paging.getDirection()) { - case ASCENDING: - query = query.addOrder(Order.asc(propertyName)); - break; - case DESCENDING: - query = query.addOrder(Order.desc(propertyName)); - break; - } - } else { - query = query.addOrder(Order.asc(propertyName)); - } - - - return query; - } - - protected Criteria updatePagingAndSortingByOid(Criteria criteria, ObjectQuery query) { - ObjectPagingAfterOid paging = (ObjectPagingAfterOid) query.getPaging(); - if (paging.getOrderBy() != null || paging.getDirection() != null || paging.getOffset() != null) { - throw new IllegalArgumentException("orderBy, direction nor offset is allowed on ObjectPagingAfterOid"); - } - criteria = criteria.addOrder(Order.asc("oid")); - if (paging.getMaxSize() != null) { - criteria = criteria.setMaxResults(paging.getMaxSize()); - } - return criteria; - } - - public Matcher findMatcher(T value) { - return findMatcher(value != null ? (Class) value.getClass() : null); - } - - public Matcher findMatcher(Class type) { - Matcher matcher = AVAILABLE_MATCHERS.get(type); - if (matcher == null) { - //we return default matcher - matcher = AVAILABLE_MATCHERS.get(null); - } - - return matcher; - } - - public Restriction findAndCreateRestriction(T filter, QueryContext context, - Restriction parent) throws QueryException { - - for (Restriction restriction : AVAILABLE_RESTRICTIONS) { - Restriction res = restriction.newInstance(); - res.setContext(context); - if (!res.canHandle(filter)) { - continue; - } - res.setParent(parent); - res.setFilter(filter); - - return res; - } - - LOGGER.error("Couldn't find proper restriction that can handle filter '{}'.", new Object[]{filter.debugDump()}); - throw new QueryException("Couldn't find proper restriction that can handle '" + filter + "'"); - } -} diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/RQueryCriteriaImpl.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/RQueryCriteriaImpl.java deleted file mode 100644 index 5373fbcf19f..00000000000 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/RQueryCriteriaImpl.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2010-2013 Evolveum - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.evolveum.midpoint.repo.sql.query; - -import org.apache.commons.lang.Validate; -import org.hibernate.Criteria; -import org.hibernate.HibernateException; -import org.hibernate.ScrollMode; -import org.hibernate.ScrollableResults; - -import java.util.List; - -/** - * @author lazyman - */ -public class RQueryCriteriaImpl implements RQuery { - - private Criteria criteria; - - public RQueryCriteriaImpl(Criteria criteria) { - Validate.notNull(criteria, "Criteria must not be null."); - this.criteria = criteria; - } - - @Override - public List list() throws HibernateException { - return criteria.list(); - } - - @Override - public Object uniqueResult() throws HibernateException { - return criteria.uniqueResult(); - } - - @Override - public ScrollableResults scroll(ScrollMode mode) throws HibernateException { - return criteria.scroll(mode); - } - - public Criteria getCriteria() { - return criteria; - } -} diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/custom/CustomQuery.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/custom/CustomQuery.java deleted file mode 100644 index ce8b3343ee6..00000000000 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/custom/CustomQuery.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2010-2014 Evolveum - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.evolveum.midpoint.repo.sql.query.custom; - -import com.evolveum.midpoint.prism.PrismContext; -import com.evolveum.midpoint.prism.query.ObjectQuery; -import com.evolveum.midpoint.repo.sql.SqlRepositoryConfiguration; -import com.evolveum.midpoint.repo.sql.query.RQuery; -import com.evolveum.midpoint.schema.GetOperationOptions; -import com.evolveum.midpoint.schema.SelectorOptions; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; - -import org.hibernate.Session; - -import java.util.Collection; - -/** - * @author lazyman - */ -public abstract class CustomQuery { - - private SqlRepositoryConfiguration repoConfiguration; - private PrismContext prismContext; - - protected SqlRepositoryConfiguration getRepoConfiguration() { - return repoConfiguration; - } - - protected PrismContext getPrismContext() { - return prismContext; - } - - public void init(SqlRepositoryConfiguration repoConfiguration, PrismContext prismContext) { - this.repoConfiguration = repoConfiguration; - this.prismContext = prismContext; - } - - public abstract boolean match(ObjectQuery objectQuery, Class type, - Collection> options, boolean countingObjects); - - public abstract RQuery createQuery(ObjectQuery objectQuery, Class type, - Collection> options, boolean countingObjects, - Session session); -} diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/custom/OrgFilterQuery.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/custom/OrgFilterQuery.java deleted file mode 100644 index c7134b9a15e..00000000000 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/custom/OrgFilterQuery.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (c) 2010-2014 Evolveum - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.evolveum.midpoint.repo.sql.query.custom; - -import com.evolveum.midpoint.prism.query.ObjectQuery; -import com.evolveum.midpoint.prism.query.OrgFilter; -import com.evolveum.midpoint.repo.sql.query.RQuery; -import com.evolveum.midpoint.repo.sql.query.RQueryImpl; -import com.evolveum.midpoint.repo.sql.util.ClassMapper; -import com.evolveum.midpoint.repo.sql.util.GetObjectResult; -import com.evolveum.midpoint.schema.GetOperationOptions; -import com.evolveum.midpoint.schema.SelectorOptions; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; - -import org.hibernate.Query; -import org.hibernate.Session; - -import java.util.Collection; - -/** - * @author lazyman - * - * CURRENTLY UNUSED. - */ -public class OrgFilterQuery extends CustomQuery { - - private static final Trace LOGGER = TraceManager.getTrace(OrgFilterQuery.class); - - @Override - public boolean match(ObjectQuery objectQuery, Class type, - Collection> options, boolean countingObjects) { - - if (objectQuery == null || !(objectQuery.getFilter() instanceof OrgFilter)) { - return false; - } - - OrgFilter filter = (OrgFilter) objectQuery.getFilter(); - if (filter.isRoot()) { - return false; - } - - return true; - } - - @Override - public RQuery createQuery(ObjectQuery objectQuery, Class type, - Collection> options, boolean countingObjects, - Session session) { - - OrgFilter filter = (OrgFilter) objectQuery.getFilter(); - - LOGGER.trace("createOrgQuery {}, counting={}, filter={}", new Object[]{type.getSimpleName(), countingObjects, filter}); - - if (countingObjects) { - return countQuery(filter, type, session); - } - - StringBuilder sb = new StringBuilder(); - if (OrgFilter.Scope.ONE_LEVEL.equals(filter.getScope())) { - sb.append("select o.fullObject,o.stringsCount,o.longsCount,o.datesCount,o.referencesCount,o.polysCount,o.booleansCount from "); - sb.append(ClassMapper.getHQLType(type)).append(" as o where o.oid in (select distinct p.ownerOid from RObjectReference p where p.targetOid=:oid and p.referenceType=0)"); - } else { - sb.append("select o.fullObject,o.stringsCount,o.longsCount,o.datesCount,o.referencesCount,o.polysCount,o.booleansCount from "); - sb.append(ClassMapper.getHQLType(type)).append(" as o where o.oid in ("); - //todo change to sb.append("select d.descendantOid from ROrgClosure as d where d.ancestorOid = :oid and d.descendantOid != :oid)"); - sb.append("select distinct d.descendantOid from ROrgClosure as d where d.ancestorOid = :oid and d.descendantOid != :oid)"); - } - Query query = session.createQuery(sb.toString()); - query.setString("oid", filter.getOrgRef().getOid()); - query.setResultTransformer(GetObjectResult.RESULT_TRANSFORMER); - - return new RQueryImpl(query); - } - - private RQuery countQuery(OrgFilter filter, Class type, Session session) { - StringBuilder sb = new StringBuilder(); - if (OrgFilter.Scope.ONE_LEVEL.equals(filter.getScope())) { - sb.append("select count(distinct o.oid) from "); - sb.append(ClassMapper.getHQLType(type)).append(" o left join o.parentOrgRef p where p.targetOid=:oid"); - } else { - if (ObjectType.class.equals(type)) { - //todo change to select count(*) from ROrgClosure d where d.ancestorOid = :oid - sb.append("select count(distinct d.descendantOid) from ROrgClosure d where d.ancestorOid = :oid and d.descendantOid != :oid"); - } else { - //todo change to sb.append("select count(d.descendantOid) from ").append(ClassMapper.getHQLType(type)); - sb.append("select count(distinct d.descendantOid) from ").append(ClassMapper.getHQLType(type)); - sb.append(" as o left join o.descendants as d where d.ancestorOid = :oid and d.descendantOid != :oid"); - } - } - Query query = session.createQuery(sb.toString()); - query.setString("oid", filter.getOrgRef().getOid()); - - return new RQueryImpl(query); - } -} diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/custom/ShadowQueryWithDisjunction.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/custom/ShadowQueryWithDisjunction.java deleted file mode 100644 index 999c88668ac..00000000000 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/custom/ShadowQueryWithDisjunction.java +++ /dev/null @@ -1,268 +0,0 @@ -/* - * Copyright (c) 2010-2014 Evolveum - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.evolveum.midpoint.repo.sql.query.custom; - -import com.evolveum.midpoint.prism.PrismPropertyValue; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.prism.path.NameItemPathSegment; -import com.evolveum.midpoint.prism.polystring.PolyString; -import com.evolveum.midpoint.prism.query.AndFilter; -import com.evolveum.midpoint.prism.query.EqualFilter; -import com.evolveum.midpoint.prism.query.ObjectFilter; -import com.evolveum.midpoint.prism.query.ObjectPaging; -import com.evolveum.midpoint.prism.query.ObjectQuery; -import com.evolveum.midpoint.prism.query.OrFilter; -import com.evolveum.midpoint.prism.query.RefFilter; -import com.evolveum.midpoint.repo.sql.data.common.type.RObjectExtensionType; -import com.evolveum.midpoint.repo.sql.query.QueryDefinitionRegistry; -import com.evolveum.midpoint.repo.sql.query.RQuery; -import com.evolveum.midpoint.repo.sql.query.RQueryCriteriaImpl; -import com.evolveum.midpoint.repo.sql.query.definition.Definition; -import com.evolveum.midpoint.repo.sql.query.definition.EntityDefinition; -import com.evolveum.midpoint.repo.sql.util.ClassMapper; -import com.evolveum.midpoint.repo.sql.util.GetObjectResult; -import com.evolveum.midpoint.repo.sql.util.RUtil; -import com.evolveum.midpoint.schema.GetOperationOptions; -import com.evolveum.midpoint.schema.SchemaConstantsGenerated; -import com.evolveum.midpoint.schema.SelectorOptions; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; - -import org.hibernate.Criteria; -import org.hibernate.Session; -import org.hibernate.criterion.Conjunction; -import org.hibernate.criterion.Criterion; -import org.hibernate.criterion.DetachedCriteria; -import org.hibernate.criterion.Disjunction; -import org.hibernate.criterion.Order; -import org.hibernate.criterion.ProjectionList; -import org.hibernate.criterion.Projections; -import org.hibernate.criterion.Restrictions; -import org.hibernate.criterion.Subqueries; -import org.hibernate.sql.JoinType; - -import javax.xml.namespace.QName; - -import java.util.Collection; - -/** - * A hack oriented towards queries in the form - * resourceRef = X && (attributes/uid = Y || attributes/name = Z) - * - * The reason is that default implementation of such queries returns shadows that comply with - * both branches of the disjunction twice. Changing the way of dealing with such queries seriously - * is not possible at this moment (moreover, it brings along unclear performance consequences). - * Therefore this hack. - * - * @author mederly - */ -public class ShadowQueryWithDisjunction extends CustomQuery { - - private static final Trace LOGGER = TraceManager.getTrace(ShadowQueryWithDisjunction.class); - - static private class ParsedQuery { - RefFilter refFilter; - EqualFilter eqUidFilter, eqNameFilter; - } - - @Override - public boolean match(ObjectQuery objectQuery, Class type, - Collection> options, boolean countingObjects) { - - if (!ShadowType.class.equals(type)) { - return false; - } - return parse(objectQuery) != null; - } - - private ParsedQuery parse(ObjectQuery objectQuery) { - - if (objectQuery == null || !(objectQuery.getFilter() instanceof AndFilter)) { - return null; - } - - AndFilter andFilter = (AndFilter) objectQuery.getFilter(); - - RefFilter refFilter = null; - OrFilter orFilter = null; - for (ObjectFilter filter : andFilter.getConditions()) { - if (filter instanceof RefFilter) { - refFilter = (RefFilter) filter; - } else if (filter instanceof OrFilter) { - orFilter = (OrFilter) filter; - } else { - return null; - } - } - if (refFilter == null || orFilter == null) { - return null; - } - if (!new ItemPath(ShadowType.F_RESOURCE_REF).equivalent(refFilter.getPath())) { - return null; - } - if (refFilter.getValues() == null || refFilter.getValues().size() != 1) { - return null; - } - - EqualFilter eqUidFilter = null; - EqualFilter eqNameFilter = null; -// ItemPath uidPath = new ItemPath(ShadowType.F_ATTRIBUTES, SchemaConstantsGenerated.ICF_S_UID); - if (orFilter.getConditions() != null && !orFilter.getConditions().isEmpty()){ - if (orFilter.getConditions().size() != 2){ - return null; - } - } - ItemPath namePath = new ItemPath(ShadowType.F_ATTRIBUTES, SchemaConstantsGenerated.ICF_S_NAME); - for (ObjectFilter filter : orFilter.getConditions()) { - if (!(filter instanceof EqualFilter)) { - return null; - } - EqualFilter equalFilter = (EqualFilter) filter; - if (namePath.equivalent(equalFilter.getPath())) { - eqNameFilter = equalFilter; - } else if (ShadowType.F_ATTRIBUTES.equals(((NameItemPathSegment)equalFilter.getPath().first()).getName())) { - eqUidFilter = equalFilter; - } else { - return null; - } - } - if (eqUidFilter == null || eqNameFilter == null) { - return null; - } - if (eqUidFilter.getValues() == null || eqUidFilter.getValues().size() != 1) { - return null; - } - if (eqNameFilter.getValues() == null || eqNameFilter.getValues().size() != 1) { - return null; - } - ParsedQuery parsedQuery = new ParsedQuery(); - parsedQuery.refFilter = refFilter; - parsedQuery.eqNameFilter = eqNameFilter; - parsedQuery.eqUidFilter = eqUidFilter; - return parsedQuery; - } - - @Override - public RQuery createQuery(ObjectQuery objectQuery, Class type, - Collection> options, boolean countingObjects, - Session session) { - - DetachedCriteria c1 = DetachedCriteria.forClass(ClassMapper.getHQLTypeClass(ShadowType.class), "s"); - c1.createCriteria("strings", "s1", JoinType.LEFT_OUTER_JOIN); - - ParsedQuery parsedQuery = parse(objectQuery); - Conjunction conjunction = Restrictions.conjunction(); - conjunction.add(Restrictions.eq("resourceRef.targetOid", parsedQuery.refFilter.getValues().get(0).getOid())); - Disjunction disjunction = Restrictions.disjunction(); - disjunction.add(createAttributeEq(parsedQuery.eqUidFilter, parsedQuery.eqUidFilter.getPath().lastNamed().getName())); - disjunction.add(createAttributeEq(parsedQuery.eqNameFilter, SchemaConstantsGenerated.ICF_S_NAME)); - conjunction.add(disjunction); - c1.add(conjunction); - - if (countingObjects) { - c1.setProjection(Projections.countDistinct("s.oid")); - return new RQueryCriteriaImpl(c1.getExecutableCriteria(session)); - } - - c1.setProjection(Projections.distinct(Projections.property("s.oid"))); - - Criteria cMain = session.createCriteria(ClassMapper.getHQLTypeClass(ShadowType.class), "o"); - cMain.add(Subqueries.propertyIn("oid", c1)); - - if (objectQuery != null && objectQuery.getPaging() != null) { - cMain = updatePagingAndSorting(cMain, type, objectQuery.getPaging()); - } - - ProjectionList projections = Projections.projectionList(); - projections.add(Projections.property("fullObject")); - projections.add(Projections.property("stringsCount")); - projections.add(Projections.property("longsCount")); - projections.add(Projections.property("datesCount")); - projections.add(Projections.property("referencesCount")); - projections.add(Projections.property("polysCount")); - projections.add(Projections.property("booleansCount")); - - cMain.setProjection(projections); - - cMain.setResultTransformer(GetObjectResult.RESULT_TRANSFORMER); - return new RQueryCriteriaImpl(cMain); - } - - private Criterion createAttributeEq(EqualFilter attributeEqFilter, QName attributeName) { - Conjunction conjunction = Restrictions.conjunction(); - conjunction.add(Restrictions.eq("s1.ownerType", RObjectExtensionType.ATTRIBUTES)); - conjunction.add(Restrictions.eq("s1.name", RUtil.qnameToString(attributeName))); - conjunction.add(Restrictions.eq("s1.value", ((PrismPropertyValue) attributeEqFilter.getValues().get(0)).getValue())); - return conjunction; - } - - // copied from QueryInterpreter, todo refactor to some util class - public Criteria updatePagingAndSorting(Criteria query, Class type, ObjectPaging paging) { - if (paging == null) { - return query; - } - if (paging.getOffset() != null) { - query = query.setFirstResult(paging.getOffset()); - } - if (paging.getMaxSize() != null) { - query = query.setMaxResults(paging.getMaxSize()); - } - - if (paging.getDirection() == null && (paging.getOrderBy() == null || paging.getOrderBy().isEmpty())) { - return query; - } - - QueryDefinitionRegistry registry = QueryDefinitionRegistry.getInstance(); - // PropertyPath path = new - // XPathHolder(paging.getOrderBy()).toPropertyPath(); - if (paging.getOrderBy() == null || paging.getOrderBy().isEmpty() || paging.getOrderBy().size() > 1 || !(paging.getOrderBy().first() instanceof NameItemPathSegment)) { - LOGGER.warn("Ordering by property path with size not equal 1 is not supported '" + paging.getOrderBy() - + "'."); - return query; - } - EntityDefinition definition = registry.findDefinition(type, null, EntityDefinition.class); - Definition def = definition.findDefinition(paging.getOrderBy(), Definition.class); - if (def == null) { - LOGGER.warn("Unknown path '" + paging.getOrderBy() + "', couldn't find definition for it, " - + "list will not be ordered by it."); - return query; - } - - String propertyName = def.getJpaName(); - if (PolyString.class.equals(def.getJaxbType())) { - propertyName += ".orig"; - } - - if (paging.getDirection() != null) { - switch (paging.getDirection()) { - case ASCENDING: - query = query.addOrder(Order.asc(propertyName)); - break; - case DESCENDING: - query = query.addOrder(Order.desc(propertyName)); - break; - } - } else { - query = query.addOrder(Order.asc(propertyName)); - } - - - return query; - } -} diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/matcher/DefaultMatcher.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/matcher/DefaultMatcher.java deleted file mode 100644 index 5a9160bfb63..00000000000 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/matcher/DefaultMatcher.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2010-2013 Evolveum - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.evolveum.midpoint.repo.sql.query.matcher; - -import com.evolveum.midpoint.repo.sql.query.QueryException; -import com.evolveum.midpoint.repo.sql.query.restriction.ItemRestrictionOperation; -import org.hibernate.criterion.Criterion; - -/** - * @author lazyman - */ -public class DefaultMatcher extends Matcher { - - @Override - public Criterion match(ItemRestrictionOperation operation, String propertyName, T value, String matcher) - throws QueryException { - - return basicMatch(operation, propertyName, value, false); - } -} diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/matcher/Matcher.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/matcher/Matcher.java deleted file mode 100644 index da2a6e265f2..00000000000 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/matcher/Matcher.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2010-2013 Evolveum - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.evolveum.midpoint.repo.sql.query.matcher; - -import com.evolveum.midpoint.repo.sql.query.QueryException; -import com.evolveum.midpoint.repo.sql.query.restriction.ItemRestrictionOperation; -import org.hibernate.criterion.Criterion; -import org.hibernate.criterion.MatchMode; -import org.hibernate.criterion.Restrictions; -import org.hibernate.criterion.SimpleExpression; - -/** - * @author lazyman - */ -public abstract class Matcher { - - /** - * Create hibernate {@link Criterion} based on matcher defined in filter. - * - * @param operation - * @param propertyName - * @param value - * @param matcher Now type of {@link String}, but will be updated to {@link javax.xml.namespace.QName} - * type after query-api update - * @return - * @throws QueryException - */ - public abstract Criterion match(ItemRestrictionOperation operation, String propertyName, T value, String matcher) - throws QueryException; - - protected Criterion basicMatch(ItemRestrictionOperation operation, String propertyName, Object value, - boolean ignoreCase) throws QueryException { - Criterion criterion; - switch (operation) { - case EQ: - if (value == null) { - criterion = Restrictions.isNull(propertyName); - } else { - criterion = Restrictions.eq(propertyName, value); - } - break; - case GT: - criterion = Restrictions.gt(propertyName, value); - break; - case GE: - criterion = Restrictions.ge(propertyName, value); - break; - case LT: - criterion = Restrictions.lt(propertyName, value); - break; - case LE: - criterion = Restrictions.le(propertyName, value); - break; - case NOT_NULL: - criterion = Restrictions.isNotNull(propertyName); - break; - case NULL: - criterion = Restrictions.isNull(propertyName); - break; - case STARTS_WITH: - criterion = Restrictions.like(propertyName, (String) value, MatchMode.START); - break; - case ENDS_WITH: - criterion = Restrictions.like(propertyName, (String) value, MatchMode.END); - break; - case SUBSTRING: - criterion = Restrictions.like(propertyName, (String) value, MatchMode.ANYWHERE); - break; - default: - throw new QueryException("Unknown operation '" + operation + "'."); - } - - if (ignoreCase && (value instanceof String) && (criterion instanceof SimpleExpression)) { - criterion = ((SimpleExpression) criterion).ignoreCase(); - } - - return criterion; - } -} diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/matcher/PolyStringMatcher.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/matcher/PolyStringMatcher.java deleted file mode 100644 index 1b0ed3c6c22..00000000000 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/matcher/PolyStringMatcher.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) 2010-2013 Evolveum - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.evolveum.midpoint.repo.sql.query.matcher; - -import com.evolveum.midpoint.prism.match.PolyStringNormMatchingRule; -import com.evolveum.midpoint.prism.match.PolyStringOrigMatchingRule; -import com.evolveum.midpoint.prism.match.PolyStringStrictMatchingRule; -import com.evolveum.midpoint.prism.polystring.PolyString; -import com.evolveum.midpoint.repo.sql.data.common.embedded.RPolyString; -import com.evolveum.midpoint.repo.sql.query.QueryException; -import com.evolveum.midpoint.repo.sql.query.restriction.ItemRestrictionOperation; -import org.apache.commons.lang.StringUtils; -import org.hibernate.criterion.Conjunction; -import org.hibernate.criterion.Criterion; -import org.hibernate.criterion.Restrictions; - -/** - * @author lazyman - */ -public class PolyStringMatcher extends Matcher { - - //todo will be changed to QNames later (after query api update) - public static final String STRICT = PolyStringStrictMatchingRule.NAME.getLocalPart(); - public static final String ORIG = PolyStringOrigMatchingRule.NAME.getLocalPart(); - public static final String NORM = PolyStringNormMatchingRule.NAME.getLocalPart(); - - public static final String STRICT_IGNORE_CASE = "strictIgnoreCase"; - public static final String ORIG_IGNORE_CASE = "origIgnoreCase"; - public static final String NORM_IGNORE_CASE = "normIgnoreCase"; - - @Override - public Criterion match(ItemRestrictionOperation operation, String propertyName, PolyString value, String matcher) - throws QueryException { - - boolean ignoreCase = STRICT_IGNORE_CASE.equals(matcher) - || ORIG_IGNORE_CASE.equals(matcher) - || NORM_IGNORE_CASE.equals(matcher); - - if (StringUtils.isEmpty(matcher) - || STRICT.equals(matcher) || STRICT_IGNORE_CASE.equals(matcher)) { - Conjunction conjunction = Restrictions.conjunction(); - conjunction.add(createOrigMatch(operation, propertyName, value, ignoreCase)); - conjunction.add(createNormMatch(operation, propertyName, value, ignoreCase)); - - return conjunction; - } else if (ORIG.equals(matcher) || ORIG_IGNORE_CASE.equals(matcher)) { - return createOrigMatch(operation, propertyName, value, ignoreCase); - } else if (NORM.equals(matcher) || NORM_IGNORE_CASE.equals(matcher)) { - return createNormMatch(operation, propertyName, value, ignoreCase); - } else { - throw new QueryException("Unknown matcher '" + matcher + "'."); - } - } - - private Criterion createNormMatch(ItemRestrictionOperation operation, String propertyName, PolyString value, - boolean ignoreCase) throws QueryException { - - String realValue = value != null ? value.getNorm() : null; - return basicMatch(operation, propertyName + '.' + RPolyString.F_NORM, realValue, ignoreCase); - } - - private Criterion createOrigMatch(ItemRestrictionOperation operation, String propertyName, PolyString value, - boolean ignoreCase) throws QueryException { - - String realValue = value != null ? value.getOrig() : null; - return basicMatch(operation, propertyName + '.' + RPolyString.F_ORIG, realValue, ignoreCase); - } -} diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/matcher/StringMatcher.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/matcher/StringMatcher.java deleted file mode 100644 index 03ccd19295d..00000000000 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/matcher/StringMatcher.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2010-2013 Evolveum - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.evolveum.midpoint.repo.sql.query.matcher; - -import com.evolveum.midpoint.prism.match.StringIgnoreCaseMatchingRule; -import com.evolveum.midpoint.repo.sql.query.QueryException; -import com.evolveum.midpoint.repo.sql.query.restriction.ItemRestrictionOperation; -import org.hibernate.criterion.Criterion; - -/** - * @author lazyman - */ -public class StringMatcher extends Matcher { - - //todo will be changed to QName later (after query api update) - public static final String IGNORE_CASE = StringIgnoreCaseMatchingRule.NAME.getLocalPart(); - - @Override - public Criterion match(ItemRestrictionOperation operation, String propertyName, String value, String matcher) - throws QueryException { - - boolean ignoreCase = IGNORE_CASE.equalsIgnoreCase(matcher); - - return basicMatch(operation, propertyName, value, ignoreCase); - } -} diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/AndRestriction.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/AndRestriction.java deleted file mode 100644 index bc356978e68..00000000000 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/AndRestriction.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2010-2013 Evolveum - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.evolveum.midpoint.repo.sql.query.restriction; - -import com.evolveum.midpoint.prism.query.AndFilter; -import com.evolveum.midpoint.prism.query.ObjectFilter; -import com.evolveum.midpoint.repo.sql.query.QueryException; -import org.hibernate.criterion.Conjunction; -import org.hibernate.criterion.Criterion; -import org.hibernate.criterion.Restrictions; - -/** - * @author lazyman - */ -public class AndRestriction extends NaryLogicalRestriction { - - @Override - public boolean canHandle(ObjectFilter filter) { - if (!super.canHandle(filter)) { - return false; - } - - return (filter instanceof AndFilter); - } - - @Override - public Criterion interpret() throws QueryException { - validateFilter(filter); - Conjunction conjunction = Restrictions.conjunction(); - updateJunction(filter.getConditions(), conjunction); - - return conjunction; - } - - @Override - public AndRestriction newInstance() { - return new AndRestriction(); - } -} diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/AnyPropertyRestriction.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/AnyPropertyRestriction.java deleted file mode 100644 index 10c6760a285..00000000000 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/AnyPropertyRestriction.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (c) 2010-2013 Evolveum - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.evolveum.midpoint.repo.sql.query.restriction; - -import com.evolveum.midpoint.prism.ItemDefinition; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.prism.path.ItemPathSegment; -import com.evolveum.midpoint.prism.path.NameItemPathSegment; -import com.evolveum.midpoint.prism.query.ObjectFilter; -import com.evolveum.midpoint.prism.query.ValueFilter; -import com.evolveum.midpoint.repo.sql.data.common.any.RAnyConverter; -import com.evolveum.midpoint.repo.sql.data.common.any.RAnyValue; -import com.evolveum.midpoint.repo.sql.data.common.type.RObjectExtensionType; -import com.evolveum.midpoint.repo.sql.query.QueryException; -import com.evolveum.midpoint.repo.sql.query.definition.AnyDefinition; -import com.evolveum.midpoint.repo.sql.query.definition.Definition; -import com.evolveum.midpoint.repo.sql.util.RUtil; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import org.hibernate.criterion.Conjunction; -import org.hibernate.criterion.Criterion; -import org.hibernate.criterion.Restrictions; - -import javax.xml.namespace.QName; -import java.util.ArrayList; -import java.util.List; - -/** - * @author lazyman - */ -public class AnyPropertyRestriction extends ItemRestriction { - - private static final Trace LOGGER = TraceManager.getTrace(AnyPropertyRestriction.class); - - @Override - public boolean canHandle(ObjectFilter filter) throws QueryException { - if (!super.canHandle(filter)) { - return false; - } - - ValueFilter valFilter = (ValueFilter) filter; - ItemPath fullPath = valFilter.getFullPath(); - - List defPath = createDefinitionPath(fullPath); - return containsAnyDefinition(defPath) - || (fullPath.first().equivalent(new NameItemPathSegment(ObjectType.F_EXTENSION))) - || (fullPath.first().equivalent(new NameItemPathSegment(ShadowType.F_ATTRIBUTES))); - } - - private boolean containsAnyDefinition(List definitions) { - for (Definition definition : definitions) { - if (definition instanceof AnyDefinition) { - return true; - } - } - - return false; - } - - @Override - public Criterion interpretInternal(ValueFilter filter) throws QueryException { - - ItemDefinition itemDefinition = filter.getDefinition(); - QName name = itemDefinition.getName(); - QName type = itemDefinition.getTypeName(); - - if (name == null || type == null) { - throw new QueryException("Couldn't get name or type for queried item '" + itemDefinition + "'"); - } - - ItemPath anyItemPath = createAnyItemPath(filter.getParentPath(), filter.getDefinition()); - if (!getContext().hasAlias(anyItemPath)) { - QName anyTypeName = ((NameItemPathSegment) anyItemPath.last()).getName(); - LOGGER.trace("Condition item is from 'any' container, adding new criteria based on any type '{}'", - new Object[]{anyTypeName.getLocalPart()}); - addNewCriteriaToContext(anyItemPath, null, anyTypeName.getLocalPart()); - } - String propertyNamePrefix = getContext().getAlias(anyItemPath) + '.'; - - Conjunction conjunction = Restrictions.conjunction(); - - RObjectExtensionType ownerType = filter.getFullPath().first().equivalent(new NameItemPathSegment(ObjectType.F_EXTENSION)) ? - RObjectExtensionType.EXTENSION : RObjectExtensionType.ATTRIBUTES; - conjunction.add(Restrictions.eq(propertyNamePrefix + "ownerType", ownerType)); - - conjunction.add(Restrictions.eq(propertyNamePrefix + RAnyValue.F_NAME, RUtil.qnameToString(name))); - - Object testedValue = getValue(filter.getValues()); - Object value = RAnyConverter.getAggregatedRepoObject(testedValue); - conjunction.add(createCriterion(propertyNamePrefix + RAnyValue.F_VALUE, value, filter)); - - // todo what about "not"? but it would not work in this setting anyway (ownerType=A & name=B & value=C) - //conjunction.add(Restrictions.isNotNull(propertyNamePrefix + RAnyValue.F_VALUE)); - return conjunction; - } - - private ItemPath createAnyItemPath(ItemPath path, ItemDefinition itemDef) throws QueryException { - try { - List segments = new ArrayList(); -// segments.addAll(path.getSegments()); - // get any type name (e.g. clobs, strings, dates,...) based on definition - String anyTypeName = RAnyConverter.getAnySetType(itemDef); - segments.add(new NameItemPathSegment(new QName(RUtil.NS_SQL_REPO, anyTypeName))); - - return new ItemPath(segments); - } catch (SchemaException ex) { - throw new QueryException(ex.getMessage(), ex); - } - } - - @Override - public AnyPropertyRestriction newInstance() { - return new AnyPropertyRestriction(); - } -} diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/CollectionRestriction.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/CollectionRestriction.java deleted file mode 100644 index f14a279cae2..00000000000 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/CollectionRestriction.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2010-2013 Evolveum - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.evolveum.midpoint.repo.sql.query.restriction; - -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.prism.polystring.PolyString; -import com.evolveum.midpoint.prism.query.ObjectFilter; -import com.evolveum.midpoint.prism.query.ValueFilter; -import com.evolveum.midpoint.repo.sql.query.QueryContext; -import com.evolveum.midpoint.repo.sql.query.QueryException; -import com.evolveum.midpoint.repo.sql.query.definition.CollectionDefinition; -import com.evolveum.midpoint.repo.sql.query.definition.PropertyDefinition; -import org.hibernate.criterion.Criterion; - -/** - * @author lazyman - */ -public class CollectionRestriction extends ItemRestriction { - - @Override - public boolean canHandle(ObjectFilter filter) throws QueryException { - if (!super.canHandle(filter)) { - return false; - } - - ValueFilter valFilter = (ValueFilter) filter; - ItemPath fullPath = valFilter.getFullPath(); - - CollectionDefinition def = findProperDefinition(fullPath, CollectionDefinition.class); - if (def == null) { - return false; - } - - return def.getDefinition() instanceof PropertyDefinition; - } - - @Override - public Criterion interpretInternal(ValueFilter filter) throws QueryException { - ItemPath fullPath = filter.getFullPath(); - QueryContext context = getContext(); - CollectionDefinition def = findProperDefinition(fullPath, CollectionDefinition.class); - - String alias = context.getAlias(fullPath); - Object value = getValueFromFilter(filter, (PropertyDefinition) def.getDefinition()); - - // TODO what about not-null ? - - //custom propertyPath handling for PolyString (it's embedded entity, not a primitive) - if (value instanceof PolyString) { - return createCriterion(alias, value, filter); - } - - return createCriterion(alias + ".elements", value, filter); - } - - @Override - public Restriction newInstance() { - return new CollectionRestriction(); - } -} diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/InOidRestriction.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/InOidRestriction.java deleted file mode 100644 index 71368cdbe55..00000000000 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/InOidRestriction.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2010-2014 Evolveum - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.evolveum.midpoint.repo.sql.query.restriction; - -import com.evolveum.midpoint.prism.query.InOidFilter; -import com.evolveum.midpoint.prism.query.ObjectFilter; -import com.evolveum.midpoint.repo.sql.query.QueryException; -import org.hibernate.criterion.Criterion; -import org.hibernate.criterion.Restrictions; - -/** - * @author lazyman - */ -public class InOidRestriction extends Restriction { - - @Override - public Criterion interpret() throws QueryException { - String property = getContext().getAlias(null) + ".oid"; - - return Restrictions.in(property, filter.getOids()); - } - - @Override - public boolean canHandle(ObjectFilter filter) throws QueryException { - if (filter instanceof InOidFilter) { - return true; - } - - return false; - } - - @Override - public Restriction newInstance() { - return new InOidRestriction(); - } -} diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/ItemRestriction.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/ItemRestriction.java deleted file mode 100644 index e2d2335fd30..00000000000 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/ItemRestriction.java +++ /dev/null @@ -1,599 +0,0 @@ -/* - * Copyright (c) 2010-2013 Evolveum - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.evolveum.midpoint.repo.sql.query.restriction; - -import com.evolveum.midpoint.prism.PrismPropertyValue; -import com.evolveum.midpoint.prism.PrismValue; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.prism.path.ItemPathSegment; -import com.evolveum.midpoint.prism.path.NameItemPathSegment; -import com.evolveum.midpoint.prism.polystring.PolyString; -import com.evolveum.midpoint.prism.query.*; -import com.evolveum.midpoint.repo.sql.data.common.enums.SchemaEnum; -import com.evolveum.midpoint.repo.sql.query.QueryContext; -import com.evolveum.midpoint.repo.sql.query.QueryDefinitionRegistry; -import com.evolveum.midpoint.repo.sql.query.QueryException; -import com.evolveum.midpoint.repo.sql.query.QueryInterpreter; -import com.evolveum.midpoint.repo.sql.query.definition.*; -import com.evolveum.midpoint.repo.sql.query.matcher.Matcher; -import com.evolveum.midpoint.repo.sql.util.RUtil; -import com.evolveum.midpoint.schema.constants.ObjectTypes; -import com.evolveum.midpoint.util.QNameUtil; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; - -import org.apache.commons.lang.Validate; -import org.hibernate.Criteria; -import org.hibernate.criterion.Criterion; -import org.hibernate.criterion.Restrictions; -import org.hibernate.sql.JoinType; - -import javax.xml.namespace.QName; - -import java.util.*; - -/** - * @author lazyman - */ -public abstract class ItemRestriction extends Restriction { - - private static final Trace LOGGER = TraceManager.getTrace(ItemRestriction.class); - - @Override - public boolean canHandle(ObjectFilter filter) throws QueryException { - Validate.notNull(filter, "Object filter must not be null."); - if (!(filter instanceof ValueFilter)) { - return false; - } - return true; - } - - @Override - public Criterion interpret() throws QueryException { - - ItemPath path = filter.getFullPath(); - if (path != null) { - // at first we build criterias with aliases - updateQueryContext(path); - } - - Criterion main = interpretInternal(filter); - Criterion virtual = createVirtualCriterion(path); - if (virtual != null) { - return Restrictions.and(virtual, main); - } - - return main; - } - - public abstract Criterion interpretInternal(T filter) throws QueryException; - - private TypeRestriction findTypeRestrictionParent(Restriction restriction) { - if (restriction == null) { - return null; - } - - if (restriction instanceof TypeRestriction) { - return (TypeRestriction) restriction; - } - - return findTypeRestrictionParent(restriction.getParent()); - } - - private Set> findOtherPossibleParents() { - TypeRestriction typeRestriction = findTypeRestrictionParent(this); - ObjectTypes typeClass; - if (typeRestriction != null) { - TypeFilter filter = typeRestriction.getFilter(); - typeClass = ObjectTypes.getObjectTypeFromTypeQName(filter.getType()); - } else { - typeClass = ObjectTypes.getObjectType(getContext().getType()); - } - - Set> classes = new HashSet<>(); - classes.add(typeClass.getClassDefinition()); - - switch (typeClass) { - case OBJECT: - classes.addAll(ObjectTypes.getAllObjectTypes()); - break; - case FOCUS_TYPE: - classes.add(UserType.class); - case ABSTRACT_ROLE: - classes.add(RoleType.class); - classes.add(OrgType.class); - } - - LOGGER.trace("Found possible parents {} for entity definitions.", Arrays.toString(classes.toArray())); - return classes; - } - - protected T findProperDefinition(ItemPath path, Class clazz) { - QueryContext context = getContext(); - QueryDefinitionRegistry registry = QueryDefinitionRegistry.getInstance(); - if (!ObjectType.class.equals(context.getType())) { - return registry.findDefinition(context.getType(), path, clazz); - } - - //we should try to find property in descendant classes - for (Class type : findOtherPossibleParents()) { - Definition def = registry.findDefinition(type, path, clazz); - if (def != null) { - return (T) def; - } - } - - return null; - } - - protected EntityDefinition findProperEntityDefinition(ItemPath path) { - QueryContext context = getContext(); - QueryDefinitionRegistry registry = QueryDefinitionRegistry.getInstance(); - if (!ObjectType.class.equals(context.getType())) { - return registry.findDefinition(context.getType(), null, EntityDefinition.class); - } - - EntityDefinition entity = null; - // we should try to find property in descendant classes - for (Class type : findOtherPossibleParents()) { - entity = registry.findDefinition(type, null, EntityDefinition.class); - Definition def = entity.findDefinition(path, Definition.class); - if (def != null) { - break; - } - } - LOGGER.trace("Found proper entity definition for path {}, {}", path, entity.toString()); - return entity; - } - - //todo reimplement, use DefinitionHandlers or maybe another great concept - private void updateQueryContext(ItemPath path) throws QueryException { - LOGGER.trace("Updating query context based on path {}", new Object[]{path.toString()}); - EntityDefinition definition = findProperEntityDefinition(path); - - List segments = path.getSegments(); - - List propPathSegments = new ArrayList(); - ItemPath propPath; - for (ItemPathSegment segment : segments) { - QName qname = ItemPath.getName(segment); - if (ObjectType.F_METADATA.equals(qname)) { - continue; - } - // ugly hack: construction/resourceRef -> resourceRef - if (QNameUtil.match(AssignmentType.F_CONSTRUCTION, qname)) { - continue; - } - - // create new property path - propPathSegments.add(new NameItemPathSegment(qname)); - propPath = new ItemPath(propPathSegments); - // get entity query definition - if (QNameUtil.match(qname, ObjectType.F_EXTENSION) || QNameUtil.match(qname, ShadowType.F_ATTRIBUTES)) { - break; - } - - Definition childDef = definition.findDefinition(qname, Definition.class); - if (childDef == null) { - throw new QueryException("Definition '" + definition + "' doesn't contain child definition '" - + qname + "'. Please check your path in query, or query entity/attribute mappings. " - + "Full path was '" + path + "'."); - } - - //todo change this if instanceof and use DefinitionHandler [lazyman] - if (childDef instanceof EntityDefinition) { - EntityDefinition entityDef = (EntityDefinition) childDef; - if (!entityDef.isEmbedded()) { - //create new criteria - LOGGER.trace("Adding criteria '{}' to context based on sub path\n{}", - new Object[]{entityDef.getJpaName(), propPath.toString()}); - addNewCriteriaToContext(propPath, entityDef, entityDef.getJpaName()); - } else { - // we don't create new sub criteria, just add this new item path to aliases - addPathAliasToContext(propPath); - } - definition = entityDef; - } else if (childDef instanceof AnyDefinition) { - LOGGER.trace("Adding criteria '{}' to context based on sub path\n{}", - new Object[]{childDef.getJpaName(), propPath.toString()}); - addNewCriteriaToContext(propPath, childDef, childDef.getJpaName()); - break; - } else if (childDef instanceof CollectionDefinition) { - LOGGER.trace("Adding criteria '{}' to context based on sub path\n{}", - new Object[]{childDef.getJpaName(), propPath.toString()}); - addNewCriteriaToContext(propPath, childDef, childDef.getJpaName()); - Definition def = ((CollectionDefinition) childDef).getDefinition(); - if (def instanceof EntityDefinition) { - definition = (EntityDefinition) def; - } - } else if (childDef instanceof PropertyDefinition || childDef instanceof ReferenceDefinition) { - break; - } else { - //todo throw something here [lazyman] - throw new QueryException("Not implemented yet."); - } - } - } - - /** - * This method scans {@link ItemPath} in {@link ValueFilter} and looks for virtual properties, collections - * or entities in {@link QueryDefinitionRegistry}. - *

- * Virtual definitions offer additional query params, which can be used for filtering - this method updates - * criteria based on {@link VirtualQueryParam}. For example assignments and inducements are defined in two - * collections in schema ({@link com.evolveum.midpoint.xml.ns._public.common.common_3.AbstractRoleType}), - * but in repository ({@link com.evolveum.midpoint.repo.sql.data.common.RAbstractRole}) they are stored in - * single {@link java.util.Set}. - *

- * TODO: implement definition handlers to get rid of these methods with many instanceOf comparisons. - * - * @param path - * @return {@link Criterion} based on {@link VirtualQueryParam} - * @throws QueryException - */ - private Criterion createVirtualCriterion(ItemPath path) throws QueryException { - LOGGER.trace("Scanning path for virtual definitions to create criteria {}", new Object[]{path.toString()}); - - EntityDefinition definition = findProperEntityDefinition(path); - - List criterions = new ArrayList(); - - List segments = path.getSegments(); - List propPathSegments = new ArrayList(); - - ItemPath propPath; - for (ItemPathSegment segment : segments) { - QName qname = ItemPath.getName(segment); - if (ObjectType.F_METADATA.equals(qname)) { - continue; - } - // ugly hack: construction/resourceRef -> resourceRef - if (QNameUtil.match(AssignmentType.F_CONSTRUCTION, qname)) { - continue; - } - // create new property path - propPathSegments.add(new NameItemPathSegment(qname)); - propPath = new ItemPath(propPathSegments); - - if (QNameUtil.match(qname, ObjectType.F_EXTENSION) || QNameUtil.match(qname, ShadowType.F_ATTRIBUTES)) { - break; - } - - // get entity query definition - Definition childDef = definition.findDefinition(qname, Definition.class); - if (childDef == null) { - throw new QueryException("Definition '" + definition + "' doesn't contain child definition '" - + qname + "'. Please check your path in query, or query entity/attribute mappings. " - + "Full path was '" + path + "'."); - } - - //todo change this if instanceof and use DefinitionHandler [lazyman] - if (childDef instanceof EntityDefinition) { - definition = (EntityDefinition) childDef; - } else if (childDef instanceof CollectionDefinition) { - CollectionDefinition collection = (CollectionDefinition) childDef; - if (childDef instanceof VirtualCollectionDefinition) { - VirtualCollectionDefinition virtual = (VirtualCollectionDefinition) childDef; - - criterions.add(updateMainCriterionQueryParam(virtual.getAdditionalParams(), propPath)); - } - - Definition def = collection.getDefinition(); - if (def instanceof EntityDefinition) { - definition = (EntityDefinition) def; - } - } else if (childDef instanceof PropertyDefinition || childDef instanceof ReferenceDefinition - || childDef instanceof AnyDefinition) { - break; - } else { - //todo throw something here [lazyman] - throw new QueryException("Not implemented yet."); - } - } - - return andCriterions(criterions); - } - - private Criterion andCriterions(List criterions) { - switch (criterions.size()) { - case 0: - return null; - case 1: - return criterions.get(0); - default: - return Restrictions.and(criterions.toArray(new Criterion[criterions.size()])); - } - } - - private Criterion updateMainCriterionQueryParam(VirtualQueryParam[] params, ItemPath propPath) - throws QueryException { - List criterions = new ArrayList(); - - String alias = getContext().getAlias(propPath); - for (VirtualQueryParam param : params) { - Criterion criterion = Restrictions.eq(alias + "." + param.name(), createQueryParamValue(param, propPath)); - criterions.add(criterion); - } - - return andCriterions(criterions); - } - - /** - * This method provides transformation from {@link String} value defined in - * {@link com.evolveum.midpoint.repo.sql.query.definition.VirtualQueryParam#value()} to real object. Currently only - * to simple types and enum values. - * - * @param param - * @param propPath - * @return real value - * @throws QueryException - */ - private Object createQueryParamValue(VirtualQueryParam param, ItemPath propPath) throws QueryException { - Class type = param.type(); - String value = param.value(); - - try { - if (type.isPrimitive()) { - return type.getMethod("valueOf", new Class[]{String.class}).invoke(null, new Object[]{value}); - } - - if (type.isEnum()) { - return Enum.valueOf(type, value); - } - } catch (Exception ex) { - throw new QueryException("Couldn't transform virtual query parameter '" - + param.name() + "' from String to '" + type + "', reason: " + ex.getMessage(), ex); - } - - throw new QueryException("Couldn't transform virtual query parameter '" - + param.name() + "' from String to '" + type + "', it's not yet implemented."); - } - - private void addPathAliasToContext(ItemPath path) { - ItemPath lastPropPath = path.allExceptLast(); - if (ItemPath.EMPTY_PATH.equivalent(lastPropPath)) { - lastPropPath = null; - } - - String alias = getContext().getAlias(lastPropPath); - getContext().addAlias(path, alias); - } - - protected void addNewCriteriaToContext(ItemPath path, Definition def, String realName) { - ItemPath lastPropPath = path.allExceptLast(); - if (ItemPath.EMPTY_PATH.equivalent(lastPropPath)) { - lastPropPath = null; - } - - // Virtual path is defined for example for virtual collections. {c:role/c:assignment} and {c:role/c:iducement} - // must use the same criteria, therefore {c:role/assigmnents} is also path under which is this criteria saved. - final ItemPath virtualPath = lastPropPath != null ? new ItemPath(lastPropPath, new QName("", realName)) : - new ItemPath(new QName("", realName)); - - Criteria existing = getContext().getCriteria(path); - if (existing != null) { - return; - } - - // If there is already criteria on virtual path, only add new path to aliases and criterias. - Criteria virtualCriteria = getContext().getCriteria(virtualPath); - if (virtualCriteria != null) { - getContext().addAlias(path, virtualCriteria.getAlias()); - getContext().addCriteria(path, virtualCriteria); - return; - } - - // get parent criteria - Criteria pCriteria = getContext().getCriteria(lastPropPath); - - // create new criteria and alias for this relationship - String alias = getContext().addAlias(path, def); - Criteria criteria = pCriteria.createCriteria(realName, alias, JoinType.LEFT_OUTER_JOIN); - getContext().addCriteria(path, criteria); - //also add virtual path to criteria map - getContext().addCriteria(virtualPath, criteria); - } - - protected Criterion createCriterion(String propertyName, Object value, ValueFilter filter) throws QueryException { - ItemRestrictionOperation operation; - if (filter instanceof EqualFilter) { - operation = ItemRestrictionOperation.EQ; - } else if (filter instanceof GreaterFilter) { - GreaterFilter gf = (GreaterFilter) filter; - operation = gf.isEquals() ? ItemRestrictionOperation.GE : ItemRestrictionOperation.GT; - } else if (filter instanceof LessFilter) { - LessFilter lf = (LessFilter) filter; - operation = lf.isEquals() ? ItemRestrictionOperation.LE : ItemRestrictionOperation.LT; - } else if (filter instanceof SubstringFilter) { - SubstringFilter substring = (SubstringFilter) filter; - if (substring.isAnchorEnd()) { - operation = ItemRestrictionOperation.ENDS_WITH; - } else if (substring.isAnchorStart()) { - operation = ItemRestrictionOperation.STARTS_WITH; - } else { - operation = ItemRestrictionOperation.SUBSTRING; - } - } else { - throw new QueryException("Can't translate filter '" + filter + "' to operation."); - } - - QueryContext context = getContext(); - QueryInterpreter interpreter = context.getInterpreter(); - Matcher matcher = interpreter.findMatcher(value); - - String matchingRule = null; - if (filter.getMatchingRule() != null){ - matchingRule = filter.getMatchingRule().getLocalPart(); - } - - return matcher.match(operation, propertyName, value, matchingRule); - } - - protected List createDefinitionPath(ItemPath path) throws QueryException { - List definitions = new ArrayList(); - if (path == null) { - return definitions; - } - - EntityDefinition lastDefinition = findProperEntityDefinition(path); - for (ItemPathSegment segment : path.getSegments()) { - if (lastDefinition == null) { - break; - } - - if (!(segment instanceof NameItemPathSegment)) { - continue; - } - - NameItemPathSegment named = (NameItemPathSegment) segment; - Definition def = lastDefinition.findDefinition(named.getName(), Definition.class); - definitions.add(def); - - if (def instanceof EntityDefinition) { - lastDefinition = (EntityDefinition) def; - } else if (def instanceof CollectionDefinition) { // todo this seems logical but is it correct? [mederly] - def = ((CollectionDefinition) def).getDefinition(); - if (def instanceof EntityDefinition) { - lastDefinition = ((EntityDefinition) def); - } else { - lastDefinition = null; - } - } - } - - return definitions; - } - - protected Object getValue(List values) { - if (values == null || values.isEmpty()) { - return null; - } - - PrismValue val = values.get(0); - if (val instanceof PrismPropertyValue) { - PrismPropertyValue propertyValue = (PrismPropertyValue) val; - return propertyValue.getValue(); - } - - return null; - } - - protected Object getValueFromFilter(ValueFilter filter, PropertyDefinition def) throws QueryException { - Object value; - if (filter != null) { - value = getValue((filter).getValues()); - } else { - throw new QueryException("Unknown filter '" + filter + "', can't get value from it."); - } - - //todo remove after some time [lazyman] - //attempt to fix value type for polystring (if it was string in filter we create polystring from it) - if (PolyString.class.equals(def.getJaxbType()) && (value instanceof String)) { - LOGGER.debug("Trying to query PolyString value but filter contains String '{}'.", new Object[]{filter}); - value = new PolyString((String) value, (String) value); - } - //attempt to fix value type for polystring (if it was polystringtype in filter we create polystring from it) - if (PolyString.class.equals(def.getJaxbType()) && (value instanceof PolyStringType)) { - LOGGER.debug("Trying to query PolyString value but filter contains PolyStringType '{}'.", new Object[]{filter}); - PolyStringType type = (PolyStringType) value; - value = new PolyString(type.getOrig(), type.getNorm()); - } - - if (String.class.equals(def.getJaxbType()) && (value instanceof QName)) { - //eg. shadow/objectClass - value = RUtil.qnameToString((QName) value); - } - - if (value != null && !def.getJaxbType().isAssignableFrom(value.getClass())) { - throw new QueryException("Value should by type of '" + def.getJaxbType() + "' but it's '" - + value.getClass() + "', filter '" + filter + "'."); - } - - if (def.isEnumerated()) { - value = getRepoEnumValue((Enum) value, def.getJpaType()); - } - - return value; - } - - private Enum getRepoEnumValue(Enum schemaValue, Class repoType) throws QueryException { - if (schemaValue == null) { - return null; - } - - if (SchemaEnum.class.isAssignableFrom(repoType)) { - return (Enum) RUtil.getRepoEnumValue(schemaValue, repoType); - } - - Object[] constants = repoType.getEnumConstants(); - for (Object constant : constants) { - Enum e = (Enum) constant; - if (e.name().equals(schemaValue.name())) { - return e; - } - } - - throw new QueryException("Unknown enum value '" + schemaValue + "', which is type of '" - + schemaValue.getClass() + "'."); - } - - protected String createPropertyOrReferenceNamePrefix(ItemPath path) throws QueryException { - StringBuilder sb = new StringBuilder(); - - EntityDefinition definition = findProperEntityDefinition(path); - - List segments = path.getSegments(); - for (ItemPathSegment segment : segments) { - QName qname = ItemPath.getName(segment); - if (ObjectType.F_METADATA.equals(qname)) { // todo not QNameUtil.match? [mederly] - continue; - } - if (QNameUtil.match(AssignmentType.F_CONSTRUCTION, qname)) { // ugly hack: construction/resourceRef -> resourceRef - continue; - } - - // get entity query definition - Definition childDef = definition.findDefinition(qname, Definition.class); - - //todo change this if instanceof and use DefinitionHandler [lazyman] - if (childDef instanceof EntityDefinition) { - EntityDefinition entityDef = (EntityDefinition) childDef; - if (entityDef.isEmbedded()) { - // we don't create new sub criteria, just add dot with jpaName - sb.append(entityDef.getJpaName()); - sb.append('.'); - } - definition = entityDef; - } else if (childDef instanceof CollectionDefinition) { - Definition def = ((CollectionDefinition) childDef).getDefinition(); - if (def instanceof EntityDefinition) { - definition = (EntityDefinition) def; - } - } else if (childDef instanceof PropertyDefinition || childDef instanceof ReferenceDefinition) { - break; - } else { - throw new QueryException("Not implemented yet. Create property name prefix for segment '" - + segment + "', path '" + path + "'."); - } - } - - return sb.toString(); - } - -} diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/ItemRestrictionOperation.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/ItemRestrictionOperation.java deleted file mode 100644 index 36d7bdaa5d2..00000000000 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/ItemRestrictionOperation.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2010-2013 Evolveum - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.evolveum.midpoint.repo.sql.query.restriction; - -/** - * @author lazyman - */ -public enum ItemRestrictionOperation { - - EQ, GT, GE, LT, LE, NULL, NOT_NULL, SUBSTRING, STARTS_WITH, ENDS_WITH; -} diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/LogicalRestriction.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/LogicalRestriction.java deleted file mode 100644 index e561993d808..00000000000 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/LogicalRestriction.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2010-2013 Evolveum - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.evolveum.midpoint.repo.sql.query.restriction; - -import com.evolveum.midpoint.prism.query.LogicalFilter; -import com.evolveum.midpoint.prism.query.ObjectFilter; -import com.evolveum.midpoint.repo.sql.query.QueryContext; -import com.evolveum.midpoint.repo.sql.query.QueryException; -import com.evolveum.midpoint.repo.sql.query.QueryInterpreter; -import org.hibernate.criterion.Criterion; - -/** - * @author lazyman - */ -public abstract class LogicalRestriction extends Restriction { - - @Override - public boolean canHandle(ObjectFilter filter) { - if (filter instanceof LogicalFilter) { - return true; - } - - return false; - } - - protected Criterion interpretChildFilter(ObjectFilter filter) throws QueryException { - QueryContext context = getContext(); - QueryInterpreter interpreter = context.getInterpreter(); - return interpreter.interpretFilter(filter, context, this); - } -} diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/NaryLogicalRestriction.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/NaryLogicalRestriction.java deleted file mode 100644 index d7b86bee990..00000000000 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/NaryLogicalRestriction.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2010-2014 Evolveum - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.evolveum.midpoint.repo.sql.query.restriction; - -import com.evolveum.midpoint.prism.query.NaryLogicalFilter; -import com.evolveum.midpoint.prism.query.ObjectFilter; -import com.evolveum.midpoint.repo.sql.query.QueryContext; -import com.evolveum.midpoint.repo.sql.query.QueryException; -import com.evolveum.midpoint.repo.sql.query.QueryInterpreter; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import org.hibernate.criterion.Criterion; -import org.hibernate.criterion.Junction; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author lazyman - */ -public abstract class NaryLogicalRestriction extends LogicalRestriction { - - private static final Trace LOGGER = TraceManager.getTrace(NaryLogicalRestriction.class); - private List restrictions; - - @Override - public boolean canHandle(ObjectFilter filter) { - if (filter instanceof NaryLogicalFilter) { - return true; - } - - return false; - } - - public List getRestrictions() { - if (restrictions == null) { - restrictions = new ArrayList<>(); - } - return restrictions; - } - - protected void validateFilter(NaryLogicalFilter filter) throws QueryException { - if (filter.getConditions() == null || filter.getConditions().isEmpty()) { - LOGGER.trace("NaryLogicalFilter filter must have at least two conditions in it. " + - "Removing logical filter and processing simple condition."); - throw new QueryException("NaryLogicalFilter filter '" + filter.debugDump() - + "' must have at least two conditions in it. Removing logical filter and processing simple condition."); - } - } - - protected Junction updateJunction(List conditions, Junction junction) - throws QueryException { - - QueryContext context = getContext(); - QueryInterpreter interpreter = context.getInterpreter(); - - for (ObjectFilter condition : conditions) { - Criterion criterion = interpreter.interpretFilter(condition, context, this); - junction.add(criterion); - } - - return junction; - } -} diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/NotRestriction.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/NotRestriction.java deleted file mode 100644 index 9881a54ace0..00000000000 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/NotRestriction.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2010-2013 Evolveum - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.evolveum.midpoint.repo.sql.query.restriction; - -import com.evolveum.midpoint.prism.query.NotFilter; -import com.evolveum.midpoint.prism.query.ObjectFilter; -import com.evolveum.midpoint.repo.sql.query.QueryException; -import org.hibernate.criterion.Criterion; -import org.hibernate.criterion.Restrictions; - -/** - * @author lazyman - */ -public class NotRestriction extends UnaryLogicalRestriction { - - @Override - public boolean canHandle(ObjectFilter filter) { - if (!super.canHandle(filter)) { - return false; - } - - return (filter instanceof NotFilter); - } - - - @Override - public Criterion interpret() throws QueryException { - validateFilter(filter); - Criterion criterion = interpretChildFilter(filter.getFilter()); - - return Restrictions.not(criterion); - } - - @Override - public NotRestriction newInstance() { - return new NotRestriction(); - } -} diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/OrRestriction.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/OrRestriction.java deleted file mode 100644 index 025a5d454d9..00000000000 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/OrRestriction.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2010-2013 Evolveum - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.evolveum.midpoint.repo.sql.query.restriction; - -import com.evolveum.midpoint.prism.query.ObjectFilter; -import com.evolveum.midpoint.prism.query.OrFilter; -import com.evolveum.midpoint.repo.sql.query.QueryException; -import org.hibernate.criterion.Criterion; -import org.hibernate.criterion.Disjunction; -import org.hibernate.criterion.Restrictions; - -/** - * @author lazyman - */ -public class OrRestriction extends NaryLogicalRestriction { - - @Override - public boolean canHandle(ObjectFilter filter) { - if (!super.canHandle(filter)) { - return false; - } - - return (filter instanceof OrFilter); - } - - @Override - public Criterion interpret() - throws QueryException { - - validateFilter(filter); - - Disjunction disjunction = Restrictions.disjunction(); - updateJunction(filter.getConditions(), disjunction); - - return disjunction; - } - - @Override - public OrRestriction newInstance() { - return new OrRestriction(); - } -} diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/OrgRestriction.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/OrgRestriction.java deleted file mode 100644 index 6ab8c5baebb..00000000000 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/OrgRestriction.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (c) 2010-2013 Evolveum - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.evolveum.midpoint.repo.sql.query.restriction; - -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.prism.query.ObjectFilter; -import com.evolveum.midpoint.prism.query.OrgFilter; -import com.evolveum.midpoint.repo.sql.data.common.RObjectReference; -import com.evolveum.midpoint.repo.sql.data.common.ROrgClosure; -import com.evolveum.midpoint.repo.sql.data.common.other.RReferenceOwner; -import com.evolveum.midpoint.repo.sql.query.QueryException; -import com.evolveum.midpoint.repo.sql.util.RUtil; -import org.hibernate.criterion.*; -import org.hibernate.type.StringType; -import org.hibernate.type.Type; - -import javax.xml.namespace.QName; - -/** - * @author lazyman - */ -public class OrgRestriction extends Restriction { - - private static final String QUERY_PATH = "descendants"; - private static final ItemPath QUERY_ITEM_PATH = new ItemPath(new QName(RUtil.NS_SQL_REPO, QUERY_PATH)); - - private static final String CLOSURE_ALIAS = "closure"; - private static final String DEPTH = CLOSURE_ALIAS + ".depth"; - - @Override - public boolean canHandle(ObjectFilter filter) { - if (filter instanceof OrgFilter) { - return true; - } - return false; - } - - @Override - public Criterion interpret() throws QueryException { - if (filter.isRoot()) { -// Criteria pCriteria = getInterpreter().getCriteria(null); - DetachedCriteria dc = DetachedCriteria.forClass(ROrgClosure.class); - String[] strings = new String[1]; - strings[0] = "descendant.oid"; - Type[] type = new Type[1]; - type[0] = StringType.INSTANCE; - dc.setProjection(Projections.sqlGroupProjection("descendant_oid", "descendant_oid having count(descendant_oid)=1", strings, type)); -// pCriteria.add(Subqueries.in("this.oid", dc)); - return Subqueries.propertyIn("oid", dc); -// Query rootOrgQuery = session.createQuery("select org from ROrg as org where org.oid in (select descendant.oid from ROrgClosure group by descendant.oid having count(descendant.oid)=1)"); - } - - if (filter.getOrgRef() == null) { - throw new QueryException("No organization reference defined in the search query."); - } - - if (filter.getOrgRef().getOid() == null) { - throw new QueryException("No oid specified in organization reference " + filter.getOrgRef().debugDump()); - } - - DetachedCriteria detached; - switch (filter.getScope()) { - case ONE_LEVEL: - detached = DetachedCriteria.forClass(RObjectReference.class, "p"); - detached.add(Restrictions.eq("referenceType", RReferenceOwner.OBJECT_PARENT_ORG)); - detached.setProjection(Projections.distinct(Projections.property("p.ownerOid"))); - detached.add(Restrictions.eq("p.targetOid", filter.getOrgRef().getOid())); - break; - case ANCESTORS: - throw new UnsupportedOperationException("ANCESTORS query is not supported in this query interpreter"); - case SUBTREE: - default: - detached = DetachedCriteria.forClass(RObjectReference.class, "p"); - detached.add(Restrictions.eq("referenceType", RReferenceOwner.OBJECT_PARENT_ORG)); - detached.setProjection(Projections.distinct(Projections.property("p.ownerOid"))); - detached.add(Property.forName("targetOid").in( - DetachedCriteria.forClass(ROrgClosure.class, "cl") - .setProjection(Projections.property("cl.descendantOid")) - .add(Restrictions.eq("cl.ancestorOid", filter.getOrgRef().getOid())))); - } - String mainAlias = getContext().getAlias(null); - return Subqueries.propertyIn(mainAlias + ".oid", detached); - } - - @Override - public OrgRestriction newInstance() { - return new OrgRestriction(); - } -} diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/PropertyRestriction.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/PropertyRestriction.java deleted file mode 100644 index ac512e95206..00000000000 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/PropertyRestriction.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (c) 2010-2013 Evolveum - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.evolveum.midpoint.repo.sql.query.restriction; - -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.prism.query.ObjectFilter; -import com.evolveum.midpoint.prism.query.ValueFilter; -import com.evolveum.midpoint.repo.sql.query.QueryContext; -import com.evolveum.midpoint.repo.sql.query.QueryException; -import com.evolveum.midpoint.repo.sql.query.definition.*; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import org.apache.commons.lang.StringUtils; -import org.hibernate.criterion.Criterion; - -/** - * @author lazyman - */ -public class PropertyRestriction extends ItemRestriction { - - private static final Trace LOGGER = TraceManager.getTrace(PropertyRestriction.class); - - @Override - public boolean canHandle(ObjectFilter filter) throws QueryException { - if (!super.canHandle(filter)) { - return false; - } - - ValueFilter valFilter = (ValueFilter) filter; - ItemPath fullPath = valFilter.getFullPath(); - - PropertyDefinition def = findProperDefinition(fullPath, PropertyDefinition.class); - return def != null; - } - - @Override - public Criterion interpretInternal(ValueFilter filter) - throws QueryException { - QueryContext context = getContext(); - - ItemPath fullPath = filter.getFullPath(); - PropertyDefinition def = findProperDefinition(fullPath, PropertyDefinition.class); - if (def.isLob()) { - throw new QueryException("Can't query based on clob property value '" + def + "'."); - } - - String propertyName = def.getJpaName(); - String alias = context.getAlias(filter.getParentPath()); - - StringBuilder sb = new StringBuilder(); - if (StringUtils.isNotEmpty(alias)) { - sb.append(alias); - sb.append('.'); - } - sb.append(createPropertyOrReferenceNamePrefix(fullPath)); - sb.append(propertyName); - - Object value = getValueFromFilter(filter, def); - - String propertyPath = sb.toString(); - Criterion criterion = createCriterion(propertyPath, value, filter); - return addIsNotNullIfNecessary(criterion, propertyPath); - } - - @Override - public PropertyRestriction newInstance() { - return new PropertyRestriction(); - } -} diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/ReferenceRestriction.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/ReferenceRestriction.java deleted file mode 100644 index 88ea00deea6..00000000000 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/ReferenceRestriction.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright (c) 2010-2015 Evolveum - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.evolveum.midpoint.repo.sql.query.restriction; - -import com.evolveum.midpoint.prism.PrismConstants; -import com.evolveum.midpoint.prism.PrismReferenceValue; -import com.evolveum.midpoint.prism.PrismValue; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.prism.path.NameItemPathSegment; -import com.evolveum.midpoint.prism.query.ObjectFilter; -import com.evolveum.midpoint.prism.query.RefFilter; -import com.evolveum.midpoint.repo.sql.data.common.ObjectReference; -import com.evolveum.midpoint.repo.sql.query.QueryException; -import com.evolveum.midpoint.repo.sql.query.QueryContext; -import com.evolveum.midpoint.repo.sql.query.definition.Definition; -import com.evolveum.midpoint.repo.sql.query.definition.ReferenceDefinition; -import com.evolveum.midpoint.repo.sql.util.ClassMapper; -import com.evolveum.midpoint.repo.sql.util.RUtil; -import com.evolveum.midpoint.util.QNameUtil; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ConstructionType; - -import org.apache.commons.lang.StringUtils; -import org.hibernate.criterion.Conjunction; -import org.hibernate.criterion.Criterion; -import org.hibernate.criterion.Restrictions; - -import javax.xml.namespace.QName; - -import java.util.List; - -/** - * @author lazyman - */ -public class ReferenceRestriction extends ItemRestriction { - - @Override - public boolean canHandle(ObjectFilter filter) { - if (filter instanceof RefFilter) { - return true; - } - return false; - } - - // modelled after PropertyRestriction.interpretInternal, with some differences - @Override - public Criterion interpretInternal(RefFilter filter) throws QueryException { - - // let's check the value (null is not supported yet) - List values = filter.getValues(); - if (values != null && values.size() > 1) { - throw new QueryException("Ref filter '" + filter + "' contain more than one reference value (which is not supported for now)."); - } - PrismReferenceValue refValue = null; - if (values != null && !values.isEmpty()) { - refValue = (PrismReferenceValue) values.get(0); - } - - QueryContext context = getContext(); - - ItemPath fullPath = filter.getFullPath(); - // actually, we cannot look for ReferenceDefinition here, because e.g. linkRef has a CollectionDefinition - Definition def = findProperDefinition(fullPath, Definition.class); - if (def == null) { - throw new QueryException("Definition for " + fullPath + " couldn't be found."); - } - - // ugly hacking, todo refactor! - StringBuilder sb = new StringBuilder(); - if (def instanceof ReferenceDefinition) { - ItemPath parentPath = filter.getParentPath(); - // hack: construction/resourceRef->resourceRef - if (QNameUtil.match(ConstructionType.F_RESOURCE_REF, filter.getElementName()) && - parentPath != null && parentPath.last() instanceof NameItemPathSegment && - QNameUtil.match(AssignmentType.F_CONSTRUCTION, ((NameItemPathSegment) parentPath.last()).getName())) { - parentPath = parentPath.allExceptLast(); - } - String alias = context.getAlias(parentPath); - if (StringUtils.isNotEmpty(alias)) { - sb.append(alias); - sb.append('.'); - } - sb.append(createPropertyOrReferenceNamePrefix(filter.getPath())); // i'm not sure about this [mederly] - String referenceName = def.getJpaName(); - sb.append(referenceName); - sb.append("."); - } else { - String alias = context.getAlias(filter.getPath()); - if (StringUtils.isNotEmpty(alias)) { - sb.append(alias); - sb.append('.'); - } - sb.append(createPropertyOrReferenceNamePrefix(filter.getPath())); // i'm not sure about this [mederly] - } - String prefix = sb.toString(); - - String refValueOid = null; - QName refValueRelation = null; - QName refValueTargetType = null; - if (refValue != null) { - refValueOid = refValue.getOid(); - refValueRelation = refValue.getRelation(); - refValueTargetType = refValue.getTargetType(); - } - Conjunction conjunction = Restrictions.conjunction(); - conjunction.add(handleEqOrNull(prefix + ObjectReference.F_TARGET_OID, refValueOid)); - - if (refValueOid != null) { - if (refValueRelation == null) { - // Return only references without relation - conjunction.add(Restrictions.eq(prefix + ObjectReference.F_RELATION, RUtil.QNAME_DELIMITER)); - } else if (refValueRelation.equals(PrismConstants.Q_ANY)) { - // Return all relations => no restriction - } else { - // return references with specific relation - conjunction.add(handleEqOrNull(prefix + ObjectReference.F_RELATION, RUtil.qnameToString(refValueRelation))); - } - - if (refValueTargetType != null) { - conjunction.add(handleEqOrNull(prefix + ObjectReference.F_TYPE, - ClassMapper.getHQLTypeForQName(refValueTargetType))); - } - } - - // TODO what about isNotNull if necessary ? - - return conjunction; - } - - @Override - public ReferenceRestriction newInstance() { - return new ReferenceRestriction(); - } - - private Criterion handleEqOrNull(String propertyName, Object value) { - if (value == null) { - return Restrictions.isNull(propertyName); - } - - return Restrictions.eq(propertyName, value); - } -} diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/Restriction.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/Restriction.java deleted file mode 100644 index 0bf8efd2a85..00000000000 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/Restriction.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2010-2013 Evolveum - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.evolveum.midpoint.repo.sql.query.restriction; - -import com.evolveum.midpoint.prism.query.NotFilter; -import com.evolveum.midpoint.prism.query.ObjectFilter; -import com.evolveum.midpoint.repo.sql.query.QueryContext; -import com.evolveum.midpoint.repo.sql.query.QueryException; -import org.hibernate.criterion.Conjunction; -import org.hibernate.criterion.Criterion; -import org.hibernate.criterion.NotNullExpression; -import org.hibernate.criterion.NullExpression; -import org.hibernate.criterion.Restrictions; - -/** - * @author lazyman - */ -public abstract class Restriction { - - protected QueryContext context; - protected Restriction parent; - protected T filter; - - public T getFilter() { - return filter; - } - - public void setFilter(T filter) { - this.filter = filter; - } - - public QueryContext getContext() { - return context; - } - - public void setContext(QueryContext context) { - this.context = context; - } - - public Restriction getParent() { - return parent; - } - - public void setParent(Restriction parent) { - this.parent = parent; - } - - public abstract Criterion interpret() throws QueryException; - - public abstract boolean canHandle(ObjectFilter filter) throws QueryException; - - // todo don't know if cloning is necessary... [lazyman] - // this can be replaced probably by simple java reflection call - public abstract Restriction newInstance(); - - protected boolean isNegated() { - return filter instanceof NotFilter || (parent != null && parent.isNegated()); - } - - /** - * Filter of type NOT(PROPERTY=VALUE) causes problems when there are entities with PROPERTY set to NULL. - * - * Such a filter has to be treated like - * - * NOT (PROPERTY=VALUE & PROPERTY IS NOT NULL) - * - * TODO implement for restrictions other than PropertyRestriction. - */ - protected Criterion addIsNotNullIfNecessary(Criterion criterion, String propertyPath) { - if (criterion instanceof NullExpression || criterion instanceof NotNullExpression) { - return criterion; - } - if (!isNegated()) { - return criterion; - } - Conjunction conjunction = Restrictions.conjunction(); - conjunction.add(criterion); - conjunction.add(Restrictions.isNotNull(propertyPath)); - return conjunction; - } -} diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/TypeRestriction.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/TypeRestriction.java deleted file mode 100644 index 66f7e1e3d96..00000000000 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/TypeRestriction.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (c) 2010-2014 Evolveum - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.evolveum.midpoint.repo.sql.query.restriction; - -import com.evolveum.midpoint.prism.query.ObjectFilter; -import com.evolveum.midpoint.prism.query.TypeFilter; -import com.evolveum.midpoint.repo.sql.data.common.RObject; -import com.evolveum.midpoint.repo.sql.data.common.other.RObjectType; -import com.evolveum.midpoint.repo.sql.query.QueryContext; -import com.evolveum.midpoint.repo.sql.query.QueryException; -import com.evolveum.midpoint.repo.sql.query.QueryInterpreter; -import com.evolveum.midpoint.repo.sql.util.ClassMapper; -import org.hibernate.criterion.Criterion; -import org.hibernate.criterion.Restrictions; - -import javax.xml.namespace.QName; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - -/** - * @author lazyman - */ -public class TypeRestriction extends Restriction { - - @Override - public Criterion interpret() throws QueryException { - String property = getContext().getAlias(null) + "." + RObject.F_OBJECT_TYPE_CLASS; - - Set values = getValues(filter.getType()); - - Criterion basedOnType; - if (values.size() > 1) { - basedOnType = Restrictions.in(property, values); - } else { - basedOnType = Restrictions.eq(property, values.iterator().next()); - } - - if (filter.getFilter() == null) { - return basedOnType; - } - - QueryContext context = getContext(); - QueryInterpreter interpreter = context.getInterpreter(); - Criterion basedOnFilter = interpreter.interpretFilter(filter.getFilter(), context, this); - - return Restrictions.and(basedOnType, basedOnFilter); - } - - private Set getValues(QName typeQName) { - Set set = new HashSet<>(); - - RObjectType type = ClassMapper.getHQLTypeForQName(typeQName); - set.add(type); - - switch (type) { - case OBJECT: - set.addAll(Arrays.asList(RObjectType.values())); - break; - case FOCUS: - set.add(RObjectType.USER); - case ABSTRACT_ROLE: - set.add(RObjectType.ROLE); - set.add(RObjectType.ORG); - break; - default: - } - - return set; - } - - @Override - public boolean canHandle(ObjectFilter filter) throws QueryException { - if (filter instanceof TypeFilter) { - return true; - } - return false; - } - - @Override - public Restriction newInstance() { - return new TypeRestriction(); - } -} diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/UnaryLogicalRestriction.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/UnaryLogicalRestriction.java deleted file mode 100644 index 06786e931c4..00000000000 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/restriction/UnaryLogicalRestriction.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2010-2014 Evolveum - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.evolveum.midpoint.repo.sql.query.restriction; - -import com.evolveum.midpoint.prism.query.ObjectFilter; -import com.evolveum.midpoint.prism.query.UnaryLogicalFilter; -import com.evolveum.midpoint.repo.sql.query.QueryException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; - -/** - * @author lazyman - */ -public abstract class UnaryLogicalRestriction extends LogicalRestriction { - - private static final Trace LOGGER = TraceManager.getTrace(UnaryLogicalRestriction.class); - - @Override - public boolean canHandle(ObjectFilter filter) { - if (filter instanceof UnaryLogicalFilter) { - return true; - } - - return false; - } - - protected void validateFilter(UnaryLogicalFilter filter) throws QueryException { - if (filter.getFilter() == null) { - LOGGER.trace("UnaryLogicalFilter filter must have child filter defined in it."); - throw new QueryException("UnaryLogicalFilter '" + filter.debugDump() - + "' must have child filter defined in it."); - } - } -} diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/QueryDefinitionRegistry2.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/QueryDefinitionRegistry2.java index 3ed8daaa2c6..34fbad53360 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/QueryDefinitionRegistry2.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/QueryDefinitionRegistry2.java @@ -17,7 +17,6 @@ package com.evolveum.midpoint.repo.sql.query2; import com.evolveum.midpoint.prism.Containerable; -import com.evolveum.midpoint.prism.Visitable; import com.evolveum.midpoint.prism.Visitor; import com.evolveum.midpoint.repo.sql.data.common.RObject; import com.evolveum.midpoint.repo.sql.data.common.container.RAccessCertificationCase; @@ -86,44 +85,38 @@ public class QueryDefinitionRegistry2 implements DebugDumpable { // link parents (maybe not needed at all, we'll see) and referenced entity definitions // sort definitions for (final JpaEntityDefinition definition : map.values()) { - Visitor resolutionVisitor = new Visitor() { - @Override - public void visit(Visitable visitable) { - if (visitable instanceof JpaEntityDefinition) { - JpaEntityDefinition entityDef = ((JpaEntityDefinition) visitable); - Class superclass = entityDef.getJpaClass().getSuperclass(); - if (superclass == null || !RObject.class.isAssignableFrom(superclass)) { - return; - } - JpaEntityDefinition superclassDefinition = definitionsByClass.get(superclass); - if (superclassDefinition == null) { - throw new IllegalStateException("No definition for superclass " + superclass + " of " + entityDef); - } - entityDef.setSuperclassDefinition(superclassDefinition); - } else if (visitable instanceof JpaEntityPointerDefinition) { - JpaEntityPointerDefinition entPtrDef = ((JpaEntityPointerDefinition) visitable); - if (!entPtrDef.isResolved()) { - Class referencedEntityJpaClass = entPtrDef.getJpaClass(); - JpaEntityDefinition realEntDef = definitionsByClass.get(referencedEntityJpaClass); - if (realEntDef == null) { - throw new IllegalStateException("Couldn't find entity definition for " + referencedEntityJpaClass); - } - entPtrDef.setResolvedEntityDefinition(realEntDef); - } - } - } - }; + Visitor resolutionVisitor = visitable -> { + if (visitable instanceof JpaEntityDefinition) { + JpaEntityDefinition entityDef = ((JpaEntityDefinition) visitable); + Class superclass = entityDef.getJpaClass().getSuperclass(); + if (superclass == null || !RObject.class.isAssignableFrom(superclass)) { + return; + } + JpaEntityDefinition superclassDefinition = definitionsByClass.get(superclass); + if (superclassDefinition == null) { + throw new IllegalStateException("No definition for superclass " + superclass + " of " + entityDef); + } + entityDef.setSuperclassDefinition(superclassDefinition); + } else if (visitable instanceof JpaEntityPointerDefinition) { + JpaEntityPointerDefinition entPtrDef = ((JpaEntityPointerDefinition) visitable); + if (!entPtrDef.isResolved()) { + Class referencedEntityJpaClass = entPtrDef.getJpaClass(); + JpaEntityDefinition realEntDef = definitionsByClass.get(referencedEntityJpaClass); + if (realEntDef == null) { + throw new IllegalStateException("Couldn't find entity definition for " + referencedEntityJpaClass); + } + entPtrDef.setResolvedEntityDefinition(realEntDef); + } + } + }; definition.accept(resolutionVisitor); - Visitor sortingVisitor = new Visitor() { - @Override - public void visit(Visitable visitable) { - if (visitable instanceof JpaEntityDefinition) { - JpaEntityDefinition entityDef = ((JpaEntityDefinition) visitable); - entityDef.sortDefinitions(); - } - } - }; + Visitor sortingVisitor = visitable -> { + if (visitable instanceof JpaEntityDefinition) { + JpaEntityDefinition entityDef = ((JpaEntityDefinition) visitable); + entityDef.sortDefinitions(); + } + }; definition.accept(sortingVisitor); } diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/QueryInterpreter2.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/QueryInterpreter2.java index d06838d4d0a..aca710000ed 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/QueryInterpreter2.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/QueryInterpreter2.java @@ -210,7 +210,7 @@ Restriction findAndCreateRestrictionInternal(T filter, InterpretationContext con ItemPath path = existsFilter.getFullPath(); ItemDefinition definition = existsFilter.getDefinition(); ProperDataSearchResult searchResult = resolver.findProperDataDefinition( - baseEntityDefinition, path, definition, JpaEntityDefinition.class); + baseEntityDefinition, path, definition, JpaEntityDefinition.class, context.getPrismContext()); if (searchResult == null) { throw new QueryException("Path for ExistsFilter (" + path + ") doesn't point to a hibernate entity within " + baseEntityDefinition); } @@ -220,7 +220,7 @@ Restriction findAndCreateRestrictionInternal(T filter, InterpretationContext con ItemPath path = refFilter.getFullPath(); ItemDefinition definition = refFilter.getDefinition(); ProperDataSearchResult searchResult = resolver.findProperDataDefinition( - baseEntityDefinition, path, definition, JpaReferenceDefinition.class); + baseEntityDefinition, path, definition, JpaReferenceDefinition.class, context.getPrismContext()); if (searchResult == null) { throw new QueryException("Path for RefFilter (" + path + ") doesn't point to a reference item within " + baseEntityDefinition); } @@ -231,7 +231,8 @@ Restriction findAndCreateRestrictionInternal(T filter, InterpretationContext con ItemPath path = valFilter.getFullPath(); ItemDefinition definition = valFilter.getDefinition(); - ProperDataSearchResult propDefRes = resolver.findProperDataDefinition(baseEntityDefinition, path, definition, JpaPropertyDefinition.class); + ProperDataSearchResult propDefRes = resolver.findProperDataDefinition(baseEntityDefinition, path, definition, JpaPropertyDefinition.class, + context.getPrismContext()); if (propDefRes == null) { throw new QueryException("Couldn't find a proper restriction for a ValueFilter: " + valFilter.debugDump()); } @@ -311,7 +312,7 @@ private void addOrdering(InterpretationContext context, ObjectOrdering ordering) // TODO if we'd like to have order-by extension properties, we'd need to provide itemDefinition for them ProperDataSearchResult result = context.getItemPathResolver().findProperDataDefinition( - context.getRootEntityDefinition(), orderByPath, null, JpaDataNodeDefinition.class); + context.getRootEntityDefinition(), orderByPath, null, JpaDataNodeDefinition.class, context.getPrismContext()); if (result == null) { LOGGER.error("Unknown path '" + orderByPath + "', couldn't find definition for it, " + "list will not be ordered by it."); diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaAnyContainerDefinition.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaAnyContainerDefinition.java index 12ff9f679d6..012473e740c 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaAnyContainerDefinition.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaAnyContainerDefinition.java @@ -17,6 +17,7 @@ package com.evolveum.midpoint.repo.sql.query2.definition; import com.evolveum.midpoint.prism.ItemDefinition; +import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.Visitor; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.repo.sql.data.common.any.RAnyConverter; @@ -40,7 +41,7 @@ protected String getDebugDumpClassName() { } @Override - public DataSearchResult nextLinkDefinition(ItemPath path, ItemDefinition itemDefinition) throws QueryException { + public DataSearchResult nextLinkDefinition(ItemPath path, ItemDefinition itemDefinition, PrismContext prismContext) throws QueryException { if (ItemPath.asSingleName(path) == null) { throw new QueryException("Couldn't resolve paths other than those in the form of single name in extension/attributes container: " + path); } @@ -50,7 +51,7 @@ public DataSearchResult nextLinkDefinition(ItemPath path, ItemDefinition itemDef String jpaName; // longs, strings, ... try { - jpaName = RAnyConverter.getAnySetType(itemDefinition); + jpaName = RAnyConverter.getAnySetType(itemDefinition, prismContext); } catch (SchemaException e) { throw new QueryException(e.getMessage(), e); } diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaDataNodeDefinition.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaDataNodeDefinition.java index 523e8ae4cf0..f7acb123e09 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaDataNodeDefinition.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaDataNodeDefinition.java @@ -17,6 +17,7 @@ package com.evolveum.midpoint.repo.sql.query2.definition; import com.evolveum.midpoint.prism.ItemDefinition; +import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.Visitable; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.repo.sql.query.QueryException; @@ -89,13 +90,15 @@ public Class getJaxbClass() { * * @param path A path to be resolved. Always non-null and non-empty. Should produce at least one transition. * @param itemDefinition Item definition for the item being sought. Needed only for "any" items. - * @return + * @param prismContext + * @return * - Normally it returns the search result containing next item definition (entity, collection, ...) in the chain * and the unresolved remainder of the path. The transition may be empty ("self") e.g. for metadata or construction. * - If the search was not successful, returns null. * */ - public abstract DataSearchResult nextLinkDefinition(ItemPath path, ItemDefinition itemDefinition) throws QueryException; + public abstract DataSearchResult nextLinkDefinition(ItemPath path, ItemDefinition itemDefinition, + PrismContext prismContext) throws QueryException; public String toString() { return getShortInfo(); diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaEntityDefinition.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaEntityDefinition.java index c1e6556804e..8a6efe5159e 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaEntityDefinition.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaEntityDefinition.java @@ -17,6 +17,7 @@ package com.evolveum.midpoint.repo.sql.query2.definition; import com.evolveum.midpoint.prism.ItemDefinition; +import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.Visitable; import com.evolveum.midpoint.prism.Visitor; import com.evolveum.midpoint.prism.path.IdItemPathSegment; @@ -96,19 +97,22 @@ public interface LinkDefinitionHandler { * @param path ItemPath to resolve. Non-empty! * @param itemDefinition Definition of the final path segment, if it's "any" property. * @param type Type of definition to be found + * @param prismContext * @return * * If successful, returns correct definition + empty path. * If unsuccessful, return null. */ - public DataSearchResult findDataNodeDefinition(ItemPath path, ItemDefinition itemDefinition, Class type) throws QueryException { - return findDataNodeDefinition(path, itemDefinition, type, null); + public DataSearchResult findDataNodeDefinition(ItemPath path, + ItemDefinition itemDefinition, Class type, PrismContext prismContext) throws QueryException { + return findDataNodeDefinition(path, itemDefinition, type, null, prismContext); } - public DataSearchResult findDataNodeDefinition(ItemPath path, ItemDefinition itemDefinition, Class type, LinkDefinitionHandler handler) throws QueryException { + public DataSearchResult findDataNodeDefinition(ItemPath path, + ItemDefinition itemDefinition, Class type, LinkDefinitionHandler handler, PrismContext prismContext) throws QueryException { JpaDataNodeDefinition currentDefinition = this; for (;;) { - DataSearchResult result = currentDefinition.nextLinkDefinition(path, itemDefinition); + DataSearchResult result = currentDefinition.nextLinkDefinition(path, itemDefinition, prismContext); if (result == null) { // oops return null; } @@ -140,7 +144,7 @@ public JpaEntityDefinition getSuperclassDefinition() { } @Override - public DataSearchResult nextLinkDefinition(ItemPath path, ItemDefinition itemDefinition) throws QueryException { + public DataSearchResult nextLinkDefinition(ItemPath path, ItemDefinition itemDefinition, PrismContext prismContext) throws QueryException { if (ItemPath.isNullOrEmpty(path)) { // doesn't fulfill precondition return null; diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaEntityPointerDefinition.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaEntityPointerDefinition.java index 36b65745583..dbba9a29eb3 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaEntityPointerDefinition.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaEntityPointerDefinition.java @@ -17,6 +17,7 @@ package com.evolveum.midpoint.repo.sql.query2.definition; import com.evolveum.midpoint.prism.ItemDefinition; +import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.Visitor; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.repo.sql.query.QueryException; @@ -53,8 +54,9 @@ public void setResolvedEntityDefinition(JpaEntityDefinition resolvedEntityDefini } @Override - public DataSearchResult nextLinkDefinition(ItemPath path, ItemDefinition itemDefinition) throws QueryException { - return resolvedEntityDefinition.nextLinkDefinition(path, itemDefinition); + public DataSearchResult nextLinkDefinition(ItemPath path, ItemDefinition itemDefinition, + PrismContext prismContext) throws QueryException { + return resolvedEntityDefinition.nextLinkDefinition(path, itemDefinition, prismContext); } @Override diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaPropertyDefinition.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaPropertyDefinition.java index d8d34a29fd4..fd4c129a8c3 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaPropertyDefinition.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaPropertyDefinition.java @@ -17,6 +17,7 @@ package com.evolveum.midpoint.repo.sql.query2.definition; import com.evolveum.midpoint.prism.ItemDefinition; +import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.Visitor; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.repo.sql.data.common.embedded.RPolyString; @@ -74,7 +75,7 @@ protected String getDebugDumpClassName() { } @Override - public DataSearchResult nextLinkDefinition(ItemPath path, ItemDefinition itemDefinition) { + public DataSearchResult nextLinkDefinition(ItemPath path, ItemDefinition itemDefinition, PrismContext prismContext) { // nowhere to come from here return null; } diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaReferenceDefinition.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaReferenceDefinition.java index 1674de70f70..373391d1cc1 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaReferenceDefinition.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaReferenceDefinition.java @@ -17,6 +17,7 @@ package com.evolveum.midpoint.repo.sql.query2.definition; import com.evolveum.midpoint.prism.ItemDefinition; +import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.Visitor; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.path.ObjectReferencePathSegment; @@ -42,7 +43,7 @@ protected String getDebugDumpClassName() { } @Override - public DataSearchResult nextLinkDefinition(ItemPath path, ItemDefinition itemDefinition) { + public DataSearchResult nextLinkDefinition(ItemPath path, ItemDefinition itemDefinition, PrismContext prismContext) { if (path.first() instanceof ObjectReferencePathSegment) { // returning artificially created transition definition, used to allow dereferencing target object in a generic way return new DataSearchResult( diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/resolution/ItemPathResolutionState.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/resolution/ItemPathResolutionState.java index b461658ada6..cd67ee30d8d 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/resolution/ItemPathResolutionState.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/resolution/ItemPathResolutionState.java @@ -17,6 +17,7 @@ package com.evolveum.midpoint.repo.sql.query2.resolution; import com.evolveum.midpoint.prism.ItemDefinition; +import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.path.ParentPathSegment; import com.evolveum.midpoint.repo.sql.query.QueryException; @@ -87,9 +88,10 @@ public boolean isFinal() { * * @param itemDefinition Target item definition (used/required only for "any" properties) * @param singletonOnly Collections are forbidden + * @param prismContext * @return destination state - always not null */ - public ItemPathResolutionState nextState(ItemDefinition itemDefinition, boolean singletonOnly) throws QueryException { + public ItemPathResolutionState nextState(ItemDefinition itemDefinition, boolean singletonOnly, PrismContext prismContext) throws QueryException { // special case - ".." when having previous state means returning to that state // used e.g. for Exists (some-path, some-conditions AND Equals(../xxx, yyy)) @@ -103,7 +105,8 @@ public ItemPathResolutionState nextState(ItemDefinition itemDefinition, boolean return next; } - DataSearchResult result = hqlDataInstance.getJpaDefinition().nextLinkDefinition(remainingItemPath, itemDefinition); + DataSearchResult result = hqlDataInstance.getJpaDefinition().nextLinkDefinition(remainingItemPath, itemDefinition, + prismContext); LOGGER.trace("nextLinkDefinition on '{}' returned '{}'", remainingItemPath, result != null ? result.getLinkDefinition() : "(null)"); if (result == null) { // sorry we failed (however, this should be caught before -> so IllegalStateException) throw new IllegalStateException("Couldn't find " + remainingItemPath + " in " + hqlDataInstance.getJpaDefinition()); diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/resolution/ItemPathResolver.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/resolution/ItemPathResolver.java index 73466b1ea83..41ee828152e 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/resolution/ItemPathResolver.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/resolution/ItemPathResolver.java @@ -17,6 +17,7 @@ package com.evolveum.midpoint.repo.sql.query2.resolution; import com.evolveum.midpoint.prism.ItemDefinition; +import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.repo.sql.data.common.RObject; import com.evolveum.midpoint.repo.sql.data.common.any.RAnyValue; @@ -81,7 +82,7 @@ public HqlDataInstance resolveItemPath(ItemPath relativePath, ItemDefinition ite while (!currentState.isFinal()) { LOGGER.trace("Current resolution state:\n{}", currentState.debugDumpNoParent()); - currentState = currentState.nextState(itemDefinition, singletonOnly); + currentState = currentState.nextState(itemDefinition, singletonOnly, context.getPrismContext()); } LOGGER.trace("resolveItemPath({}) ending in resolution state of:\n{}", relativePath, currentState.debugDump()); @@ -202,17 +203,18 @@ private Object createQueryParamValue(VirtualQueryParam param) throws QueryExcept * @param path Path to be found (non-empty!) * @param itemDefinition Definition of target property, required/used only for "any" properties * @param clazz Kind of definition to be looked for + * @param prismContext * @return Entity type definition + item definition, or null if nothing was found */ public ProperDataSearchResult findProperDataDefinition(JpaEntityDefinition baseEntityDefinition, - ItemPath path, ItemDefinition itemDefinition, - Class clazz) throws QueryException { + ItemPath path, ItemDefinition itemDefinition, + Class clazz, PrismContext prismContext) throws QueryException { QueryDefinitionRegistry2 registry = QueryDefinitionRegistry2.getInstance(); ProperDataSearchResult candidateResult = null; for (JpaEntityDefinition entityDefinition : findPossibleBaseEntities(baseEntityDefinition, registry)) { - DataSearchResult result = entityDefinition.findDataNodeDefinition(path, itemDefinition, clazz); + DataSearchResult result = entityDefinition.findDataNodeDefinition(path, itemDefinition, clazz, prismContext); if (result != null) { if (candidateResult == null) { candidateResult = new ProperDataSearchResult<>(entityDefinition, result);