repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
infinispan-main/spring/spring6/spring6-embedded/src/main/java/org/infinispan/spring/embedded/support/InfinispanNamedEmbeddedCacheFactoryBean.java
package org.infinispan.spring.embedded.support; import java.lang.invoke.MethodHandles; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.springframework.beans.factory.BeanNameAware; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.util.StringUtils; /** * <p> * A {@link FactoryBean <code>FactoryBean</code>} for creating a * native {@link #setCacheName(String) named} Infinispan {@link Cache * <code>org.infinispan.Cache</code>}, delegating to a * {@link #setInfinispanEmbeddedCacheManager(EmbeddedCacheManager) <code>configurable</code>} * {@link EmbeddedCacheManager * <code>org.infinispan.manager.EmbeddedCacheManager</code>}. If no cache name is explicitly set, * this <code>FactoryBean</code>'s {@link #setBeanName(String) <code>beanName</code>} will be used * instead. * </p> * <p> * Beyond merely creating named <code>Cache</code> instances, this <code>FactoryBean</code> offers * great flexibility in configuring those <code>Caches</code>. It has setters for all non-global * configuration settings, i.e. all settings that are specific to a single <code>Cache</code>. The * configuration settings thus defined override those settings obtained from the * <code>EmbeddedCacheManager</code>. * </p> * <p> * There are different configuration {@link #setConfigurationTemplateMode(String) * <code>modes</code>} that control with what <code>Configuration</code> to start before further * customizing it as described above: * <ul> * <li> * <code>NONE</code>: Configuration starts with a new <code>Configuration</code> instance. * Note that this mode may only be used if no named configuration having the same name as the <code>Cache</code> * to be created already exists. It is therefore illegal to use this mode to create a <code>Cache</code> named, say, * &quot;cacheName&quot; if the configuration file used to configure the * <code>EmbeddedCacheManager</code> contains a configuration section named * &quot;cacheName&quot;.</li> * <li> * <code>DEFAULT</code>: Configuration starts with the <code>EmbeddedCacheManager</code>'s * <em>default</em> <code>Configuration</code> instance, i.e. the configuration settings defined * in its configuration file's default section. Note that this mode may only be used if no named configuration * having the same name as the <code>Cache</code> to be created already exists. It is therefore illegal to use * this mode to create a <code>Cache</code> named, say, &quot;cacheName&quot; if the configuration file used * to configure the <code>EmbeddedCacheManager</code> contains a configuration section named * &quot;cacheName&quot;.</li> * <li> * <code>CUSTOM</code>: This is where a user will provide a custom-built <code>ConfigurationBuilder</code> * object which will be used to configure a <code>Cache</code> instance. If a {@link #setCacheName(String)} has * already been called, then that name will be used. * </li> * <li> * <code>NAMED</code>: Configuration starts with the <code>EmbeddedCacheManager</code>'s * <code>Configuration</code> instance having the same name as the <code>Cache</code> to be * created. For a <code>Cache</code> named, say, &quot;cacheName&quot; this is the configuration * section named &quot;cacheName&quot; as defined in the <code>EmbeddedCacheManager</code>'s * configuration file. Note that this mode is only useful if such a named configuration section does indeed exist. * Otherwise, it is equivalent to using * <code>DEFAULT</code>.</li> * </ul> * </p> * <p> * In addition to creating a named <code>Cache</code> this <code>FactoryBean</code> does also * control that <code>Cache</code>' {@link org.infinispan.commons.api.Lifecycle lifecycle} by shutting * it down when the enclosing Spring application context is closed. It is therefore advisable to * <em>always</em> use this <code>FactoryBean</code> when creating a named <code>Cache</code>. * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * @author Marius Bogoevici * */ public class InfinispanNamedEmbeddedCacheFactoryBean<K, V> implements FactoryBean<Cache<K, V>>, BeanNameAware, InitializingBean, DisposableBean { /** * <p> * Defines how to configure a new named cache produced by this <code>FactoryBean</code>: * <ul> * <li> * <code>NONE</code>: Configuration starts with a new <code>Configuration</code> instance. * Note that this mode may only be used if no named configuration having the same name as the <code>Cache</code> * to be created already exists. It is therefore illegal to use this mode to create a <code>Cache</code> named, say, * &quot;cacheName&quot; if the configuration file used to configure the * <code>EmbeddedCacheManager</code> contains a configuration section named * &quot;cacheName&quot;.</li> * <li> * <code>DEFAULT</code>: Configuration starts with the <code>EmbeddedCacheManager</code>'s * <em>default</em> <code>Configuration</code> instance, i.e. the configuration settings defined * in its configuration file's default section. Note that this mode may only be used if no named configuration * having the same name as the <code>Cache</code> to be created already exists. It is therefore illegal to use * this mode to create a <code>Cache</code> named, say, &quot;cacheName&quot; if the configuration file used * to configure the <code>EmbeddedCacheManager</code> contains a configuration section named * &quot;cacheName&quot;.</li> * <li> * <code>CUSTOM</code>: This is where a user will provide a custom-built <code>ConfigurationBuilder</code> * object which will be used to configure a <code>Cache</code> instance. If a {@link #setCacheName(String)} has * already been called, then that name will be used. * </li> * <li> * <code>NAMED</code>: Configuration starts with the <code>EmbeddedCacheManager</code>'s * <code>Configuration</code> instance having the same name as the <code>Cache</code> to be * created. For a <code>Cache</code> named, say, &quot;cacheName&quot; this is the configuration * section named &quot;cacheName&quot; as defined in the <code>EmbeddedCacheManager</code>'s * configuration file. Note that this mode is only useful if such a named configuration section does indeed exist. * Otherwise, it is equivalent to using * <code>DEFAULT</code>.</li> * </ul> * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * */ enum ConfigurationTemplateMode { NONE, DEFAULT, CUSTOM, NAMED } private static final Log logger = LogFactory.getLog(MethodHandles.lookup().lookupClass()); private EmbeddedCacheManager infinispanEmbeddedCacheManager; private ConfigurationTemplateMode configurationTemplateMode = ConfigurationTemplateMode.NAMED; private String cacheName; private String beanName; private Cache<K, V> infinispanCache; private ConfigurationBuilder builder = null; // ------------------------------------------------------------------------ // org.springframework.beans.factory.InitializingBean // ------------------------------------------------------------------------ /** * @see InitializingBean#afterPropertiesSet() */ @Override public void afterPropertiesSet() throws Exception { if (this.infinispanEmbeddedCacheManager == null) { throw new IllegalStateException("No Infinispan EmbeddedCacheManager has been set"); } this.logger.info("Initializing named Infinispan embedded cache ..."); final String effectiveCacheName = obtainEffectiveCacheName(); this.infinispanCache = configureAndCreateNamedCache(effectiveCacheName); this.logger.info("New Infinispan embedded cache [" + this.infinispanCache + "] initialized"); } private Cache<K, V> configureAndCreateNamedCache(final String cacheName) { switch (this.configurationTemplateMode) { case NONE: this.logger.debug("ConfigurationTemplateMode is NONE: using a fresh Configuration"); if (this.infinispanEmbeddedCacheManager.getCacheNames().contains(cacheName)) { throw new IllegalStateException("Cannot use ConfigurationTemplateMode NONE: a cache named [" + cacheName + "] has already been defined."); } builder = new ConfigurationBuilder(); this.infinispanEmbeddedCacheManager.defineConfiguration(cacheName, builder.build()); break; case NAMED: this.logger.debug("ConfigurationTemplateMode is NAMED: using a named Configuration [" + cacheName + "]"); break; case DEFAULT: this.logger.debug("ConfigurationTemplateMode is DEFAULT."); if (this.infinispanEmbeddedCacheManager.getCacheNames().contains(cacheName)) { throw new IllegalStateException("Cannot use ConfigurationTemplateMode DEFAULT: a cache named [" + cacheName + "] has already been defined."); } break; case CUSTOM: this.logger.debug("ConfigurationTemplateMode is CUSTOM. Using the provided ConfigurationBuilder."); if (this.builder == null) { throw new IllegalStateException("There has not been a ConfigurationBuilder provided. There has to be one " + "provided for ConfigurationTemplateMode CUSTOM."); } this.infinispanEmbeddedCacheManager.defineConfiguration(cacheName, builder.build()); break; default: throw new IllegalStateException("Unknown ConfigurationTemplateMode: " + this.configurationTemplateMode); } return this.infinispanEmbeddedCacheManager.getCache(cacheName); } private String obtainEffectiveCacheName() { if (StringUtils.hasText(this.cacheName)) { if (this.logger.isDebugEnabled()) { this.logger.debug("Using custom cache name [" + this.cacheName + "]"); } return this.cacheName; } else { if (this.logger.isDebugEnabled()) { this.logger.debug("Using bean name [" + this.beanName + "] as cache name"); } return this.beanName; } } // ------------------------------------------------------------------------ // org.springframework.beans.factory.FactoryBean // ------------------------------------------------------------------------ /** * @see FactoryBean#getObject() */ @Override public Cache<K, V> getObject() throws Exception { return this.infinispanCache; } /** * @see FactoryBean#getObjectType() */ @Override public Class<? extends Cache> getObjectType() { return this.infinispanCache != null ? this.infinispanCache.getClass() : Cache.class; } /** * Always returns <code>true</code>. * * @return Always <code>true</code> * * @see FactoryBean#isSingleton() */ @Override public boolean isSingleton() { return true; } // ------------------------------------------------------------------------ // org.springframework.beans.factory.BeanNameAware // ------------------------------------------------------------------------ /** * @see BeanNameAware#setBeanName(String) */ @Override public void setBeanName(final String name) { this.beanName = name; } // ------------------------------------------------------------------------ // org.springframework.beans.factory.DisposableBean // ------------------------------------------------------------------------ /** * Shuts down the <code>org.infinispan.Cache</code> created by this <code>FactoryBean</code>. * * @see DisposableBean#destroy() * @see Cache#stop() */ @Override public void destroy() throws Exception { // Probably being paranoid here ... if (this.infinispanCache != null) { this.infinispanCache.stop(); } } // ------------------------------------------------------------------------ // Properties // ------------------------------------------------------------------------ /** * <p> * Sets the {@link Cache#getName() name} of the {@link Cache * <code>org.infinispan.Cache</code>} to be created. If no explicit <code>cacheName</code> is * set, this <code>FactoryBean</code> will use its {@link #setBeanName(String) * <code>beanName</code>} as the <code>cacheName</code>. * </p> * * @param cacheName * The {@link Cache#getName() name} of the {@link Cache * <code>org.infinispan.Cache</code>} to be created */ public void setCacheName(final String cacheName) { this.cacheName = cacheName; } /** * <p> * Sets the {@link EmbeddedCacheManager * <code>org.infinispan.manager.EmbeddedCacheManager</code>} to be used for creating our * {@link Cache <code>Cache</code>} instance. Note that this is a * <strong>mandatory</strong> property. * </p> * * @param infinispanEmbeddedCacheManager * The {@link EmbeddedCacheManager * <code>org.infinispan.manager.EmbeddedCacheManager</code>} to be used for creating * our {@link Cache <code>Cache</code>} instance */ public void setInfinispanEmbeddedCacheManager( final EmbeddedCacheManager infinispanEmbeddedCacheManager) { this.infinispanEmbeddedCacheManager = infinispanEmbeddedCacheManager; } /** * @param configurationTemplateMode * @throws IllegalArgumentException */ public void setConfigurationTemplateMode(final String configurationTemplateMode) throws IllegalArgumentException { this.configurationTemplateMode = ConfigurationTemplateMode.valueOf(configurationTemplateMode); } /** * API to introduce a customised {@link ConfigurationBuilder} that will override the default configurations * which are already available on this class. This can <strong>only</strong> be used if {@link * #setConfigurationTemplateMode(String)} has been set to <code>CUSTOM</code>. * * @param builder */ public void addCustomConfiguration(final ConfigurationBuilder builder) { this.builder = builder; } }
14,696
43.268072
156
java
null
infinispan-main/spring/spring6/spring6-embedded/src/main/java/org/infinispan/spring/embedded/support/InfinispanEmbeddedCacheManagerFactoryBean.java
package org.infinispan.spring.embedded.support; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.spring.embedded.AbstractEmbeddedCacheManagerFactory; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; /** * <p> * A {@link FactoryBean <code>FactoryBean</code>} for creating an * {@link EmbeddedCacheManager <code>Infinispan EmbeddedCacheManager</code>} * instance. The location of the Infinispan configuration file used to provide the default * {@link org.infinispan.configuration.cache.Configuration configuration} for the * <code>EmbeddedCacheManager</code> instance created by this <code>FactoryBean</code> is * {@link #setConfigurationFileLocation(org.springframework.core.io.Resource) configurable}. * </p> * <p> * If no configuration file location is set the <code>EmbeddedCacheManager</code> instance created * by this <code>FactoryBean</code> will use Infinispan's default settings. See Infinispan's <a * href="http://www.jboss.org/infinispan/docs">documentation</a> for what those default settings * are. * </p> * <p> * A user may further customize the <code>EmbeddedCacheManager</code>'s configuration using explicit * setters on this <code>FactoryBean</code>. The properties thus defined will be applied either to * the configuration loaded from Infinispan's configuration file in case one has been specified, or * to a configuration initialized with Infinispan's default settings. Either way, the net effect is * that explicitly set configuration properties take precedence over both those loaded from a * configuration file as well as INFNISPAN's default settings. * </p> * <p> * In addition to creating an <code>EmbeddedCacheManager</code> this <code>FactoryBean</code> does * also control that <code>EmbeddedCacheManagers</code>'s {@link org.infinispan.commons.api.Lifecycle * lifecycle} by shutting it down when the enclosing Spring application context is closed. It is * therefore advisable to <em>always</em> use this <code>FactoryBean</code> when creating an * <code>EmbeddedCacheManager</code>. * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * * @see #setConfigurationFileLocation(org.springframework.core.io.Resource) * @see #destroy() * @see EmbeddedCacheManager * @see org.infinispan.configuration.cache.Configuration * */ public class InfinispanEmbeddedCacheManagerFactoryBean extends AbstractEmbeddedCacheManagerFactory implements FactoryBean<EmbeddedCacheManager>, InitializingBean, DisposableBean { private static final Log logger = LogFactory.getLog(InfinispanEmbeddedCacheManagerFactoryBean.class); private EmbeddedCacheManager cacheManager; // ------------------------------------------------------------------------ // org.springframework.beans.factory.InitializingBean // ------------------------------------------------------------------------ /** * @see InitializingBean#afterPropertiesSet() */ @Override public void afterPropertiesSet() throws Exception { logger.info("Initializing Infinispan EmbeddedCacheManager instance ..."); this.cacheManager = createBackingEmbeddedCacheManager(); logger.info("Successfully initialized Infinispan EmbeddedCacheManager instance [" + this.cacheManager + "]"); } // ------------------------------------------------------------------------ // org.springframework.beans.factory.FactoryBean // ------------------------------------------------------------------------ /** * @see FactoryBean#getObject() */ @Override public EmbeddedCacheManager getObject() throws Exception { return this.cacheManager; } /** * @see FactoryBean#getObjectType() */ @Override public Class<? extends EmbeddedCacheManager> getObjectType() { return this.cacheManager != null ? this.cacheManager.getClass() : EmbeddedCacheManager.class; } /** * Always returns <code>true</code>. * * @return Always <code>true</code> * * @see FactoryBean#isSingleton() */ @Override public boolean isSingleton() { return true; } // ------------------------------------------------------------------------ // org.springframework.beans.factory.DisposableBean // ------------------------------------------------------------------------ /** * Shuts down the <code>EmbeddedCacheManager</code> instance created by this * <code>FactoryBean</code>. * * @see DisposableBean#destroy() * @see EmbeddedCacheManager#stop() */ @Override public void destroy() throws Exception { // Probably being paranoid here ... if (this.cacheManager != null) { this.cacheManager.stop(); } } }
4,964
39.040323
104
java
null
infinispan-main/spring/spring6/spring6-embedded/src/main/java/org/infinispan/spring/embedded/provider/SpringEmbeddedCacheManager.java
package org.infinispan.spring.embedded.provider; import java.util.Collection; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.infinispan.Cache; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.spring.common.provider.SpringCache; import org.springframework.cache.CacheManager; import org.springframework.util.Assert; /** * <p> * A {@link CacheManager <code>CacheManager</code>} implementation that is * backed by an {@link EmbeddedCacheManager * <code>Infinispan EmbeddedCacheManager</code>} instance. * </p> * <p> * Note that this <code>CacheManager</code> <strong>does</strong> support adding new * {@link org.infinispan.Cache <code>Caches</code>} at runtime, i.e. <code>Caches</code> added * programmatically to the backing <code>EmbeddedCacheManager</code> after this * <code>CacheManager</code> has been constructed will be seen by this <code>CacheManager</code>. * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * @author Marius Bogoevici * */ public class SpringEmbeddedCacheManager implements CacheManager { private final EmbeddedCacheManager nativeCacheManager; private final ConcurrentMap<String, SpringCache> springCaches = new ConcurrentHashMap<>(); /** * @param nativeCacheManager Underlying cache manager */ public SpringEmbeddedCacheManager(final EmbeddedCacheManager nativeCacheManager) { Assert.notNull(nativeCacheManager, "A non-null instance of EmbeddedCacheManager needs to be supplied"); this.nativeCacheManager = nativeCacheManager; } @Override public SpringCache getCache(final String name) { return springCaches.computeIfAbsent(name, n -> { final Cache<Object, Object> nativeCache = this.nativeCacheManager.getCache(n); return new SpringCache(nativeCache); }); } @Override public Collection<String> getCacheNames() { return this.nativeCacheManager.getCacheNames(); } /** * Return the {@link EmbeddedCacheManager * <code>org.infinispan.manager.EmbeddedCacheManager</code>} that backs this * <code>CacheManager</code>. * * @return The {@link EmbeddedCacheManager * <code>org.infinispan.manager.EmbeddedCacheManager</code>} that backs this * <code>CacheManager</code> */ public EmbeddedCacheManager getNativeCacheManager() { return this.nativeCacheManager; } /** * Stop the {@link EmbeddedCacheManager <code>EmbeddedCacheManager</code>} this * <code>CacheManager</code> delegates to. */ public void stop() { this.nativeCacheManager.stop(); this.springCaches.clear(); } }
2,736
33.2125
97
java
null
infinispan-main/spring/spring6/spring6-embedded/src/main/java/org/infinispan/spring/embedded/provider/ContainerEmbeddedCacheManagerFactoryBean.java
package org.infinispan.spring.embedded.provider; import org.infinispan.manager.EmbeddedCacheManager; import org.springframework.beans.factory.FactoryBean; import org.springframework.cache.CacheManager; import org.springframework.util.Assert; /** * {@link FactoryBean} for creating a {@link CacheManager} for a pre-defined {@link org.infinispan.manager.CacheContainer}. * <p/> * Useful when the cache container is defined outside the application (e.g. provided by the application server) * * @author Marius Bogoevici */ public class ContainerEmbeddedCacheManagerFactoryBean implements FactoryBean<CacheManager> { private EmbeddedCacheManager cacheContainer; public ContainerEmbeddedCacheManagerFactoryBean(EmbeddedCacheManager cacheContainer) { Assert.notNull(cacheContainer, "CacheContainer cannot be null"); this.cacheContainer = cacheContainer; } @Override public CacheManager getObject() throws Exception { return new SpringEmbeddedCacheManager((EmbeddedCacheManager) this.cacheContainer); } @Override public Class<?> getObjectType() { return CacheManager.class; } @Override public boolean isSingleton() { return true; } }
1,206
29.175
123
java
null
infinispan-main/spring/spring6/spring6-embedded/src/main/java/org/infinispan/spring/embedded/provider/SpringEmbeddedCacheManagerFactoryBean.java
package org.infinispan.spring.embedded.provider; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.spring.embedded.AbstractEmbeddedCacheManagerFactory; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; /** * <p> * A {@link FactoryBean <code>FactoryBean</code>} for creating an * {@link SpringEmbeddedCacheManager * <code>SpringEmbeddedCacheManager</code>} instance. The location of the Infinispan configuration * file used to provide the default {@link org.infinispan.configuration.cache.Configuration configuration} for * the <code>EmbeddedCacheManager</code> instance created by this <code>FactoryBean</code> is * {@link #setConfigurationFileLocation(org.springframework.core.io.Resource) configurable}. * </p> * <p> * If no configuration file location is set the <code>SpringEmbeddedCacheManager</code> instance * created by this <code>FactoryBean</code> will use Infinispan's default settings. See Infinispan's * <a href="http://www.jboss.org/infinispan/docs">documentation</a> for what those default settings * are. * </p> * <p> * A user may further customize the <code>SpringEmbeddedCacheManager</code>'s configuration using * explicit setters on this <code>FactoryBean</code>. The properties thus defined will be applied * either to the configuration loaded from Infinispan's configuration file in case one has been * specified, or to a configuration initialized with Infinispan's default settings. Either way, the * net effect is that explicitly set configuration properties take precedence over both those loaded * from a configuration file as well as INFINISPAN's default settings. * </p> * <p> * In addition to creating an <code>SpringEmbeddedCacheManager</code> this <code>FactoryBean</code> * does also control that <code>SpringEmbeddedCacheManager</code>'s * {@link org.infinispan.commons.api.Lifecycle lifecycle} by shutting it down when the enclosing * Spring application context is closed. It is therefore advisable to <em>always</em> use this * <code>FactoryBean</code> when creating an <code>SpringEmbeddedCacheManager</code>. * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * * @see #setConfigurationFileLocation(org.springframework.core.io.Resource) * @see #destroy() * @see SpringEmbeddedCacheManager * @see EmbeddedCacheManager * @see org.infinispan.configuration.cache.Configuration * */ public class SpringEmbeddedCacheManagerFactoryBean extends AbstractEmbeddedCacheManagerFactory implements FactoryBean<SpringEmbeddedCacheManager>, InitializingBean, DisposableBean { private static final Log logger = LogFactory.getLog(SpringEmbeddedCacheManagerFactoryBean.class); private SpringEmbeddedCacheManager cacheManager; // ------------------------------------------------------------------------ // org.springframework.beans.factory.InitializingBean // ------------------------------------------------------------------------ /** * @see InitializingBean#afterPropertiesSet() */ @Override public void afterPropertiesSet() throws Exception { logger.info("Initializing SpringEmbeddedCacheManager instance ..."); final EmbeddedCacheManager nativeEmbeddedCacheManager = createBackingEmbeddedCacheManager(); this.cacheManager = new SpringEmbeddedCacheManager(nativeEmbeddedCacheManager); logger.info("Successfully initialized SpringEmbeddedCacheManager instance [" + this.cacheManager + "]"); } // ------------------------------------------------------------------------ // org.springframework.beans.factory.FactoryBean // ------------------------------------------------------------------------ /** * @see FactoryBean#getObject() */ @Override public SpringEmbeddedCacheManager getObject() throws Exception { return this.cacheManager; } /** * @see FactoryBean#getObjectType() */ @Override public Class<? extends SpringEmbeddedCacheManager> getObjectType() { return this.cacheManager != null ? this.cacheManager.getClass() : SpringEmbeddedCacheManager.class; } /** * Always returns <code>true</code>. * * @return Always <code>true</code> * * @see FactoryBean#isSingleton() */ @Override public boolean isSingleton() { return true; } // ------------------------------------------------------------------------ // org.springframework.beans.factory.DisposableBean // ------------------------------------------------------------------------ /** * Shuts down the <code>SpringEmbeddedCacheManager</code> instance created by this * <code>FactoryBean</code>. * * @see DisposableBean#destroy() * @see SpringEmbeddedCacheManager#stop() */ @Override public void destroy() throws Exception { // Probably being paranoid here ... if (this.cacheManager != null) { this.cacheManager.stop(); } } }
5,189
39.866142
110
java
null
infinispan-main/object-filter/src/test/java/org/infinispan/objectfilter/test/RowMatcherTest.java
package org.infinispan.objectfilter.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import org.infinispan.objectfilter.FilterSubscription; import org.infinispan.objectfilter.Matcher; import org.infinispan.objectfilter.ObjectFilter; import org.infinispan.objectfilter.ParsingException; import org.infinispan.objectfilter.impl.RowMatcher; import org.infinispan.objectfilter.impl.syntax.parser.RowPropertyHelper; import org.infinispan.objectfilter.test.model.Person; import org.infinispan.query.dsl.Query; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; /** * @author anistor@redhat.com * @since 8.0 */ public class RowMatcherTest { @Rule public ExpectedException expectedException = ExpectedException.none(); private final FilterQueryFactory queryFactory = new FilterQueryFactory(); private Object[] createPerson1() { // id, name, surname, age, gender return new Object[]{1, "John", "Batman", 40, Person.Gender.MALE, null}; } private Object[] createPerson2() { // id, name, surname, age, gender return new Object[]{2, "Cat", "Woman", 27, Person.Gender.FEMALE, null}; } private RowMatcher createMatcher() { RowPropertyHelper.ColumnMetadata[] columns = new RowPropertyHelper.ColumnMetadata[]{ new RowPropertyHelper.ColumnMetadata(0, "id", Integer.class), new RowPropertyHelper.ColumnMetadata(1, "name", String.class), new RowPropertyHelper.ColumnMetadata(2, "surname", String.class), new RowPropertyHelper.ColumnMetadata(3, "age", Integer.class), new RowPropertyHelper.ColumnMetadata(4, "gender", Person.Gender.class), new RowPropertyHelper.ColumnMetadata(5, "license", String.class), }; return new RowMatcher(columns); } private boolean match(String queryString, Object obj) { Matcher matcher = createMatcher(); int[] matchCount = {0}; matcher.registerFilter(queryString, (userContext, eventType, instance, projection, sortProjection) -> matchCount[0]++); matcher.match(null, null, obj); return matchCount[0] == 1; } private boolean match(Query<?> query, Object obj) { Matcher matcher = createMatcher(); int[] matchCount = {0}; matcher.registerFilter(query, (userContext, eventType, instance, projection, sortProjection) -> matchCount[0]++); matcher.match(null, null, obj); return matchCount[0] == 1; } @Test public void shouldRaiseExceptionDueToUnknownAlias() { expectedException.expect(ParsingException.class); expectedException.expectMessage("ISPN028502"); String queryString = "from Row p where x.name = 'John'"; assertTrue(match(queryString, createPerson1())); } @Test public void testIntervalOverlap1() { String queryString = "from Row where age <= 50 and age <= 40"; assertTrue(match(queryString, createPerson1())); } @Test public void testIntervalOverlap2() { String queryString = "from Row where age <= 50 and age = 40"; assertTrue(match(queryString, createPerson1())); } @Test public void testIntervalOverlap3() { String queryString = "from Row where age > 50 and age = 40"; assertFalse(match(queryString, createPerson1())); } @Test public void testNoOpFilter3() { String queryString = "from Row"; // this should match ALL assertTrue(match(queryString, createPerson1())); } @Test public void testSimpleAttribute1() { String queryString = "from Row where name = 'John'"; assertTrue(match(queryString, createPerson1())); } @Test public void testSimpleAttribute2() { String queryString = "from Row p where p.name = 'John'"; assertTrue(match(queryString, createPerson1())); } @Test public void testEnum() { String queryString = "from Row p where p.gender = 'MALE'"; assertTrue(match(queryString, createPerson1())); } @Test public void testMissingProperty1() { expectedException.expect(ParsingException.class); expectedException.expectMessage("ISPN028501"); String queryString = "from Row where missingProp is null"; assertFalse(match(queryString, createPerson1())); } @Test public void testMissingProperty2() { expectedException.expect(ParsingException.class); expectedException.expectMessage("ISPN028501"); String queryString = "from Row p where p.missingProp is null"; assertFalse(match(queryString, createPerson1())); } @Test public void testIsNull1() { String queryString = "from Row p where p.surname is null"; assertFalse(match(queryString, createPerson1())); } @Test public void testIsNull2() { String queryString = "from Row p where p.license is null"; assertTrue(match(queryString, createPerson1())); } @Test public void testIsNotNull() { String queryString = "from Row p where p.surname is not null"; assertTrue(match(queryString, createPerson1())); } @Test public void testSimpleAttribute3() { String queryString = "from Row p where p.name = 'George'"; assertFalse(match(queryString, createPerson1())); } @Test public void testSimpleAttribute4() { String queryString = "from Row p where not(p.name != 'George')"; assertFalse(match(queryString, createPerson1())); } @Test public void testSimpleAttribute5() { String queryString = "from Row p where p.name != 'George'"; assertTrue(match(queryString, createPerson1())); } @Test public void testSimpleAttributeInterval1() { String queryString = "from Row p where p.name > 'G'"; assertTrue(match(queryString, createPerson1())); } @Test public void testSimpleAttributeInterval2() { String queryString = "from Row p where p.name < 'G'"; assertFalse(match(queryString, createPerson1())); } @Test public void testFilterInterference() { Matcher matcher = createMatcher(); int[] matchCount = {0, 0}; String queryString1 = "from Row p where p.name = 'John'"; matcher.registerFilter(queryString1, (userContext, eventType, instance, projection, sortProjection) -> matchCount[0]++); String queryString2 = "from Row p where p.age = 40"; matcher.registerFilter(queryString2, (userContext, eventType, instance, projection, sortProjection) -> matchCount[1]++); matcher.match(null, null, createPerson1()); // assert that only one of the filters matched and the callback of the other was not invoked assertEquals(1, matchCount[0]); assertEquals(1, matchCount[1]); } @Test public void testOrderBy() { Matcher matcher = createMatcher(); List<Comparable<?>[]> sortProjections = new ArrayList<>(); String queryString1 = "from Row p where p.age > 18 order by p.name, p.surname"; FilterSubscription filterSubscription = matcher.registerFilter(queryString1, (userContext, eventType, instance, projection, sortProjection) -> sortProjections.add(sortProjection)); matcher.match(null, null, createPerson1()); matcher.match(null, null, createPerson2()); assertEquals(2, sortProjections.size()); sortProjections.sort(filterSubscription.getComparator()); assertEquals("Cat", sortProjections.get(0)[0]); assertEquals("Woman", sortProjections.get(0)[1]); assertEquals("John", sortProjections.get(1)[0]); assertEquals("Batman", sortProjections.get(1)[1]); } @Test public void testDSL() { Query<Person> q = queryFactory.create("FROM " + Person.class.getName() + " WHERE name = 'John'"); assertTrue(match(q, createPerson1())); } @Test public void testObjectFilterWithExistingSubscription() { String queryString = "from Row p where p.name = 'John'"; Matcher matcher = createMatcher(); Object person = createPerson1(); int[] matchCount = {0}; FilterSubscription filterSubscription = matcher.registerFilter(queryString, (userContext, eventType, instance, projection, sortProjection) -> matchCount[0]++); ObjectFilter objectFilter = matcher.getObjectFilter(filterSubscription); matcher.match(null, null, person); assertEquals(1, matchCount[0]); ObjectFilter.FilterResult result = objectFilter.filter(person); assertSame(person, result.getInstance()); assertEquals(1, matchCount[0]); // check that the object filter did not also mistakenly trigger a match in the parent matcher } @Test public void testObjectFilterWithIckle() { String queryString = "from Row p where p.name = 'John'"; Matcher matcher = createMatcher(); Object person = createPerson1(); ObjectFilter objectFilter = matcher.getObjectFilter(queryString); ObjectFilter.FilterResult result = objectFilter.filter(person); assertNotNull(result); assertSame(person, result.getInstance()); } @Test public void testObjectFilterWithDSLSamePredicate1() { Matcher matcher = createMatcher(); Object person = createPerson1(); // use the same '< 1000' predicate on two different attributes to demonstrate they do not interfere (see ISPN-4654) Query<Person> q = queryFactory.create("FROM " + Person.class.getName() + " WHERE id < 1000 AND age < 1000"); ObjectFilter objectFilter = matcher.getObjectFilter(q); ObjectFilter.FilterResult result = objectFilter.filter(person); assertNotNull(result); assertSame(person, result.getInstance()); } @Test public void testObjectFilterWithDSLSamePredicate2() { Matcher matcher = createMatcher(); Object person = createPerson1(); // use the same "like 'Jo%'" predicate (in positive and negative form) on the same attribute to demonstrate they do not interfere (see ISPN-4654) Query<Person> q = queryFactory.create("FROM " + Person.class.getName() + " p WHERE p.name LIKE 'Jo%' AND (p.name NOT LIKE 'Jo%' OR p.id < 1000)"); ObjectFilter objectFilter = matcher.getObjectFilter(q); ObjectFilter.FilterResult result = objectFilter.filter(person); assertNotNull(result); assertSame(person, result.getInstance()); } @Test public void testMatcherAndObjectFilterWithDSL() { Matcher matcher = createMatcher(); Object person = createPerson1(); Query<Person> q = queryFactory.create("FROM " + Person.class.getName() + " WHERE name = 'John'"); boolean[] b = {false}; FilterSubscription filterSubscription = matcher.registerFilter(q, (userContext, eventType, instance, projection, sortProjection) -> b[0] = true); ObjectFilter objectFilter = matcher.getObjectFilter(filterSubscription); ObjectFilter.FilterResult result = objectFilter.filter(person); assertNotNull(result); assertSame(person, result.getInstance()); matcher.match(null, null, person); assertTrue(b[0]); } @Test public void testObjectFilterWithDSL() { Matcher matcher = createMatcher(); Object person = createPerson1(); Query<Person> q = queryFactory.create("FROM " + Person.class.getName() + " WHERE name = 'John'"); ObjectFilter objectFilter = matcher.getObjectFilter(q); ObjectFilter.FilterResult result = objectFilter.filter(person); assertNotNull(result); assertSame(person, result.getInstance()); } @Test public void testUnregistration() { String queryString = "from Row p where p.name = 'John'"; Matcher matcher = createMatcher(); Object person = createPerson1(); int[] matchCount = new int[1]; FilterSubscription filterSubscription = matcher.registerFilter(queryString, (userContext, eventType, instance, projection, sortProjection) -> matchCount[0]++); matcher.match(null, null, person); assertEquals(1, matchCount[0]); matcher.unregisterFilter(filterSubscription); matcher.match(null, null, person); // check that unregistration really took effect assertEquals(1, matchCount[0]); } @Test public void testAnd1() { String queryString = "from Row p where p.age < 44 and p.name = 'John'"; assertTrue(match(queryString, createPerson1())); } @Test public void testAnd2() { String queryString = "from Row where age > 10 and age < 30"; assertFalse(match(queryString, createPerson1())); } @Test public void testAnd3() { String queryString = "from Row where age > 30 and name >= 'John'"; assertTrue(match(queryString, createPerson1())); } @Test public void testAnd4() { String queryString = "from Row where surname = 'X' and age > 10"; assertFalse(match(queryString, createPerson1())); } @Test public void testOr1() { String queryString = "from Row where age < 30 or age > 10"; assertTrue(match(queryString, createPerson1())); } @Test public void testOr2() { String queryString = "from Row where surname = 'X' or name like 'Joh%'"; assertTrue(match(queryString, createPerson1())); } @Test public void testOr3() { String queryString = "from Row p where (p.gender = 'MALE' or p.name = 'John' or p.gender = 'FEMALE') and p.surname = 'Batman'"; assertTrue(match(queryString, createPerson1())); } @Test public void testLike1() { String queryString = "from Row p where p.name like 'Jo%'"; assertTrue(match(queryString, createPerson1())); } @Test public void testLike2() { String queryString = "from Row p where p.name like 'Ja%'"; assertFalse(match(queryString, createPerson1())); } @Test public void testLike3() { String queryString = "from Row p where p.name like 'Jo%'"; assertTrue(match(queryString, createPerson1())); } @Test public void testLike4() { String queryString = "from Row p where p.name like 'Joh_'"; assertTrue(match(queryString, createPerson1())); } @Test public void testLike5() { String queryString = "from Row p where p.name like 'Joh_nna'"; assertFalse(match(queryString, createPerson1())); } @Test public void testLike6() { String queryString = "from Row p where p.name like '_oh_'"; assertTrue(match(queryString, createPerson1())); } @Test public void testLike7() { String queryString = "from Row p where p.name like '_oh_noes'"; assertFalse(match(queryString, createPerson1())); } @Test public void testLike8() { String queryString = "from Row p where p.name like '%hn%'"; assertTrue(match(queryString, createPerson1())); } @Test public void testLike9() { String queryString = "from Row p where p.name like '%hn'"; assertTrue(match(queryString, createPerson1())); } @Test public void testLike10() { String queryString = "from Row p where p.name like 'Jo%hn'"; assertTrue(match(queryString, createPerson1())); } @Test public void testIn() { String queryString = "from Row where age between 22 and 42"; assertTrue(match(queryString, createPerson1())); } @Test public void testNotIn() { String queryString = "from Row where age not between 22 and 42"; assertFalse(match(queryString, createPerson1())); } @Test public void testProjections() { String queryString = "select p.name, p.age from Row p where p.name = 'John'"; Matcher matcher = createMatcher(); Object person = createPerson1(); List<Object[]> result = new ArrayList<>(); FilterSubscription filterSubscription = matcher.registerFilter(queryString, (userContext, eventType, instance, projection, sortProjection) -> result.add(projection)); assertNotNull(filterSubscription.getProjection()); assertEquals(2, filterSubscription.getProjection().length); assertEquals("name", filterSubscription.getProjection()[0]); assertEquals("age", filterSubscription.getProjection()[1]); matcher.match(null, null, person); matcher.unregisterFilter(filterSubscription); assertEquals(1, result.size()); assertEquals(2, result.get(0).length); assertEquals("John", result.get(0)[0]); assertEquals(40, result.get(0)[1]); } @Test public void testDuplicateProjections() { String queryString = "select p.name, p.name, p.age from Row p where p.name = 'John'"; Matcher matcher = createMatcher(); Object person = createPerson1(); List<Object[]> result = new ArrayList<>(); FilterSubscription filterSubscription = matcher.registerFilter(queryString, (userContext, eventType, instance, projection, sortProjection) -> result.add(projection)); assertNotNull(filterSubscription.getProjection()); assertEquals(3, filterSubscription.getProjection().length); assertEquals("name", filterSubscription.getProjection()[0]); assertEquals("name", filterSubscription.getProjection()[1]); assertEquals("age", filterSubscription.getProjection()[2]); matcher.match(null, null, person); matcher.unregisterFilter(filterSubscription); assertEquals(1, result.size()); assertEquals(3, result.get(0).length); assertEquals("John", result.get(0)[0]); assertEquals("John", result.get(0)[1]); assertEquals(40, result.get(0)[2]); } @Test public void testDisallowGroupingAndAggregations() { expectedException.expect(ParsingException.class); expectedException.expectMessage("Filters cannot use grouping or aggregations"); String queryString = "SELECT sum(p.age) " + "from Row p " + "WHERE p.age <= 99 " + "GROUP BY p.name " + "HAVING count(p.age) > 3"; Matcher matcher = createMatcher(); matcher.registerFilter(queryString, (userContext, eventType, instance, projection, sortProjection) -> { }); } }
18,215
32.423853
186
java
null
infinispan-main/object-filter/src/test/java/org/infinispan/objectfilter/test/AbstractMatcherTest.java
package org.infinispan.objectfilter.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.infinispan.objectfilter.FilterSubscription; import org.infinispan.objectfilter.Matcher; import org.infinispan.objectfilter.ObjectFilter; import org.infinispan.objectfilter.ParsingException; import org.infinispan.objectfilter.test.model.Address; import org.infinispan.objectfilter.test.model.Person; import org.infinispan.objectfilter.test.model.PhoneNumber; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; /** * @author anistor@redhat.com * @since 7.0 */ public abstract class AbstractMatcherTest { @Rule public ExpectedException expectedException = ExpectedException.none(); protected abstract QueryFactory createQueryFactory(); protected Object createPerson1() throws Exception { Person person = new Person(); person.setId(1); person.setName("John"); person.setSurname("Batman"); person.setAge(40); person.setGender(Person.Gender.MALE); Address address = new Address(); address.setStreet("Old Street"); address.setPostCode("SW12345"); person.setAddress(address); PhoneNumber phoneNumber1 = new PhoneNumber(); phoneNumber1.setNumber("0040888888"); PhoneNumber phoneNumber2 = new PhoneNumber(); phoneNumber2.setNumber("004012345"); person.setPhoneNumbers(Arrays.asList(phoneNumber1, phoneNumber2)); return person; } protected Object createPerson2() throws Exception { Person person = new Person(); person.setId(2); person.setName("Cat"); person.setSurname("Woman"); person.setAge(27); person.setGender(Person.Gender.FEMALE); return person; } protected abstract Matcher createMatcher(); protected boolean match(String queryString, Object obj) { Matcher matcher = createMatcher(); int[] matchCount = {0}; matcher.registerFilter(queryString, (userContext, eventType, instance, projection, sortProjection) -> matchCount[0]++); matcher.match(null, null, obj); return matchCount[0] == 1; } protected boolean match(Query<?> query, Object obj) { Matcher matcher = createMatcher(); int[] matchCount = {0}; matcher.registerFilter(query, (userContext, eventType, instance, projection, sortProjection) -> matchCount[0]++); matcher.match(null, null, obj); return matchCount[0] == 1; } @Test public void shouldRaiseExceptionDueToUnknownAlias() throws Exception { expectedException.expect(ParsingException.class); expectedException.expectMessage("ISPN028502"); String queryString = "from org.infinispan.objectfilter.test.model.Person person where x.name = 'John'"; match(queryString, createPerson1()); } @Test public void shouldRaiseNoSuchPropertyException() throws Exception { expectedException.expect(ParsingException.class); expectedException.expectMessage("ISPN028501"); String queryString = "from org.infinispan.objectfilter.test.model.Person person where person.name.blah = 'John'"; match(queryString, createPerson1()); } @Test public void shouldRaisePredicatesOnEntityAliasNotAllowedException1() throws Exception { expectedException.expect(ParsingException.class); expectedException.expectMessage("ISPN028519"); String queryString = "from org.infinispan.objectfilter.test.model.Person name where name = 'John'"; match(queryString, createPerson1()); } @Test public void shouldRaisePredicatesOnEntityAliasNotAllowedException2() throws Exception { expectedException.expect(ParsingException.class); expectedException.expectMessage("ISPN028519"); String queryString = "from org.infinispan.objectfilter.test.model.Person name where name is not null"; match(queryString, createPerson1()); } @Test public void testIntervalOverlap1() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person where age <= 50 and age <= 40"; assertTrue(match(queryString, createPerson1())); } @Test public void testIntervalOverlap2() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person where age <= 50 and age = 40"; assertTrue(match(queryString, createPerson1())); } @Test public void testIntervalOverlap3() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person where age > 50 and age = 40"; assertFalse(match(queryString, createPerson1())); } @Test //todo this triggers a bug in hql parser (https://hibernate.atlassian.net/browse/HQLPARSER-44): NPE in SingleEntityQueryRendererDelegate.addComparisonPredicate due to null property path. public void testNoOpFilter1() throws Exception { expectedException.expect(ParsingException.class); expectedException.expectMessage("ISPN028524"); String queryString = "from org.infinispan.objectfilter.test.model.Person where 4 = 4"; match(queryString, createPerson1()); } @Test @Ignore //todo this triggers a bug in hql parser (https://hibernate.atlassian.net/browse/HQLPARSER-44): second name token is mistakenly recognized as a string constant instead of property reference. this should trigger a parsing error. public void testNoOpFilter2() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person where name = name"; // this should match ALL assertTrue(match(queryString, createPerson1())); } @Test public void testNoOpFilter3() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person"; // this should match ALL assertTrue(match(queryString, createPerson1())); } @Test public void testNoOpFilter4() throws Exception { String queryString = "select name from org.infinispan.objectfilter.test.model.Person"; // this should match ALL assertTrue(match(queryString, createPerson1())); } @Test public void testSimpleAttribute1() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person where name = 'John'"; assertTrue(match(queryString, createPerson1())); } @Test public void testSimpleAttribute2() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person p where p.name = 'John'"; assertTrue(match(queryString, createPerson1())); } @Test public void testEnum() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person p where p.gender = 'MALE'"; assertTrue(match(queryString, createPerson1())); } @Test public void testMissingProperty1() throws Exception { expectedException.expect(ParsingException.class); expectedException.expectMessage("ISPN028501"); String queryString = "from org.infinispan.objectfilter.test.model.Person where missingProp is null"; match(queryString, createPerson1()); } @Test public void testMissingProperty2() throws Exception { expectedException.expect(ParsingException.class); expectedException.expectMessage("ISPN028501"); String queryString = "from org.infinispan.objectfilter.test.model.Person p where p.missingProp is null"; match(queryString, createPerson1()); } @Test public void testIsNull1() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person p where p.surname is null"; assertFalse(match(queryString, createPerson1())); } @Test public void testIsNull2() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person p where p.license is null"; assertTrue(match(queryString, createPerson1())); } @Test public void testIsNotNull1() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person p where p.surname is not null"; assertTrue(match(queryString, createPerson1())); } @Test public void testIsNotNull2() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person p where not(p.surname is null)"; assertTrue(match(queryString, createPerson1())); } @Test public void testCollectionIsNull1() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person where phoneNumbers is null"; assertTrue(match(queryString, createPerson2())); } @Test public void testCollectionIsNull2() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person where phoneNumbers is null"; assertFalse(match(queryString, createPerson1())); } @Test public void testCollectionIsNotNull1() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person where phoneNumbers is not null"; assertTrue(match(queryString, createPerson1())); } @Test public void testCollectionIsNotNull2() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person where phoneNumbers is not null"; assertFalse(match(queryString, createPerson2())); } @Test public void testSimpleAttribute3() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person p where p.name = 'George'"; assertFalse(match(queryString, createPerson1())); } @Test public void testSimpleAttribute4() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person p where not(p.name != 'George')"; assertFalse(match(queryString, createPerson1())); } @Test public void testSimpleAttribute5() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person p where p.name != 'George'"; assertTrue(match(queryString, createPerson1())); } @Test public void testNestedAttribute1() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person p where p.address.postCode = 'SW12345'"; assertTrue(match(queryString, createPerson1())); } @Test public void testNestedAttribute2() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person p where p.address.postCode = 'NW045'"; assertFalse(match(queryString, createPerson1())); } @Test public void testNestedRepeatedAttribute1() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person p where p.phoneNumbers.number = '004012345'"; assertTrue(match(queryString, createPerson1())); } @Test public void testNestedRepeatedAttribute2() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person p where p.phoneNumbers.number = '11111'"; assertFalse(match(queryString, createPerson1())); } @Test public void testNestedRepeatedAttribute3() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person p where p.phoneNumbers.number != '11111'"; assertTrue(match(queryString, createPerson1())); } @Test public void testSimpleAttributeInterval1() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person p where p.name > 'G'"; assertTrue(match(queryString, createPerson1())); } @Test public void testSimpleAttributeInterval2() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person p where p.name < 'G'"; assertFalse(match(queryString, createPerson1())); } @Test public void testFilterInterference() throws Exception { Matcher matcher = createMatcher(); int[] matchCount = {0, 0}; String queryString1 = "from org.infinispan.objectfilter.test.model.Person p where p.name = 'John'"; matcher.registerFilter(queryString1, (userContext, eventType, instance, projection, sortProjection) -> matchCount[0]++); String queryString2 = "from org.infinispan.objectfilter.test.model.Person p where p.phoneNumbers.number = '004012345'"; matcher.registerFilter(queryString2, (userContext, eventType, instance, projection, sortProjection) -> matchCount[1]++); matcher.match(null, null, createPerson1()); // assert that only one of the filters matched and the callback of the other was not invoked assertEquals(1, matchCount[0]); assertEquals(1, matchCount[1]); } @Test public void testOrderBy() throws Exception { Matcher matcher = createMatcher(); List<Comparable<?>[]> sortProjections = new ArrayList<>(); String queryString1 = "from org.infinispan.objectfilter.test.model.Person p where p.age > 18 order by p.name, p.surname"; FilterSubscription filterSubscription = matcher.registerFilter(queryString1, (userContext, eventType, instance, projection, sortProjection) -> sortProjections.add(sortProjection)); matcher.match(null, null, createPerson1()); matcher.match(null, null, createPerson2()); assertEquals(2, sortProjections.size()); sortProjections.sort(filterSubscription.getComparator()); assertEquals("Cat", sortProjections.get(0)[0]); assertEquals("Woman", sortProjections.get(0)[1]); assertEquals("John", sortProjections.get(1)[0]); assertEquals("Batman", sortProjections.get(1)[1]); } @Test public void testDSL() throws Exception { QueryFactory qf = createQueryFactory(); Query<Person> q = qf.from(Person.class) .having("phoneNumbers.number").eq("004012345").build(); assertTrue(match(q, createPerson1())); } @Test public void testObjectFilterWithExistingSubscription() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person p where p.name = 'John'"; Matcher matcher = createMatcher(); Object person = createPerson1(); int[] matchCount = {0}; FilterSubscription filterSubscription = matcher.registerFilter(queryString, (userContext, eventType, instance, projection, sortProjection) -> matchCount[0]++); ObjectFilter objectFilter = matcher.getObjectFilter(filterSubscription); matcher.match(null, null, person); assertEquals(1, matchCount[0]); ObjectFilter.FilterResult result = objectFilter.filter(person); assertSame(person, result.getInstance()); assertEquals(1, matchCount[0]); // check that the object filter did not also mistakenly trigger a match in the parent matcher } @Test public void testObjectFilterWithQL() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person p where p.name = 'John'"; Matcher matcher = createMatcher(); Object person = createPerson1(); ObjectFilter objectFilter = matcher.getObjectFilter(queryString); ObjectFilter.FilterResult result = objectFilter.filter(person); assertNotNull(result); assertSame(person, result.getInstance()); } @Test public void testObjectFilterWithDSLSamePredicate1() throws Exception { Matcher matcher = createMatcher(); Object person = createPerson1(); QueryFactory qf = createQueryFactory(); // use the same '< 1000' predicate on two different attributes to demonstrate they do not interfere (see ISPN-4654) Query<Person> q = qf.from(Person.class) .having("id").lt(1000) .and() .having("age").lt(1000) .build(); ObjectFilter objectFilter = matcher.getObjectFilter(q); ObjectFilter.FilterResult result = objectFilter.filter(person); assertNotNull(result); assertSame(person, result.getInstance()); } @Test public void testObjectFilterWithDSLSamePredicate2() throws Exception { Matcher matcher = createMatcher(); Object person = createPerson1(); QueryFactory qf = createQueryFactory(); // use the same "like 'Jo%'" predicate (in positive and negative form) on the same attribute to demonstrate they do not interfere (see ISPN-4654) Query<Person> q = qf.from(Person.class) .having("name").like("Jo%") .and(qf.not().having("name").like("Jo%").or().having("id").lt(1000)) .build(); ObjectFilter objectFilter = matcher.getObjectFilter(q); ObjectFilter.FilterResult result = objectFilter.filter(person); assertNotNull(result); assertSame(person, result.getInstance()); } @Test public void testMatcherAndObjectFilterWithDSL() throws Exception { Matcher matcher = createMatcher(); Object person = createPerson1(); QueryFactory qf = createQueryFactory(); Query<Person> q = qf.from(Person.class) .having("name").eq("John").build(); boolean[] b = new boolean[1]; FilterSubscription filterSubscription = matcher.registerFilter(q, (userContext, eventType, instance, projection, sortProjection) -> b[0] = true); ObjectFilter objectFilter = matcher.getObjectFilter(filterSubscription); ObjectFilter.FilterResult result = objectFilter.filter(person); assertNotNull(result); assertSame(person, result.getInstance()); matcher.match(null, null, person); assertTrue(b[0]); } @Test public void testObjectFilterWithDSL() throws Exception { Matcher matcher = createMatcher(); Object person = createPerson1(); QueryFactory qf = createQueryFactory(); Query<Person> q = qf.from(Person.class) .having("name").eq("John").build(); ObjectFilter objectFilter = matcher.getObjectFilter(q); ObjectFilter.FilterResult result = objectFilter.filter(person); assertNotNull(result); assertSame(person, result.getInstance()); } @Test public void testUnregistration() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person p where p.name = 'John'"; Matcher matcher = createMatcher(); Object person = createPerson1(); int[] matchCount = {0}; FilterSubscription filterSubscription = matcher.registerFilter(queryString, (userContext, eventType, instance, projection, sortProjection) -> matchCount[0]++); matcher.match(null, null, person); assertEquals(1, matchCount[0]); matcher.unregisterFilter(filterSubscription); matcher.match(null, null, person); // check that unregistration really took effect assertEquals(1, matchCount[0]); } @Test public void testAnd1() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person p where p.address.postCode = 'SW12345' and p.name = 'John'"; assertTrue(match(queryString, createPerson1())); } @Test public void testAnd2() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person where age > 10 and age < 30"; assertFalse(match(queryString, createPerson1())); } @Test public void testAnd3() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person where age > 30 and name >= 'John'"; assertTrue(match(queryString, createPerson1())); } @Test public void testAnd4() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person where surname = 'X' and age > 10"; assertFalse(match(queryString, createPerson1())); } @Test public void testOr1() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person where age < 30 or age > 10"; assertTrue(match(queryString, createPerson1())); } @Test public void testOr2() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person where surname = 'X' or name like 'Joh%'"; assertTrue(match(queryString, createPerson1())); } @Test public void testOr3() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person p where (p.gender = 'MALE' or p.name = 'John' or p.gender = 'FEMALE') and p.surname = 'Batman'"; assertTrue(match(queryString, createPerson1())); } @Test public void testLike1() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person p where p.phoneNumbers.number like '0040%'"; assertTrue(match(queryString, createPerson1())); } @Test public void testLike2() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person p where p.phoneNumbers.number like '999%'"; assertFalse(match(queryString, createPerson1())); } @Test public void testLike3() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person p where p.name like 'Jo%'"; assertTrue(match(queryString, createPerson1())); } @Test public void testLike4() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person p where p.name like 'Joh_'"; assertTrue(match(queryString, createPerson1())); } @Test public void testLike5() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person p where p.name like 'Joh_nna'"; assertFalse(match(queryString, createPerson1())); } @Test public void testLike6() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person p where p.name like '_oh_'"; assertTrue(match(queryString, createPerson1())); } @Test public void testLike7() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person p where p.name like '_oh_noes'"; assertFalse(match(queryString, createPerson1())); } @Test public void testLike8() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person p where p.name like '%hn%'"; assertTrue(match(queryString, createPerson1())); } @Test public void testLike9() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person p where p.name like '%hn'"; assertTrue(match(queryString, createPerson1())); } @Test public void testLike10() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person p where p.name like 'Jo%hn'"; assertTrue(match(queryString, createPerson1())); } @Test public void testIn() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person where age between 22 and 42"; assertTrue(match(queryString, createPerson1())); } @Test public void testNotIn() throws Exception { String queryString = "from org.infinispan.objectfilter.test.model.Person where age not between 22 and 42"; assertFalse(match(queryString, createPerson1())); } @Test public void testProjections() throws Exception { String queryString = "select p.name, p.address.postCode from org.infinispan.objectfilter.test.model.Person p where p.name = 'John'"; Matcher matcher = createMatcher(); Object person = createPerson1(); List<Object[]> result = new ArrayList<>(); FilterSubscription filterSubscription = matcher.registerFilter(queryString, (userContext, eventType, instance, projection, sortProjection) -> result.add(projection)); assertNotNull(filterSubscription.getProjection()); assertEquals(2, filterSubscription.getProjection().length); assertEquals("name", filterSubscription.getProjection()[0]); assertEquals("address.postCode", filterSubscription.getProjection()[1]); matcher.match(null, null, person); matcher.unregisterFilter(filterSubscription); assertEquals(1, result.size()); assertEquals(2, result.get(0).length); assertEquals("John", result.get(0)[0]); assertEquals("SW12345", result.get(0)[1]); } @Test public void testDuplicateProjections() throws Exception { String queryString = "select p.name, p.name, p.address.postCode from org.infinispan.objectfilter.test.model.Person p where p.name = 'John'"; Matcher matcher = createMatcher(); Object person = createPerson1(); final List<Object[]> result = new ArrayList<>(); FilterSubscription filterSubscription = matcher.registerFilter(queryString, (userContext, eventType, instance, projection, sortProjection) -> result.add(projection)); assertNotNull(filterSubscription.getProjection()); assertEquals(3, filterSubscription.getProjection().length); assertEquals("name", filterSubscription.getProjection()[0]); assertEquals("name", filterSubscription.getProjection()[1]); assertEquals("address.postCode", filterSubscription.getProjection()[2]); matcher.match(null, null, person); matcher.unregisterFilter(filterSubscription); assertEquals(1, result.size()); assertEquals(3, result.get(0).length); assertEquals("John", result.get(0)[0]); assertEquals("John", result.get(0)[1]); assertEquals("SW12345", result.get(0)[2]); } @Test public void testProjectionOnRepeatedAttribute() throws Exception { String queryString = "select p.address.postCode, p.phoneNumbers.number from org.infinispan.objectfilter.test.model.Person p where p.name = 'John'"; Matcher matcher = createMatcher(); Object person = createPerson1(); List<Object[]> result = new ArrayList<>(); FilterSubscription filterSubscription = matcher.registerFilter(queryString, (userContext, eventType, instance, projection, sortProjection) -> result.add(projection)); assertNotNull(filterSubscription.getProjection()); assertEquals(2, filterSubscription.getProjection().length); assertEquals("address.postCode", filterSubscription.getProjection()[0]); assertEquals("phoneNumbers.number", filterSubscription.getProjection()[1]); matcher.match(null, null, person); matcher.unregisterFilter(filterSubscription); assertEquals(1, result.size()); assertEquals(2, result.get(0).length); assertEquals("SW12345", result.get(0)[0]); //todo [anistor] it is unclear what whe should expect here... assertEquals("0040888888", result.get(0)[1]); //expect the first phone number } @Test public void testProjectionOnEmbeddedEntity() { expectedException.expect(ParsingException.class); expectedException.expectMessage("ISPN028503"); String queryString = "select p.phoneNumbers from org.infinispan.objectfilter.test.model.Person p"; Matcher matcher = createMatcher(); matcher.registerFilter(queryString, (userContext, eventType, instance, projection, sortProjection) -> { }); } /** * Test that projections are properly computed even if the query is a tautology so no predicates will ever be * computed. */ @Test public void testTautologyAndProjections() throws Exception { String queryString = "select name from org.infinispan.objectfilter.test.model.Person where age < 30 or age >= 30"; Matcher matcher = createMatcher(); Object person = createPerson1(); List<Object[]> result = new ArrayList<>(); FilterSubscription filterSubscription = matcher.registerFilter(queryString, (userContext, eventType, instance, projection, sortProjection) -> result.add(projection)); assertNotNull(filterSubscription.getProjection()); assertEquals(1, filterSubscription.getProjection().length); assertEquals("name", filterSubscription.getProjection()[0]); matcher.match(null, null, person); matcher.unregisterFilter(filterSubscription); assertEquals(1, result.size()); assertEquals(1, result.get(0).length); assertEquals("John", result.get(0)[0]); } @Test public void testDisallowGroupingAndAggregations() { expectedException.expect(ParsingException.class); expectedException.expectMessage("Filters cannot use grouping or aggregations"); String queryString = "SELECT sum(p.age) " + "FROM org.infinispan.objectfilter.test.model.Person p " + "WHERE p.age <= 99 " + "GROUP BY p.name " + "HAVING COUNT(p.age) > 3"; Matcher matcher = createMatcher(); matcher.registerFilter(queryString, (userContext, eventType, instance, projection, sortProjection) -> { }); } }
29,022
37.492042
230
java
null
infinispan-main/object-filter/src/test/java/org/infinispan/objectfilter/test/FilterQueryFactory.java
package org.infinispan.objectfilter.test; import java.util.List; import java.util.Map; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.objectfilter.impl.logging.Log; import org.infinispan.protostream.SerializationContext; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryBuilder; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.QueryResult; import org.infinispan.query.dsl.impl.BaseQuery; import org.infinispan.query.dsl.impl.BaseQueryBuilder; import org.infinispan.query.dsl.impl.BaseQueryFactory; import org.infinispan.query.dsl.impl.QueryStringCreator; import org.jboss.logging.Logger; /** * @author anistor@redhat.com * @since 7.2 */ final class FilterQueryFactory extends BaseQueryFactory { private final SerializationContext serializationContext; FilterQueryFactory(SerializationContext serializationContext) { this.serializationContext = serializationContext; } FilterQueryFactory() { this(null); } @Override public <T> Query<T> create(String queryString) { return new FilterQuery<>(this, queryString, null, null, -1, -1); } @Override public QueryBuilder from(Class<?> entityType) { if (serializationContext != null) { serializationContext.getMarshaller(entityType); } return new FilterQueryBuilder(this, entityType.getName()); } @Override public QueryBuilder from(String entityType) { if (serializationContext != null) { serializationContext.getMarshaller(entityType); } return new FilterQueryBuilder(this, entityType); } private static final class FilterQueryBuilder extends BaseQueryBuilder { private static final Log log = Logger.getMessageLogger(Log.class, FilterQueryBuilder.class.getName()); FilterQueryBuilder(FilterQueryFactory queryFactory, String rootType) { super(queryFactory, rootType); } @Override public <T> Query<T> build() { QueryStringCreator generator = new QueryStringCreator(); String queryString = accept(generator); if (log.isTraceEnabled()) { log.tracef("Query string : %s", queryString); } return new FilterQuery<>(queryFactory, queryString, generator.getNamedParameters(), getProjectionPaths(), startOffset, maxResults); } } private static final class FilterQuery<T> extends BaseQuery<T> { FilterQuery(QueryFactory queryFactory, String queryString, Map<String, Object> namedParameters, String[] projection, long startOffset, int maxResults) { super(queryFactory, queryString, namedParameters, projection, startOffset, maxResults, false); } @Override public CloseableIterator<T> iterator() { throw new UnsupportedOperationException(); } @Override public void resetQuery() { } @Override public QueryResult<T> execute() { throw new UnsupportedOperationException(); } @Override public int executeStatement() { throw new UnsupportedOperationException(); } // TODO [anistor] need to rethink the dsl Query/QueryBuilder interfaces to accommodate the filtering scenario ... @Override public List<T> list() { throw new UnsupportedOperationException(); } @Override public int getResultSize() { throw new UnsupportedOperationException(); } } }
3,483
30.107143
158
java
null
infinispan-main/object-filter/src/test/java/org/infinispan/objectfilter/test/ProtobufMatcherTest.java
package org.infinispan.objectfilter.test; import org.infinispan.objectfilter.impl.ProtobufMatcher; import org.infinispan.objectfilter.test.model.MarshallerRegistration; import org.infinispan.protostream.ProtobufUtil; import org.infinispan.protostream.SerializationContext; import org.junit.Before; /** * @author anistor@redhat.com * @since 7.0 */ public class ProtobufMatcherTest extends AbstractMatcherTest { private SerializationContext serCtx; private FilterQueryFactory queryFactory; @Before public void setUp() throws Exception { serCtx = ProtobufUtil.newSerializationContext(); MarshallerRegistration.registerMarshallers(serCtx); queryFactory = new FilterQueryFactory(serCtx); } @Override protected FilterQueryFactory createQueryFactory() { return queryFactory; } @Override protected byte[] createPerson1() throws Exception { return ProtobufUtil.toWrappedByteArray(serCtx, super.createPerson1()); } @Override protected byte[] createPerson2() throws Exception { return ProtobufUtil.toWrappedByteArray(serCtx, super.createPerson2()); } @Override protected ProtobufMatcher createMatcher() { return new ProtobufMatcher(serCtx, null); } }
1,245
26.086957
76
java
null
infinispan-main/object-filter/src/test/java/org/infinispan/objectfilter/test/ReflectionMatcherTest.java
package org.infinispan.objectfilter.test; import org.infinispan.objectfilter.impl.ReflectionMatcher; /** * @author anistor@redhat.com * @since 7.0 */ public class ReflectionMatcherTest extends AbstractMatcherTest { private final FilterQueryFactory queryFactory = new FilterQueryFactory(); @Override protected FilterQueryFactory createQueryFactory() { return queryFactory; } protected ReflectionMatcher createMatcher() { return new ReflectionMatcher((ClassLoader) null); } }
512
22.318182
76
java
null
infinispan-main/object-filter/src/test/java/org/infinispan/objectfilter/test/perf/PerfTest.java
package org.infinispan.objectfilter.test.perf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.Arrays; import org.infinispan.commons.test.categories.Profiling; import org.infinispan.objectfilter.Matcher; import org.infinispan.objectfilter.ObjectFilter; import org.infinispan.objectfilter.impl.ReflectionMatcher; import org.infinispan.objectfilter.test.model.Address; import org.infinispan.objectfilter.test.model.Person; import org.infinispan.objectfilter.test.model.PhoneNumber; import org.junit.Ignore; import org.junit.Test; import org.junit.experimental.categories.Category; /** * @author anistor@redhat.com * @since 7.0 */ @Category(Profiling.class) @Ignore public class PerfTest { private final int ITERATIONS = 10000000; private final int NUM_FILTERS = 1; @Test public void testLikeMatchPerf() throws Exception { long time = measureMatch("from org.infinispan.objectfilter.test.model.Person p where p.name like 'Jo%'"); printTime("testLikeMatchPerf", time); } @Test public void testIsNullMatchPerf() throws Exception { long time = measureMatch("from org.infinispan.objectfilter.test.model.Person p where p.name is not null"); printTime("testIsNullMatchPerf", time); } @Test public void testComplexMatchPerf() throws Exception { long time = measureMatch("from org.infinispan.objectfilter.test.model.Person p where p.surname = 'Batman' and p.age > 30 and p.name > 'A' and p.address.postCode = 'SW12345'"); printTime("testComplexMatchPerf", time); } protected long measureMatch(String query) throws Exception { Matcher matcher = createMatcher(); Object obj = createPerson1(); int[] matchCount = new int[1]; for (int k = 0; k < NUM_FILTERS; k++) { matcher.registerFilter(query, (userContext, eventType, instance, projection, sortProjection) -> matchCount[0]++); } long stime = System.nanoTime(); for (int i = 0; i < ITERATIONS; i++) { matchCount[0] = 0; matcher.match(null, null, obj); assertEquals(NUM_FILTERS, matchCount[0]); } return System.nanoTime() - stime; } @Test public void testSimpleObjectFilterPerf() throws Exception { long time = measureFilter("from org.infinispan.objectfilter.test.model.Person p where p.name is not null"); printTime("testSimpleObjectFilterPerf", time); } @Test public void testComplexObjectFilterPerf() throws Exception { long time = measureFilter("from org.infinispan.objectfilter.test.model.Person p where p.surname = 'Batman' and p.age > 30 and p.name > 'A' and p.address.postCode = 'SW12345'"); printTime("testComplexObjectFilterPerf", time); } protected long measureFilter(String query) throws Exception { Matcher matcher = createMatcher(); Object obj = createPerson1(); ObjectFilter objectFilter = matcher.getObjectFilter(query); long stime = System.nanoTime(); for (int i = 0; i < ITERATIONS; i++) { ObjectFilter.FilterResult result = objectFilter.filter(obj); assertNotNull(result); } return System.nanoTime() - stime; } protected void printTime(String text, long totalTime) { double iterationTime = totalTime / 1000; iterationTime /= ITERATIONS; System.out.println(getClass().getSimpleName() + "." + text + " " + iterationTime + "us"); } protected Matcher createMatcher() throws Exception { return new ReflectionMatcher((ClassLoader) null); } protected Object createPerson1() throws Exception { Person person = new Person(); person.setName("John"); person.setSurname("Batman"); person.setAge(40); person.setGender(Person.Gender.MALE); Address address = new Address(); address.setStreet("Old Street"); address.setPostCode("SW12345"); person.setAddress(address); PhoneNumber phoneNumber1 = new PhoneNumber(); phoneNumber1.setNumber("0040888888"); PhoneNumber phoneNumber2 = new PhoneNumber(); phoneNumber2.setNumber("004012345"); person.setPhoneNumbers(Arrays.asList(phoneNumber1, phoneNumber2)); return person; } }
4,251
33.016
182
java
null
infinispan-main/object-filter/src/test/java/org/infinispan/objectfilter/test/perf/ProtobufPerfTest.java
package org.infinispan.objectfilter.test.perf; import org.infinispan.commons.test.categories.Profiling; import org.infinispan.objectfilter.Matcher; import org.infinispan.objectfilter.impl.ProtobufMatcher; import org.infinispan.objectfilter.test.model.MarshallerRegistration; import org.infinispan.protostream.ProtobufUtil; import org.infinispan.protostream.SerializationContext; import org.junit.Before; import org.junit.Ignore; import org.junit.experimental.categories.Category; /** * @author anistor@redhat.com * @since 7.0 */ @Category(Profiling.class) @Ignore public class ProtobufPerfTest extends PerfTest { private SerializationContext serCtx; @Before public void setUp() throws Exception { serCtx = ProtobufUtil.newSerializationContext(); MarshallerRegistration.registerMarshallers(serCtx); } protected Matcher createMatcher() { return new ProtobufMatcher(serCtx, null); } protected Object createPerson1() throws Exception { return ProtobufUtil.toWrappedByteArray(serCtx, super.createPerson1()); } }
1,064
27.783784
76
java
null
infinispan-main/object-filter/src/test/java/org/infinispan/objectfilter/test/model/GenderMarshaller.java
package org.infinispan.objectfilter.test.model; import org.infinispan.protostream.EnumMarshaller; /** * @author anistor@redhat.com * @since 7.0 */ public class GenderMarshaller implements EnumMarshaller<Person.Gender> { @Override public Person.Gender decode(int enumValue) { switch (enumValue) { case 0: return Person.Gender.MALE; case 1: return Person.Gender.FEMALE; } return null; // unknown value } @Override public int encode(Person.Gender gender) { switch (gender) { case MALE: return 0; case FEMALE: return 1; default: throw new IllegalArgumentException("Unexpected User.Gender value : " + gender); } } @Override public Class<Person.Gender> getJavaClass() { return Person.Gender.class; } @Override public String getTypeName() { return "org.infinispan.objectfilter.test.model.Person.Gender"; } }
994
21.613636
91
java
null
infinispan-main/object-filter/src/test/java/org/infinispan/objectfilter/test/model/MarshallerRegistration.java
package org.infinispan.objectfilter.test.model; import java.io.IOException; import org.infinispan.protostream.FileDescriptorSource; import org.infinispan.protostream.SerializationContext; /** * @author anistor@redhat.com * @since 7.0 */ public final class MarshallerRegistration { private static final String PROTOBUF_RES = "org/infinispan/objectfilter/test/model/test_model.proto"; private MarshallerRegistration() { } /** * Registers proto files and marshallers. * * @param ctx the serialization context * @throws org.infinispan.protostream.DescriptorParserException if a proto definition file fails to parse correctly * @throws IOException if proto file registration fails */ public static void registerMarshallers(SerializationContext ctx) throws IOException { ctx.registerProtoFiles(FileDescriptorSource.fromResources(PROTOBUF_RES)); ctx.registerMarshaller(new AddressMarshaller()); ctx.registerMarshaller(new PhoneNumberMarshaller()); ctx.registerMarshaller(new GenderMarshaller()); ctx.registerMarshaller(new PersonMarshaller()); } }
1,122
32.029412
118
java
null
infinispan-main/object-filter/src/test/java/org/infinispan/objectfilter/test/model/Person.java
package org.infinispan.objectfilter.test.model; import java.util.Date; import java.util.List; /** * @author anistor@redhat.com * @since 7.0 */ public class Person { public enum Gender { MALE, FEMALE } // fields start with underscore to demonstrate that property getter access is used instead of field access private String _name; private int _id; private String _surname; private Address _address; private int _age; private List<Integer> _favouriteNumbers; private List<PhoneNumber> _phoneNumbers; private String _license; private Gender _gender; private Date _lastUpdate; private boolean _deleted; public int getId() { return _id; } public void setId(int id) { this._id = id; } public String getName() { return _name; } public void setName(String name) { this._name = name; } public String getSurname() { return _surname; } public void setSurname(String surname) { this._surname = surname; } public Address getAddress() { return _address; } public void setAddress(Address address) { this._address = address; } public int getAge() { return _age; } public void setAge(int age) { this._age = age; } public List<Integer> getFavouriteNumbers() { return _favouriteNumbers; } public void setFavouriteNumbers(List<Integer> favouriteNumbers) { this._favouriteNumbers = favouriteNumbers; } public List<PhoneNumber> getPhoneNumbers() { return _phoneNumbers; } public void setPhoneNumbers(List<PhoneNumber> phoneNumbers) { this._phoneNumbers = phoneNumbers; } public String getLicense() { return _license; } public void setLicense(String license) { this._license = license; } public Gender getGender() { return _gender; } public void setGender(Gender gender) { this._gender = gender; } public Date getLastUpdate() { return _lastUpdate; } public void setLastUpdate(Date lastUpdate) { this._lastUpdate = lastUpdate; } public boolean isDeleted() { return _deleted; } public void setDeleted(boolean deleted) { this._deleted = deleted; } @Override public String toString() { return "Person{" + "id='" + _id + '\'' + ", name='" + _name + '\'' + ", surname='" + _surname + '\'' + ", phoneNumbers=" + _phoneNumbers + ", address=" + _address + ", age=" + _age + ", favouriteNumbers=" + _favouriteNumbers + ", license=" + _license + ", gender=" + _gender + ", lastUpdate=" + _lastUpdate + ", deleted=" + _deleted + '}'; } }
2,814
18.548611
109
java
null
infinispan-main/object-filter/src/test/java/org/infinispan/objectfilter/test/model/PersonMarshaller.java
package org.infinispan.objectfilter.test.model; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import org.infinispan.protostream.MessageMarshaller; /** * @author anistor@redhat.com * @since 7.0 */ public class PersonMarshaller implements MessageMarshaller<Person> { @Override public Person readFrom(ProtoStreamReader reader) throws IOException { Person person = new Person(); person.setId(reader.readInt("id")); person.setName(reader.readString("name")); person.setSurname(reader.readString("surname")); person.setAddress(reader.readObject("address", Address.class)); person.setPhoneNumbers(reader.readCollection("phoneNumbers", new ArrayList<>(), PhoneNumber.class)); person.setAge(reader.readInt("age")); person.setFavouriteNumbers(reader.readCollection("favouriteNumbers", new ArrayList<>(), Integer.class)); person.setLicense(reader.readString("license")); person.setGender(reader.readEnum("gender", Person.Gender.class)); Long lastUpdate = reader.readLong("lastUpdate"); if (lastUpdate != null) { person.setLastUpdate(new Date(lastUpdate)); } person.setDeleted(reader.readBoolean("deleted")); return person; } @Override public void writeTo(ProtoStreamWriter writer, Person person) throws IOException { writer.writeInt("id", person.getId()); writer.writeString("name", person.getName()); writer.writeString("surname", person.getSurname()); writer.writeObject("address", person.getAddress(), Address.class); writer.writeCollection("phoneNumbers", person.getPhoneNumbers(), PhoneNumber.class); writer.writeInt("age", person.getAge()); writer.writeCollection("favouriteNumbers", person.getFavouriteNumbers(), Integer.class); writer.writeString("license", person.getLicense()); writer.writeEnum("gender", person.getGender()); if (person.getLastUpdate() != null) { writer.writeLong("lastUpdate", person.getLastUpdate().getTime()); } writer.writeBoolean("deleted", person.isDeleted()); } @Override public Class<Person> getJavaClass() { return Person.class; } @Override public String getTypeName() { return "org.infinispan.objectfilter.test.model.Person"; } }
2,327
36.548387
110
java
null
infinispan-main/object-filter/src/test/java/org/infinispan/objectfilter/test/model/AddressMarshaller.java
package org.infinispan.objectfilter.test.model; import java.io.IOException; import org.infinispan.protostream.MessageMarshaller; /** * @author anistor@redhat.com * @since 7.0 */ public class AddressMarshaller implements MessageMarshaller<Address> { @Override public Address readFrom(ProtoStreamReader reader) throws IOException { String street = reader.readString("street"); String postCode = reader.readString("postCode"); Address address = new Address(); address.setStreet(street); address.setPostCode(postCode); return address; } @Override public void writeTo(ProtoStreamWriter writer, Address address) throws IOException { writer.writeString("street", address.getStreet()); writer.writeString("postCode", address.getPostCode()); } @Override public Class<Address> getJavaClass() { return Address.class; } @Override public String getTypeName() { return "org.infinispan.objectfilter.test.model.Address"; } }
1,017
23.829268
86
java
null
infinispan-main/object-filter/src/test/java/org/infinispan/objectfilter/test/model/PhoneNumberMarshaller.java
package org.infinispan.objectfilter.test.model; import java.io.IOException; import org.infinispan.protostream.MessageMarshaller; /** * @author anistor@redhat.com * @since 7.0 */ public class PhoneNumberMarshaller implements MessageMarshaller<PhoneNumber> { @Override public PhoneNumber readFrom(ProtoStreamReader reader) throws IOException { PhoneNumber phoneNumber = new PhoneNumber(); phoneNumber.setNumber(reader.readString("number")); return phoneNumber; } @Override public void writeTo(ProtoStreamWriter writer, PhoneNumber phoneNumber) throws IOException { writer.writeString("number", phoneNumber.getNumber()); } @Override public Class<PhoneNumber> getJavaClass() { return PhoneNumber.class; } @Override public String getTypeName() { return "org.infinispan.objectfilter.test.model.PhoneNumber"; } }
888
24.4
94
java
null
infinispan-main/object-filter/src/test/java/org/infinispan/objectfilter/test/model/PhoneNumber.java
package org.infinispan.objectfilter.test.model; /** * @author anistor@redhat.com * @since 7.0 */ public class PhoneNumber { private String number; // this is protected in order to demonstrate that direct field access will be used instead of method access protected String getNumber() { return number; } public void setNumber(String number) { this.number = number; } @Override public String toString() { return "PhoneNumber{" + "number='" + number + '\'' + '}'; } }
542
19.111111
110
java
null
infinispan-main/object-filter/src/test/java/org/infinispan/objectfilter/test/model/Address.java
package org.infinispan.objectfilter.test.model; /** * @author anistor@redhat.com * @since 7.0 */ public class Address { private String street; private String postCode; public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getPostCode() { return postCode; } public void setPostCode(String postCode) { this.postCode = postCode; } @Override public String toString() { return "Address{" + "street='" + street + '\'' + ", postCode='" + postCode + '\'' + '}'; } }
642
16.378378
47
java
null
infinispan-main/object-filter/src/test/java/org/infinispan/objectfilter/impl/syntax/BooleanFilterNormalizerTest.java
package org.infinispan.objectfilter.impl.syntax; import static org.junit.Assert.assertEquals; import org.infinispan.objectfilter.impl.syntax.parser.IckleParser; import org.infinispan.objectfilter.impl.syntax.parser.IckleParsingResult; import org.infinispan.objectfilter.impl.syntax.parser.ReflectionEntityNamesResolver; import org.infinispan.objectfilter.impl.syntax.parser.ReflectionPropertyHelper; import org.junit.Test; /** * @author anistor@redhat.com * @since 7.2 */ public class BooleanFilterNormalizerTest { private final ReflectionPropertyHelper propertyHelper = new ReflectionPropertyHelper(new ReflectionEntityNamesResolver(null)); private final BooleanFilterNormalizer booleanFilterNormalizer = new BooleanFilterNormalizer(); private void assertExpectedTree(String queryString, String expectedExprStr) { IckleParsingResult<Class<?>> parsingResult = IckleParser.parse(queryString, propertyHelper); BooleanExpr expr = booleanFilterNormalizer.normalize(parsingResult.getWhereClause()); assertEquals(expectedExprStr, expr.toString()); } @Test public void testRepeatedPredicateDuplication1() { // predicates on repeated attributes do not get optimized assertExpectedTree("from org.infinispan.objectfilter.test.model.Person p where p.phoneNumbers.number = '1234' and p.phoneNumbers.number = '1234'", "AND(EQUAL(PROP(phoneNumbers.number*), CONST(\"1234\")), EQUAL(PROP(phoneNumbers.number*), CONST(\"1234\")))"); } @Test public void testPredicateDuplication1() { assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where name = 'John' or name = 'John'", "EQUAL(PROP(name), CONST(\"John\"))"); } @Test public void testPredicateDuplication2() { assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where name = 'John' and name = 'John'", "EQUAL(PROP(name), CONST(\"John\"))"); } @Test public void testPredicateDuplication3() { assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where name != 'Johnny' or name != 'Johnny'", "NOT_EQUAL(PROP(name), CONST(\"Johnny\"))"); } @Test public void testPredicateDuplication4() { assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where name != 'Johnny' and name != 'Johnny'", "NOT_EQUAL(PROP(name), CONST(\"Johnny\"))"); } @Test public void testSimpleTautology1() { assertExpectedTree("from org.infinispan.objectfilter.test.model.Person p where p.name = 'Noone' or not(name = 'Noone')", "CONST_TRUE"); } @Test public void testSimpleTautology2() { assertExpectedTree("from org.infinispan.objectfilter.test.model.Person p where p.name = 'Noone' or name != 'Noone'", "CONST_TRUE"); } @Test public void testSimpleTautology3() { assertExpectedTree("from org.infinispan.objectfilter.test.model.Person p where p.name > 'Noone' or name <= 'Noone'", "CONST_TRUE"); } @Test public void testSimpleContradiction1() { assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where name = 'John' and not(name = 'John')", "CONST_FALSE"); } @Test public void testSimpleContradiction2() { assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where name = 'John' and name != 'John'", "CONST_FALSE"); } @Test public void testSimpleContradiction3() { assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where name > 'John' and name <= 'John'", "CONST_FALSE"); } @Test public void testTautology() { assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where (name = 'Noone' and name = 'Noone') or (name != 'Noone' and name != 'Noone')", "CONST_TRUE"); } @Test public void testRepeatedIntervalOverlap1() { // predicates on repeated attributes do not get optimized assertExpectedTree("from org.infinispan.objectfilter.test.model.Person p where p.phoneNumbers.number <= '4567' and p.phoneNumbers.number <= '5678'", "AND(LESS_OR_EQUAL(PROP(phoneNumbers.number*), CONST(\"4567\")), LESS_OR_EQUAL(PROP(phoneNumbers.number*), CONST(\"5678\")))"); } @Test public void testIntervalOverlap() { assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 20 and age = 20", "EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 20 and age != 20", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 20 and age < 20", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 20 and age <= 20", "EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 20 and age >= 20", "EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 20 and age > 20", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 20 and age = 20", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 20 and age != 20", "NOT_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 20 and age < 20", "LESS(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 20 and age <= 20", "LESS(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 20 and age >= 20", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 20 and age > 20", "GREATER(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 20 and age = 20", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 20 and age != 20", "LESS(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 20 and age < 20", "LESS(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 20 and age <= 20", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 20 and age >= 20", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 20 and age > 20", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 20 and age = 20", "EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 20 and age != 20", "LESS(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 20 and age < 20", "EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 20 and age <= 20", "LESS_OR_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 20 and age >= 20", "EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 20 and age > 20", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 20 and age = 20", "EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 20 and age != 20", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 20 and age < 20", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 20 and age <= 20", "EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 20 and age >= 20", "GREATER_OR_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 20 and age > 20", "EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 20 and age = 20", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 20 and age != 20", "GREATER(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 20 and age < 20", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 20 and age <= 20", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 20 and age >= 20", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 20 and age > 20", "GREATER(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 20 or age = 20", "EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 20 or age != 20", "CONST_TRUE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 20 or age < 20", "LESS_OR_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 20 or age <= 20", "LESS_OR_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 20 or age >= 20", "GREATER_OR_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 20 or age > 20", "GREATER_OR_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 20 or age = 20", "CONST_TRUE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 20 or age != 20", "NOT_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 20 or age < 20", "NOT_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 20 or age <= 20", "CONST_TRUE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 20 or age >= 20", "OR(NOT_EQUAL(PROP(age), CONST(20)), GREATER_OR_EQUAL(PROP(age), CONST(20)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 20 or age > 20", "NOT_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 20 or age = 20", "LESS_OR_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 20 or age != 20", "NOT_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 20 or age < 20", "LESS(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 20 or age <= 20", "NOT_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 20 or age >= 20", "CONST_TRUE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 20 or age > 20", "NOT_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 20 or age = 20", "LESS_OR_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 20 or age != 20", "CONST_TRUE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 20 or age < 20", "CONST_TRUE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 20 or age <= 20", "LESS_OR_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 20 or age >= 20", "CONST_TRUE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 20 or age > 20", "CONST_TRUE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 20 or age = 20", "GREATER_OR_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 20 or age != 20", "OR(GREATER_OR_EQUAL(PROP(age), CONST(20)), NOT_EQUAL(PROP(age), CONST(20)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 20 or age < 20", "CONST_TRUE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 20 or age <= 20", "CONST_TRUE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 20 or age >= 20", "GREATER_OR_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 20 or age > 20", "CONST_TRUE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 20 or age = 20", "GREATER_OR_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 20 or age != 20", "NOT_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 20 or age < 20", "NOT_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 20 or age <= 20", "CONST_TRUE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 20 or age >= 20", "NOT_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 20 or age > 20", "GREATER(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 20 and age = 30", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 20 and age != 30", "EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 20 and age < 30", "EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 20 and age <= 30", "EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 20 and age >= 30", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 20 and age > 30", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 20 and age = 30", "EQUAL(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 20 and age != 30", "AND(NOT_EQUAL(PROP(age), CONST(20)), NOT_EQUAL(PROP(age), CONST(30)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 20 and age < 30", "AND(NOT_EQUAL(PROP(age), CONST(20)), LESS(PROP(age), CONST(30)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 20 and age <= 30", "AND(NOT_EQUAL(PROP(age), CONST(20)), LESS_OR_EQUAL(PROP(age), CONST(30)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 20 and age >= 30", "GREATER_OR_EQUAL(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 20 and age > 30", "GREATER(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 20 and age = 30", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 20 and age != 30", "LESS(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 20 and age < 30", "LESS(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 20 and age <= 30", "LESS(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 20 and age >= 30", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 20 and age > 30", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 20 and age = 30", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 20 and age != 30", "LESS_OR_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 20 and age < 30", "LESS_OR_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 20 and age <= 30", "LESS_OR_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 20 and age >= 30", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 20 and age > 30", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 20 and age = 30", "EQUAL(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 20 and age != 30", "GREATER(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 20 and age < 30", "AND(GREATER_OR_EQUAL(PROP(age), CONST(20)), LESS(PROP(age), CONST(30)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 20 and age <= 30", "AND(GREATER_OR_EQUAL(PROP(age), CONST(20)), LESS_OR_EQUAL(PROP(age), CONST(30)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 20 and age >= 30", "GREATER_OR_EQUAL(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 20 and age > 30", "GREATER(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 20 and age = 30", "EQUAL(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 20 and age != 30", "AND(GREATER(PROP(age), CONST(20)), NOT_EQUAL(PROP(age), CONST(30)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 20 and age < 30", "AND(GREATER(PROP(age), CONST(20)), LESS(PROP(age), CONST(30)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 20 and age <= 30", "AND(GREATER(PROP(age), CONST(20)), LESS_OR_EQUAL(PROP(age), CONST(30)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 20 and age >= 30", "GREATER_OR_EQUAL(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 20 and age > 30", "GREATER(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 20 or age = 30", "OR(EQUAL(PROP(age), CONST(20)), EQUAL(PROP(age), CONST(30)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 20 or age != 30", "OR(EQUAL(PROP(age), CONST(20)), NOT_EQUAL(PROP(age), CONST(30)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 20 or age < 30", "LESS(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 20 or age <= 30", "LESS_OR_EQUAL(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 20 or age >= 30", "OR(EQUAL(PROP(age), CONST(20)), GREATER_OR_EQUAL(PROP(age), CONST(30)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 20 or age > 30", "OR(EQUAL(PROP(age), CONST(20)), GREATER(PROP(age), CONST(30)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 20 or age = 30", "OR(NOT_EQUAL(PROP(age), CONST(20)), EQUAL(PROP(age), CONST(30)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 20 or age != 30", "CONST_TRUE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 20 or age < 30", "CONST_TRUE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 20 or age <= 30", "CONST_TRUE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 20 or age >= 30", "NOT_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 20 or age > 30", "NOT_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 20 or age = 30", "OR(LESS(PROP(age), CONST(20)), EQUAL(PROP(age), CONST(30)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 20 or age != 30", "NOT_EQUAL(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 20 or age < 30", "LESS(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 20 or age <= 30", "LESS_OR_EQUAL(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 20 or age >= 30", "OR(LESS(PROP(age), CONST(20)), GREATER_OR_EQUAL(PROP(age), CONST(30)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 20 or age > 30", "OR(LESS(PROP(age), CONST(20)), GREATER(PROP(age), CONST(30)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 20 or age = 30", "OR(LESS_OR_EQUAL(PROP(age), CONST(20)), EQUAL(PROP(age), CONST(30)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 20 or age != 30", "NOT_EQUAL(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 20 or age < 30", "LESS(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 20 or age <= 30", "LESS_OR_EQUAL(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 20 or age >= 30", "OR(LESS_OR_EQUAL(PROP(age), CONST(20)), GREATER_OR_EQUAL(PROP(age), CONST(30)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 20 or age > 30", "OR(LESS_OR_EQUAL(PROP(age), CONST(20)), GREATER(PROP(age), CONST(30)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 20 or age = 30", "GREATER_OR_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 20 or age != 30", "CONST_TRUE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 20 or age < 30", "CONST_TRUE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 20 or age <= 30", "CONST_TRUE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 20 or age >= 30", "GREATER_OR_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 20 or age > 30", "GREATER_OR_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 20 or age = 30", "GREATER(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 20 or age != 30", "CONST_TRUE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 20 or age < 30", "CONST_TRUE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 20 or age <= 30", "CONST_TRUE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 20 or age >= 30", "GREATER(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 20 or age > 30", "GREATER(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 30 and age = 20", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 30 and age != 20", "EQUAL(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 30 and age < 20", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 30 and age <= 20", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 30 and age >= 20", "EQUAL(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 30 and age > 20", "EQUAL(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 30 and age = 20", "EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 30 and age != 20", "AND(NOT_EQUAL(PROP(age), CONST(30)), NOT_EQUAL(PROP(age), CONST(20)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 30 and age < 20", "LESS(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 30 and age <= 20", "LESS_OR_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 30 and age >= 20", "GREATER(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 30 and age > 20", "AND(NOT_EQUAL(PROP(age), CONST(30)), GREATER(PROP(age), CONST(20)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 30 and age = 20", "EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 30 and age != 20", "AND(LESS(PROP(age), CONST(30)), NOT_EQUAL(PROP(age), CONST(20)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 30 and age < 20", "LESS(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 30 and age <= 20", "LESS_OR_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 30 and age >= 20", "AND(LESS(PROP(age), CONST(30)), GREATER_OR_EQUAL(PROP(age), CONST(20)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 30 and age > 20", "AND(LESS(PROP(age), CONST(30)), GREATER(PROP(age), CONST(20)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 30 and age = 20", "EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 30 and age != 20", "AND(LESS_OR_EQUAL(PROP(age), CONST(30)), NOT_EQUAL(PROP(age), CONST(20)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 30 and age < 20", "LESS(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 30 and age <= 20", "LESS_OR_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 30 and age >= 20", "AND(LESS_OR_EQUAL(PROP(age), CONST(30)), GREATER_OR_EQUAL(PROP(age), CONST(20)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 30 and age > 20", "AND(LESS_OR_EQUAL(PROP(age), CONST(30)), GREATER(PROP(age), CONST(20)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 30 and age = 20", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 30 and age != 20", "GREATER_OR_EQUAL(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 30 and age < 20", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 30 and age <= 20", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 30 and age >= 20", "GREATER_OR_EQUAL(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 30 and age > 20", "GREATER_OR_EQUAL(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 30 and age = 20", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 30 and age != 20", "GREATER(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 30 and age < 20", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 30 and age <= 20", "CONST_FALSE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 30 and age >= 20", "GREATER(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 30 and age > 20", "GREATER(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 30 or age = 20", "OR(EQUAL(PROP(age), CONST(30)), EQUAL(PROP(age), CONST(20)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 30 or age != 20", "OR(EQUAL(PROP(age), CONST(30)), NOT_EQUAL(PROP(age), CONST(20)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 30 or age < 20", "OR(EQUAL(PROP(age), CONST(30)), LESS(PROP(age), CONST(20)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 30 or age <= 20", "OR(EQUAL(PROP(age), CONST(30)), LESS_OR_EQUAL(PROP(age), CONST(20)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 30 or age >= 20", "GREATER_OR_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age = 30 or age > 20", "GREATER(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 30 or age = 20", "OR(NOT_EQUAL(PROP(age), CONST(30)), EQUAL(PROP(age), CONST(20)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 30 or age != 20", "CONST_TRUE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 30 or age < 20", "NOT_EQUAL(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 30 or age <= 20", "NOT_EQUAL(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 30 or age >= 20", "CONST_TRUE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age != 30 or age > 20", "CONST_TRUE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 30 or age = 20", "LESS(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 30 or age != 20", "CONST_TRUE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 30 or age < 20", "LESS(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 30 or age <= 20", "LESS(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 30 or age >= 20", "CONST_TRUE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age < 30 or age > 20", "CONST_TRUE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 30 or age = 20", "LESS_OR_EQUAL(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 30 or age != 20", "CONST_TRUE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 30 or age < 20", "LESS_OR_EQUAL(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 30 or age <= 20", "LESS_OR_EQUAL(PROP(age), CONST(30))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 30 or age >= 20", "CONST_TRUE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age <= 30 or age > 20", "CONST_TRUE"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 30 or age = 20", "OR(GREATER_OR_EQUAL(PROP(age), CONST(30)), EQUAL(PROP(age), CONST(20)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 30 or age != 20", "NOT_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 30 or age < 20", "OR(GREATER_OR_EQUAL(PROP(age), CONST(30)), LESS(PROP(age), CONST(20)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 30 or age <= 20", "OR(GREATER_OR_EQUAL(PROP(age), CONST(30)), LESS_OR_EQUAL(PROP(age), CONST(20)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 30 or age >= 20", "GREATER_OR_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age >= 30 or age > 20", "GREATER(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 30 or age = 20", "OR(GREATER(PROP(age), CONST(30)), EQUAL(PROP(age), CONST(20)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 30 or age != 20", "NOT_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 30 or age < 20", "OR(GREATER(PROP(age), CONST(30)), LESS(PROP(age), CONST(20)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 30 or age <= 20", "OR(GREATER(PROP(age), CONST(30)), LESS_OR_EQUAL(PROP(age), CONST(20)))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 30 or age >= 20", "GREATER_OR_EQUAL(PROP(age), CONST(20))"); assertExpectedTree("from org.infinispan.objectfilter.test.model.Person where age > 30 or age > 20", "GREATER(PROP(age), CONST(20))"); } }
35,698
108.171254
193
java
null
infinispan-main/object-filter/src/test/java/org/infinispan/objectfilter/impl/syntax/BooleShannonExpansionTest.java
package org.infinispan.objectfilter.impl.syntax; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import org.infinispan.objectfilter.impl.syntax.parser.IckleParser; import org.infinispan.objectfilter.impl.syntax.parser.IckleParsingResult; import org.infinispan.objectfilter.impl.syntax.parser.ReflectionEntityNamesResolver; import org.infinispan.objectfilter.impl.syntax.parser.ReflectionPropertyHelper; import org.junit.Test; /** * @author anistor@redhat.com * @since 8.0 */ public class BooleShannonExpansionTest { private final ReflectionPropertyHelper propertyHelper = new ReflectionPropertyHelper(new ReflectionEntityNamesResolver(null)); private final BooleanFilterNormalizer booleanFilterNormalizer = new BooleanFilterNormalizer(); private final BooleShannonExpansion booleShannonExpansion = new BooleShannonExpansion(3, new IndexedFieldProvider.FieldIndexingMetadata() { @Override public boolean isIndexed(String[] propertyPath) { String last = propertyPath[propertyPath.length - 1]; return !"number".equals(last) && !"license".equals(last); } @Override public boolean isAnalyzed(String[] propertyPath) { return false; } @Override public boolean isProjectable(String[] propertyPath) { return isIndexed(propertyPath); } @Override public boolean isSortable(String[] propertyPath) { return isIndexed(propertyPath); } @Override public Object getNullMarker(String[] propertyPath) { return null; } }); /** * @param queryString the input query to parse and expand * @param expectedExprStr the expected 'toString()' of the output AST * @param expectedQuery the expected equivalent Ickle query string of the AST */ private void assertExpectedTree(String queryString, String expectedExprStr, String expectedQuery) { IckleParsingResult<Class<?>> parsingResult = IckleParser.parse(queryString, propertyHelper); BooleanExpr expr = booleanFilterNormalizer.normalize(parsingResult.getWhereClause()); expr = booleShannonExpansion.expand(expr); if (expectedExprStr != null) { assertNotNull(expr); assertEquals(expectedExprStr, expr.toString()); } else { assertNull(expr); } if (expectedQuery != null) { String queryOut = SyntaxTreePrinter.printTree(parsingResult.getTargetEntityName(), null, expr, parsingResult.getSortFields()); assertEquals(expectedQuery, queryOut); } } @Test public void testNothingToExpand() { assertExpectedTree("from org.infinispan.objectfilter.test.model.Person", null, "FROM org.infinispan.objectfilter.test.model.Person"); } @Test public void testExpansionNotNeeded() { assertExpectedTree("from org.infinispan.objectfilter.test.model.Person p where " + "p.surname = 'Adrian' or p.name = 'Nistor'", "OR(EQUAL(PROP(surname), CONST(\"Adrian\")), EQUAL(PROP(name), CONST(\"Nistor\")))", "FROM org.infinispan.objectfilter.test.model.Person WHERE (surname = \"Adrian\") OR (name = \"Nistor\")"); } @Test public void testExpansionNotPossible() { assertExpectedTree("from org.infinispan.objectfilter.test.model.Person p where " + "p.license = 'A' or p.name = 'Nistor'", "CONST_TRUE", "FROM org.infinispan.objectfilter.test.model.Person"); } @Test public void testExpansionNotPossible2() { assertExpectedTree("from org.infinispan.objectfilter.test.model.Person p where " + "p.name = 'A' and p.name > 'A'", "CONST_FALSE", null); } @Test public void testExpansionPossible() { assertExpectedTree("from org.infinispan.objectfilter.test.model.Person p where " + "p.phoneNumbers.number != '1234' and p.surname = 'Adrian' or p.name = 'Nistor'", "OR(EQUAL(PROP(surname), CONST(\"Adrian\")), EQUAL(PROP(name), CONST(\"Nistor\")))", "FROM org.infinispan.objectfilter.test.model.Person WHERE (surname = \"Adrian\") OR (name = \"Nistor\")"); } @Test public void testExpansionTooBig() { assertExpectedTree("from org.infinispan.objectfilter.test.model.Person p where " + "p.phoneNumbers.number != '1234' and p.surname = 'Adrian' or p.name = 'Nistor' and license = 'PPL'", "CONST_TRUE", "FROM org.infinispan.objectfilter.test.model.Person"); } }
4,648
38.067227
142
java
null
infinispan-main/object-filter/src/test/java/org/infinispan/objectfilter/impl/syntax/parser/ReflectionParsingTest.java
package org.infinispan.objectfilter.impl.syntax.parser; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import org.junit.Test; /** * @author anistor@redhat.com * @since 7.0 */ public class ReflectionParsingTest extends AbstractParsingTest<Class<?>> { public ReflectionParsingTest() { super(createPropertyHelper()); } private static ObjectPropertyHelper<Class<?>> createPropertyHelper() { return new ReflectionPropertyHelper(new ReflectionEntityNamesResolver(null)); } @Test public void testParsingResult() { String queryString = "from org.infinispan.objectfilter.test.model.Person p where p.name is not null"; IckleParsingResult<Class<?>> result = IckleParser.parse(queryString, propertyHelper); assertNotNull(result.getWhereClause()); assertEquals("org.infinispan.objectfilter.test.model.Person", result.getTargetEntityName()); assertEquals(org.infinispan.objectfilter.test.model.Person.class, result.getTargetEntityMetadata()); assertNull(result.getProjectedPaths()); assertNull(result.getSortFields()); } }
1,183
31
107
java
null
infinispan-main/object-filter/src/test/java/org/infinispan/objectfilter/impl/syntax/parser/ExpressionBuilderTest.java
package org.infinispan.objectfilter.impl.syntax.parser; import static org.junit.Assert.assertEquals; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import org.infinispan.objectfilter.impl.ql.PropertyPath; import org.infinispan.objectfilter.impl.syntax.BooleanExpr; import org.infinispan.objectfilter.impl.syntax.ComparisonExpr; import org.junit.Before; import org.junit.Test; /** * Test for {@link ExpressionBuilder}. * * @author anistor@redhat.com * @since 9.0 */ public class ExpressionBuilderTest { private ExpressionBuilder<Class<?>> builder; @Before public void setup() { ReflectionPropertyHelper propertyHelper = new ReflectionPropertyHelper(new ReflectionEntityNamesResolver(null)); builder = new ExpressionBuilder<>(propertyHelper); } @Test public void testStringEqualsQuery() { builder.setEntityType(TestEntity.class); builder.addComparison(PropertyPath.make("name"), ComparisonExpr.Type.EQUAL, "foo"); BooleanExpr query = builder.build(); assertEquals("EQUAL(PROP(name), CONST(\"foo\"))", query.toString()); } @Test public void testStringEqualsQueryOnEmbeddedProperty() { builder.setEntityType(TestEntity.class); builder.addComparison(PropertyPath.make("embedded.title"), ComparisonExpr.Type.EQUAL, "bar"); BooleanExpr query = builder.build(); assertEquals("EQUAL(PROP(embedded.title), CONST(\"bar\"))", query.toString()); } @Test public void testLongEqualsQuery() { builder.setEntityType(TestEntity.class); builder.addComparison(PropertyPath.make("l"), ComparisonExpr.Type.EQUAL, 10); BooleanExpr query = builder.build(); assertEquals("EQUAL(PROP(l), CONST(10))", query.toString()); } @Test public void testDoubleEqualsQuery() { builder.setEntityType(TestEntity.class); builder.addComparison(PropertyPath.make("d"), ComparisonExpr.Type.EQUAL, 10.0); BooleanExpr query = builder.build(); assertEquals("EQUAL(PROP(d), CONST(10.0))", query.toString()); } @Test public void testDateEqualsQuery() throws Exception { builder.setEntityType(TestEntity.class); builder.addComparison(PropertyPath.make("date"), ComparisonExpr.Type.EQUAL, makeDate("2016-09-25")); BooleanExpr query = builder.build(); assertEquals("EQUAL(PROP(date), CONST(20160925000000000))", query.toString()); } @Test public void testDateRangeQuery() throws Exception { builder.setEntityType(TestEntity.class); builder.addRange(PropertyPath.make("date"), makeDate("2016-8-25"), makeDate("2016-10-25")); BooleanExpr query = builder.build(); assertEquals("BETWEEN(PROP(date), CONST(20160825000000000), CONST(20161025000000000))", query.toString()); } @Test public void testIntegerRangeQuery() { builder.setEntityType(TestEntity.class); builder.addRange(PropertyPath.make("i"), 1, 10); BooleanExpr query = builder.build(); assertEquals("BETWEEN(PROP(i), CONST(1), CONST(10))", query.toString()); } @Test public void testNegationQuery() { builder.setEntityType(TestEntity.class); builder.pushNot(); builder.addComparison(PropertyPath.make("name"), ComparisonExpr.Type.EQUAL, "foo"); BooleanExpr query = builder.build(); assertEquals("NOT(EQUAL(PROP(name), CONST(\"foo\")))", query.toString()); } @Test public void testConjunctionQuery() { builder.setEntityType(TestEntity.class); builder.pushAnd(); builder.addComparison(PropertyPath.make("name"), ComparisonExpr.Type.EQUAL, "foo"); builder.addComparison(PropertyPath.make("i"), ComparisonExpr.Type.EQUAL, 1); BooleanExpr query = builder.build(); assertEquals("AND(EQUAL(PROP(name), CONST(\"foo\")), EQUAL(PROP(i), CONST(1)))", query.toString()); } @Test public void testDisjunctionQuery() { builder.setEntityType(TestEntity.class); builder.pushOr(); builder.addComparison(PropertyPath.make("name"), ComparisonExpr.Type.EQUAL, "foo"); builder.addComparison(PropertyPath.make("i"), ComparisonExpr.Type.EQUAL, 1); BooleanExpr query = builder.build(); assertEquals("OR(EQUAL(PROP(name), CONST(\"foo\")), EQUAL(PROP(i), CONST(1)))", query.toString()); } @Test public void testNestedLogicalPredicatesQuery() { builder.setEntityType(TestEntity.class); builder.pushAnd(); builder.pushOr(); builder.addComparison(PropertyPath.make("name"), ComparisonExpr.Type.EQUAL, "foo"); builder.addComparison(PropertyPath.make("i"), ComparisonExpr.Type.EQUAL, 1); builder.pop(); builder.addComparison(PropertyPath.make("l"), ComparisonExpr.Type.EQUAL, 10); BooleanExpr query = builder.build(); assertEquals("AND(OR(EQUAL(PROP(name), CONST(\"foo\")), EQUAL(PROP(i), CONST(1))), EQUAL(PROP(l), CONST(10)))", query.toString()); } private Date makeDate(String input) throws ParseException { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); return dateFormat.parse(input); } static class TestEntity { public String id; public String name; public Date date; public int i; public long l; public float f; public double d; public EmbeddedTestEntity embedded; static class EmbeddedTestEntity { public String title; } } }
5,538
31.582353
136
java
null
infinispan-main/object-filter/src/test/java/org/infinispan/objectfilter/impl/syntax/parser/ProtobufParsingTest.java
package org.infinispan.objectfilter.impl.syntax.parser; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.io.IOException; import org.infinispan.objectfilter.test.model.MarshallerRegistration; import org.infinispan.protostream.ProtobufUtil; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.descriptors.Descriptor; import org.junit.Test; /** * @author anistor@redhat.com * @since 7.0 */ public class ProtobufParsingTest extends AbstractParsingTest<Descriptor> { public ProtobufParsingTest() throws IOException { super(createPropertyHelper()); } private static ObjectPropertyHelper<Descriptor> createPropertyHelper() throws IOException { SerializationContext serCtx = ProtobufUtil.newSerializationContext(); MarshallerRegistration.registerMarshallers(serCtx); return new ProtobufPropertyHelper(serCtx, null); } @Test public void testParsingResult() { String queryString = "from org.infinispan.objectfilter.test.model.Person p where p.name is not null"; IckleParsingResult<Descriptor> result = IckleParser.parse(queryString, propertyHelper); assertNotNull(result.getWhereClause()); assertEquals("org.infinispan.objectfilter.test.model.Person", result.getTargetEntityName()); assertEquals("org.infinispan.objectfilter.test.model.Person", result.getTargetEntityMetadata().getFullName()); assertNull(result.getProjectedPaths()); assertNull(result.getSortFields()); } @Test @Override public void testInvalidDateLiteral() { // protobuf does not have a Date type, but keep this empty test here just as a reminder } }
1,763
33.588235
116
java
null
infinispan-main/object-filter/src/test/java/org/infinispan/objectfilter/impl/syntax/parser/AbstractParsingTest.java
package org.infinispan.objectfilter.impl.syntax.parser; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import org.infinispan.objectfilter.ParsingException; import org.infinispan.objectfilter.impl.syntax.ConstantBooleanExpr; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; /** * @author anistor@redhat.com * @since 7.0 */ public abstract class AbstractParsingTest<TypeMetadata> { @Rule public ExpectedException expectedException = ExpectedException.none(); protected final ObjectPropertyHelper<TypeMetadata> propertyHelper; protected AbstractParsingTest(ObjectPropertyHelper<TypeMetadata> propertyHelper) { this.propertyHelper = propertyHelper; } @Test public void testWhereTautology() { String queryString = "FROM org.infinispan.objectfilter.test.model.Person WHERE true"; IckleParsingResult<TypeMetadata> result = IckleParser.parse(queryString, propertyHelper); assertEquals(ConstantBooleanExpr.TRUE, result.getWhereClause()); assertNull(result.getHavingClause()); } @Test public void testWhereContradiction() { String queryString = "FROM org.infinispan.objectfilter.test.model.Person WHERE false"; IckleParsingResult<TypeMetadata> result = IckleParser.parse(queryString, propertyHelper); assertEquals(ConstantBooleanExpr.FALSE, result.getWhereClause()); assertNull(result.getHavingClause()); } @Test public void testRaiseExceptionDueToUnconsumedTokens() { expectedException.expect(ParsingException.class); expectedException.expectMessage("ISPN028526"); String queryString = "FROM IndexedEntity u WHERE u.name = 'John' blah blah blah"; IckleParser.parse(queryString, propertyHelper); } @Test public void testInvalidNumericLiteral() { expectedException.expect(ParsingException.class); expectedException.expectMessage("ISPN028505"); String queryString = "from org.infinispan.objectfilter.test.model.Person where age = 'xyz'"; IckleParser.parse(queryString, propertyHelper); } @Test public void testInvalidDateLiteral() { expectedException.expect(ParsingException.class); expectedException.expectMessage("ISPN028506"); String queryString = "from org.infinispan.objectfilter.test.model.Person where lastUpdate = '20140101zzzzzzzz'"; IckleParser.parse(queryString, propertyHelper); } @Test public void testInvalidEnumLiteral() { expectedException.expect(ParsingException.class); expectedException.expectMessage("ISPN028508"); String queryString = "from org.infinispan.objectfilter.test.model.Person where gender = 'SomeUndefinedValue'"; IckleParser.parse(queryString, propertyHelper); } @Test public void testInvalidBooleanLiteral() { expectedException.expect(ParsingException.class); expectedException.expectMessage("ISPN028507"); String queryString = "from org.infinispan.objectfilter.test.model.Person where deleted = 'maybe'"; IckleParser.parse(queryString, propertyHelper); } @Test public void testInvalidPredicateOnEmbeddedEntity() { expectedException.expect(ParsingException.class); expectedException.expectMessage("ISPN028504"); String queryString = "from org.infinispan.objectfilter.test.model.Person where address = 5"; IckleParser.parse(queryString, propertyHelper); } @Test public void testInvalidPredicateOnCollectionOfEmbeddedEntity() { expectedException.expect(ParsingException.class); expectedException.expectMessage("ISPN028504"); String queryString = "from org.infinispan.objectfilter.test.model.Person where phoneNumbers = 5"; IckleParser.parse(queryString, propertyHelper); } @Test public void testFullTextQueryNotAccepted() { expectedException.expect(ParsingException.class); expectedException.expectMessage("ISPN028521"); String queryString = "from org.infinispan.objectfilter.test.model.Person where name : 'Joe'"; IckleParser.parse(queryString, propertyHelper); } }
4,137
37.672897
118
java
null
infinispan-main/object-filter/src/test/java/org/infinispan/objectfilter/impl/aggregation/DoubleStatTest.java
package org.infinispan.objectfilter.impl.aggregation; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import org.junit.Test; /** * @author anistor@redhat.com * @since 8.1 */ public class DoubleStatTest { private static final double DELTA = 0.0000001d; @Test public void testEmptySum() { DoubleStat sum = new DoubleStat(); assertNull(sum.getSum()); } @Test public void testEmptyAvg() { DoubleStat avg = new DoubleStat(); assertNull(avg.getAvg()); } @Test public void testSum() { DoubleStat sum = new DoubleStat(); sum.update(10); sum.update(20); Double computedSum = sum.getSum(); assertNotNull(computedSum); assertEquals(30.0d, computedSum, DELTA); } @Test public void testAvg() { DoubleStat avg = new DoubleStat(); avg.update(10); avg.update(20); Double computedAvg = avg.getAvg(); assertNotNull(computedAvg); assertEquals(15.0d, computedAvg, DELTA); } @Test public void testSumWithNaN() { DoubleStat sum = new DoubleStat(); sum.update(10); sum.update(Double.NaN); Double computedSum = sum.getSum(); assertNotNull(computedSum); assertEquals(Double.NaN, computedSum, DELTA); } @Test public void testAvgWithNaN() { DoubleStat avg = new DoubleStat(); avg.update(10); avg.update(Double.NaN); Double computedAvg = avg.getAvg(); assertNotNull(computedAvg); assertEquals(Double.NaN, computedAvg, DELTA); } @Test public void testSumWithPlusInf() { DoubleStat sum = new DoubleStat(); sum.update(10); sum.update(Double.POSITIVE_INFINITY); Double computedSum = sum.getSum(); assertNotNull(computedSum); assertEquals(Double.POSITIVE_INFINITY, computedSum, DELTA); } @Test public void testAvgWithPlusInf() { DoubleStat avg = new DoubleStat(); avg.update(10); avg.update(Double.POSITIVE_INFINITY); Double computedAvg = avg.getAvg(); assertNotNull(computedAvg); assertEquals(Double.POSITIVE_INFINITY, computedAvg, DELTA); } @Test public void testSumWithMinusInf() { DoubleStat sum = new DoubleStat(); sum.update(10); sum.update(Double.NEGATIVE_INFINITY); Double computedSum = sum.getSum(); assertNotNull(computedSum); assertEquals(Double.NEGATIVE_INFINITY, computedSum, DELTA); } @Test public void testAvgWithMinusInf() { DoubleStat avg = new DoubleStat(); avg.update(10); avg.update(Double.NEGATIVE_INFINITY); Double computedAvg = avg.getAvg(); assertNotNull(computedAvg); assertEquals(Double.NEGATIVE_INFINITY, computedAvg, DELTA); } @Test public void testSumWithMinusInfAndPlusInf() { DoubleStat sum = new DoubleStat(); sum.update(10); sum.update(Double.NEGATIVE_INFINITY); sum.update(Double.POSITIVE_INFINITY); Double computedSum = sum.getSum(); assertNotNull(computedSum); assertEquals(Double.NaN, computedSum, DELTA); } @Test public void testAvgWithMinusInfAndPlusInf() { DoubleStat avg = new DoubleStat(); avg.update(10); avg.update(Double.NEGATIVE_INFINITY); avg.update(Double.POSITIVE_INFINITY); Double computedAvg = avg.getAvg(); assertNotNull(computedAvg); assertEquals(Double.NaN, computedAvg, DELTA); } }
3,516
25.847328
65
java
null
infinispan-main/object-filter/src/test/java/org/infinispan/objectfilter/impl/predicateindex/LikeConditionTest.java
package org.infinispan.objectfilter.impl.predicateindex; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; /** * @author anistor@redhat.com * @since 9.0 */ public class LikeConditionTest { @Test public void testDegeneratedEquals() { LikeCondition likeCondition = new LikeCondition("ab"); assertTrue(likeCondition.match("ab")); assertFalse(likeCondition.match("ac")); assertFalse(likeCondition.match("XabY")); } @Test public void testDegeneratedContains() { LikeCondition likeCondition = new LikeCondition("%ab%"); assertTrue(likeCondition.match("ab")); assertTrue(likeCondition.match("xabxx")); assertFalse(likeCondition.match("axb")); } @Test public void testDegeneratedStartsWith() { assertTrue(new LikeCondition("ab%").match("ab")); assertTrue(new LikeCondition("ab%").match("abx")); assertTrue(new LikeCondition("ab%").match("abxx")); assertFalse(new LikeCondition("ab%").match("xab")); assertFalse(new LikeCondition("ab%").match("axb")); assertTrue(new LikeCondition("ab_").match("abc")); assertFalse(new LikeCondition("ab_").match("ab")); assertFalse(new LikeCondition("ab_").match("abxx")); assertFalse(new LikeCondition("ab_").match("xab")); assertFalse(new LikeCondition("ab_").match("xaby")); } @Test public void testDegeneratedEndsWith() { assertTrue(new LikeCondition("%ab").match("ab")); assertTrue(new LikeCondition("%ab").match("xab")); assertTrue(new LikeCondition("%ab").match("xxab")); assertFalse(new LikeCondition("%ab").match("abx")); assertFalse(new LikeCondition("%ab").match("axb")); assertTrue(new LikeCondition("_ab").match("cab")); assertFalse(new LikeCondition("_ab").match("ab")); assertFalse(new LikeCondition("_ab").match("xxab")); assertFalse(new LikeCondition("_ab").match("abc")); assertFalse(new LikeCondition("_ab").match("xabc")); } @Test public void testSingleCharWildcard() { LikeCondition likeCondition = new LikeCondition("a_b_c"); assertTrue(likeCondition.match("aXbYc")); assertTrue(likeCondition.match("a_b_c")); assertTrue(likeCondition.match("a%b%c")); assertFalse(likeCondition.match("abc")); assertFalse(likeCondition.match("aXXbYYc")); } @Test public void testMultipleCharWildcard() { LikeCondition likeCondition = new LikeCondition("a%b%c"); assertTrue(likeCondition.match("abc")); assertTrue(likeCondition.match("aXbc")); assertTrue(likeCondition.match("aXYbZc")); assertTrue(likeCondition.match("a_b_c")); assertTrue(likeCondition.match("a%b%c")); assertFalse(likeCondition.match("a")); assertFalse(likeCondition.match("aX")); assertFalse(likeCondition.match("a%")); } @Test public void testEscapeChar() { assertTrue(new LikeCondition("a\\%b").match("a%b")); assertFalse(new LikeCondition("a\\%b").match("aXb")); assertFalse(new LikeCondition("a\\%b").match("ab")); assertTrue(new LikeCondition("a\\\\b").match("a\\b")); assertTrue(new LikeCondition("a~%b", '~').match("a%b")); assertFalse(new LikeCondition("a~%b", '~').match("aXb")); assertFalse(new LikeCondition("a~%b", '~').match("ab")); assertTrue(new LikeCondition("a~~b", '~').match("a~b")); } @Test public void testPlusEscaping() { LikeCondition likeCondition = new LikeCondition("a%aZ+"); assertTrue(likeCondition.match("aaaZ+")); assertFalse(likeCondition.match("aaa")); assertFalse(likeCondition.match("aaaZ")); assertFalse(likeCondition.match("aaaZZ")); assertFalse(likeCondition.match("aaaZZZ")); } @Test public void testAsteriskEscaping() { LikeCondition likeCondition = new LikeCondition("a%aZ*"); assertTrue(likeCondition.match("aaaZ*")); assertFalse(likeCondition.match("aaa")); assertFalse(likeCondition.match("aaaZ")); assertFalse(likeCondition.match("aaaZZ")); assertFalse(likeCondition.match("aaaZZZ")); } @Test public void testGeneralMetacharEscaping() { assertTrue(new LikeCondition("a%(b").match("aaa(b")); assertTrue(new LikeCondition("a%)b").match("aaa)b")); assertTrue(new LikeCondition("a%[b").match("aaa[b")); assertTrue(new LikeCondition("a%]b").match("aaa]b")); assertTrue(new LikeCondition("a%{b").match("aaa{b")); assertTrue(new LikeCondition("a%}b").match("aaa}b")); assertTrue(new LikeCondition("a%$b").match("aaa$b")); assertTrue(new LikeCondition("a%^b").match("aaa^b")); assertTrue(new LikeCondition("a%.b").match("aaa.b")); assertTrue(new LikeCondition("a%|b").match("aaa|b")); assertTrue(new LikeCondition("a%\\b").match("aaa\\b")); } }
4,892
36.638462
63
java
null
infinispan-main/object-filter/src/test/java/org/infinispan/objectfilter/impl/util/IntervalTreeTest.java
package org.infinispan.objectfilter.impl.util; import static org.junit.Assert.assertEquals; import java.util.List; import org.junit.Test; /** * @author anistor@redhat.com * @since 7.0 */ public class IntervalTreeTest { @Test public void testSingleIntervalStab() { Interval<Integer> interval = new Interval<>(3, true, 100, false); IntervalTree<Integer, String> tree = new IntervalTree<>(); tree.add(interval); List<IntervalTree.Node<Integer, String>> result = tree.stab(3); assertEquals(1, result.size()); assertEquals(interval, result.get(0).interval); result = tree.stab(100); assertEquals(0, result.size()); result = tree.stab(4); assertEquals(1, result.size()); assertEquals(interval, result.get(0).interval); result = tree.stab(99); assertEquals(1, result.size()); assertEquals(interval, result.get(0).interval); result = tree.stab(2); assertEquals(0, result.size()); result = tree.stab(101); assertEquals(0, result.size()); } }
1,064
23.767442
71
java
null
infinispan-main/object-filter/src/test/java/org/infinispan/objectfilter/impl/util/ReflectionHelperTest.java
package org.infinispan.objectfilter.impl.util; import static org.junit.Assert.assertEquals; import java.util.Collection; import java.util.List; import java.util.Map; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; /** * @author anistor@redhat.com * @since 7.0 */ public class ReflectionHelperTest { @Rule public ExpectedException expectedException = ExpectedException.none(); // start of test dummies private static class Base { private int prop1; public float getProp2() { return 0; } private Base prop3 = null; } private abstract static class X { } private abstract static class Y extends X implements Comparable<String>, List<Long> { } private abstract static class Z extends Y { } private abstract static class Q extends X implements Map<String, Double> { } private abstract static class W extends Q { } @SuppressWarnings("unused") private static class A<T extends Base> { T[] array; Float[] array2; float[] array3; Collection<T>[] array4; List<Integer> list; List<List<Integer>> list2; List<Base> list3; Map<String, Integer> map; Map<T, T> map2; Y y; Z z; Q q; Q w; } // end of dummies @Test public void testGetSimpleProperty() throws Exception { assertEquals(int.class, ReflectionHelper.getAccessor(Base.class, "prop1").getPropertyType()); assertEquals(float.class, ReflectionHelper.getAccessor(Base.class, "prop2").getPropertyType()); } @Test public void testPropertyNotFound() throws Exception { expectedException.expect(ReflectiveOperationException.class); expectedException.expectMessage("Property not found: unknown"); ReflectionHelper.getAccessor(Base.class, "unknown"); } @Test public void testGetNestedProperty() throws Exception { ReflectionHelper.PropertyAccessor prop3 = ReflectionHelper.getAccessor(Base.class, "prop3"); assertEquals(Base.class, prop3.getPropertyType()); assertEquals(int.class, prop3.getAccessor("prop1").getPropertyType()); } @Test public void testGetMultipleProperty() throws Exception { assertEquals(Base.class, ReflectionHelper.getAccessor(A.class, "array").getPropertyType()); assertEquals(Float.class, ReflectionHelper.getAccessor(A.class, "array2").getPropertyType()); assertEquals(float.class, ReflectionHelper.getAccessor(A.class, "array3").getPropertyType()); assertEquals(Collection.class, ReflectionHelper.getAccessor(A.class, "array4").getPropertyType()); assertEquals(Integer.class, ReflectionHelper.getAccessor(A.class, "list").getPropertyType()); assertEquals(List.class, ReflectionHelper.getAccessor(A.class, "list2").getPropertyType()); assertEquals(Base.class, ReflectionHelper.getAccessor(A.class, "list3").getPropertyType()); assertEquals(Integer.class, ReflectionHelper.getAccessor(A.class, "map").getPropertyType()); assertEquals(Base.class, ReflectionHelper.getAccessor(A.class, "map2").getPropertyType()); assertEquals(Long.class, ReflectionHelper.getAccessor(A.class, "y").getPropertyType()); assertEquals(Long.class, ReflectionHelper.getAccessor(A.class, "z").getPropertyType()); assertEquals(Double.class, ReflectionHelper.getAccessor(A.class, "q").getPropertyType()); assertEquals(Double.class, ReflectionHelper.getAccessor(A.class, "w").getPropertyType()); } }
3,524
31.33945
104
java
null
infinispan-main/object-filter/src/test/java/org/infinispan/objectfilter/impl/util/IntervalTest.java
package org.infinispan.objectfilter.impl.util; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; /** * @author anistor@redhat.com * @since 7.0 */ public class IntervalTest { @Test public void testContains() { assertTrue(new Interval(Interval.<Integer>getMinusInf(), false, 1000, false).contains(20)); assertFalse(new Interval(Interval.<Integer>getMinusInf(), false, 1000, false).contains(1000)); assertFalse(new Interval(Interval.<Integer>getMinusInf(), false, 1000, false).contains(1001)); assertTrue(new Interval(1000, false, Interval.<Integer>getPlusInf(), false).contains(2000)); assertFalse(new Interval(1000, false, Interval.<Integer>getPlusInf(), false).contains(1000)); assertFalse(new Interval(1000, false, Interval.<Integer>getPlusInf(), false).contains(999)); } }
888
34.56
100
java
null
infinispan-main/object-filter/src/test/java/org/infinispan/objectfilter/impl/ql/test/GrammarTest.java
/* * Copyright 2016, Red Hat Inc. and/or its affiliates. * * 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 org.infinispan.objectfilter.impl.ql.test; import org.junit.Test; /** * @author anistor@redhat.com * @since 9.0 */ public class GrammarTest extends TestBase { @Test public void testDelete1() { expectParserSuccess("delete from example.legacy.Category", "(delete (from (PERSISTER_SPACE (ENTITY_PERSISTER_REF example.legacy.Category <gen:0>))))"); } @Test public void testDelete2() { expectParserSuccess("delete from example.legacy.Category c where c.id = 46", "(delete (from (PERSISTER_SPACE (ENTITY_PERSISTER_REF example.legacy.Category c))) (where (= (PATH (. c id)) 46)))"); } @Test public void testFT1() { String expectedFrom = "(QUERY (QUERY_SPEC (SELECT_FROM (from (PERSISTER_SPACE (ENTITY_PERSISTER_REF Cat cat))) (SELECT (SELECT_LIST (SELECT_ITEM cat)))) "; expectParserSuccess("from Cat cat where name = 1", expectedFrom + "(where (= (PATH name) 1))))"); expectParserSuccess("from Cat cat where name : /tom.at/", expectedFrom + "(where (: (PATH name) (FT_REGEXP tom.at)))))"); expectParserSuccess("from Cat cat where cat.name.xyz = 1", expectedFrom + "(where (= (PATH (. (. cat name) xyz)) 1))))"); expectParserSuccess("from Cat cat where cat.name.xyz : 1", expectedFrom + "(where (: (PATH (. (. cat name) xyz)) (FT_TERM 1)))))"); expectParserSuccess("from Cat cat where name : 'Tom*' and age > 5", expectedFrom + "(where (and (: (PATH name) (FT_TERM (CONST_STRING_VALUE Tom*))) (> (PATH age) 5)))))"); expectParserFailure("from Cat cat where (name : 'Tom') + 2"); expectParserFailure("from Cat cat where name : 'Tom' + 2"); expectParserSuccess("from Cat cat where 2 > 5", expectedFrom + "(where (> 2 5))))"); expectParserSuccess("from Cat cat where (2 > 5)", expectedFrom + "(where (> 2 5))))"); expectParserSuccess("from Cat cat where name : (+'Tom')", expectedFrom + "(where (: (PATH name) (+ (FT_TERM (CONST_STRING_VALUE Tom)))))))"); expectParserSuccess("from Cat cat where -name : (+1)", expectedFrom + "(where (: (PATH name) (- (+ (FT_TERM 1)))))))"); expectParserSuccess("from Cat cat where t.description : (+'playful' -'fat' 'kitten')", expectedFrom + "(where (: (PATH (. t description)) (OR (OR (+ (FT_TERM (CONST_STRING_VALUE playful))) (- (FT_TERM (CONST_STRING_VALUE fat)))) (FT_TERM (CONST_STRING_VALUE kitten)))))))"); } @Test public void testFT2() { String expectedFrom = "(QUERY (QUERY_SPEC (SELECT_FROM (from (PERSISTER_SPACE (ENTITY_PERSISTER_REF Cat cat))) (SELECT (SELECT_LIST (SELECT_ITEM cat)))) "; expectParserSuccess("from Cat cat where name : ('xx') and not surname:9", expectedFrom + "(where (and (: (PATH name) (FT_TERM (CONST_STRING_VALUE xx))) (not (: (PATH surname) (FT_TERM 9)))))))"); expectParserSuccess("from Cat cat where name : (not 9)", expectedFrom + "(where (: (PATH name) (not (FT_TERM 9))))))"); expectParserSuccess("from Cat cat where name : 9", expectedFrom + "(where (: (PATH name) (FT_TERM 9)))))"); expectParserSuccess("from Cat cat where not name : 9", expectedFrom + "(where (not (: (PATH name) (FT_TERM 9))))))"); expectParserSuccess("from Cat cat where not name : (-9)", expectedFrom + "(where (not (: (PATH name) (- (FT_TERM 9)))))))"); expectParserSuccess("from Cat cat where ! name : (-9)", expectedFrom + "(where (! (: (PATH name) (- (FT_TERM 9)))))))"); expectParserSuccess("from Cat cat where -name : 9", expectedFrom + "(where (: (PATH name) (- (FT_TERM 9))))))"); expectParserSuccess("from Cat cat where -name : (!9)", expectedFrom + "(where (: (PATH name) (- (! (FT_TERM 9)))))))"); expectParserSuccess("from Cat cat where -name : (- 9)", expectedFrom + "(where (: (PATH name) (- (- (FT_TERM 9)))))))"); expectParserSuccess("from Cat cat where -name : (-9)", expectedFrom + "(where (: (PATH name) (- (- (FT_TERM 9)))))))"); expectParserSuccess("from Cat cat where -name : (-9 || 0)", expectedFrom + "(where (: (PATH name) (- (|| (- (FT_TERM 9)) (FT_TERM 0)))))))"); expectParserSuccess("from Cat cat where -name : (+ 9)", expectedFrom + "(where (: (PATH name) (- (+ (FT_TERM 9)))))))"); expectParserSuccess("from Cat cat where name : ('Fritz' 'Purr' 'Meow')", expectedFrom + "(where (: (PATH name) (OR (OR (FT_TERM (CONST_STRING_VALUE Fritz)) (FT_TERM (CONST_STRING_VALUE Purr))) (FT_TERM (CONST_STRING_VALUE Meow)))))))"); expectParserSuccess("from Cat cat where name : ('Fritz' or 'Purr')", expectedFrom + "(where (: (PATH name) (or (FT_TERM (CONST_STRING_VALUE Fritz)) (FT_TERM (CONST_STRING_VALUE Purr)))))))"); expectParserSuccess("from Cat cat where name : ('Fritz' and 'Purr')", expectedFrom + "(where (: (PATH name) (and (FT_TERM (CONST_STRING_VALUE Fritz)) (FT_TERM (CONST_STRING_VALUE Purr)))))))"); expectParserSuccess("from Cat cat where name : \"Fritz\" and surname:'Purr'", expectedFrom + "(where (and (: (PATH name) (FT_TERM (CONST_STRING_VALUE Fritz))) (: (PATH surname) (FT_TERM (CONST_STRING_VALUE Purr)))))))"); expectParserSuccess("from Cat cat where (name : \"Tom\") || name > 3", expectedFrom + "(where (|| (: (PATH name) (FT_TERM (CONST_STRING_VALUE Tom))) (> (PATH name) 3)))))"); expectParserSuccess("from Cat cat where description : 'Tom Cat'~3 ^ 4", expectedFrom + "(where (: (PATH description) (4 (FT_TERM (CONST_STRING_VALUE Tom Cat) 3))))))"); expectParserSuccess("from Cat cat where description : (:paramX)^7", expectedFrom + "(where (: (PATH description) (7 (FT_TERM paramX))))))"); expectParserSuccess("from Cat cat where description : 44^7", expectedFrom + "(where (: (PATH description) (7 (FT_TERM 44))))))"); } @Test public void testFtRange() { String expectedFrom = "(QUERY (QUERY_SPEC (SELECT_FROM (from (PERSISTER_SPACE (ENTITY_PERSISTER_REF Cat cat))) (SELECT (SELECT_LIST (SELECT_ITEM cat)))) "; expectParserSuccess("from Cat cat where description : ['aaa' to 'zzz']", expectedFrom + "(where (: (PATH description) (FT_RANGE [ (CONST_STRING_VALUE aaa) (CONST_STRING_VALUE zzz) ])))))"); expectParserSuccess("from Cat cat where description : ['aaa' 'zzz']", expectedFrom + "(where (: (PATH description) (FT_RANGE [ (CONST_STRING_VALUE aaa) (CONST_STRING_VALUE zzz) ])))))"); expectParserSuccess("from Cat cat where description : {'aaa' to 'zzz'}", expectedFrom + "(where (: (PATH description) (FT_RANGE { (CONST_STRING_VALUE aaa) (CONST_STRING_VALUE zzz) })))))"); expectParserSuccess("from Cat cat where description : [* *]", expectedFrom + "(where (: (PATH description) (FT_RANGE [ * * ])))))"); expectParserSuccess("from Cat cat where description : [* to 'xyz'}", expectedFrom + "(where (: (PATH description) (FT_RANGE [ * (CONST_STRING_VALUE xyz) })))))"); expectParserSuccess("from Cat cat where description : {* to 'xyz']", expectedFrom + "(where (: (PATH description) (FT_RANGE { * (CONST_STRING_VALUE xyz) ])))))"); expectParserSuccess("from Cat cat where description : {* to 'xyz'] ^ 8", expectedFrom + "(where (: (PATH description) (8 (FT_RANGE { * (CONST_STRING_VALUE xyz) ]))))))"); } @Test public void testFtFuzzyAndProximity() { String expectedFrom = "(QUERY (QUERY_SPEC (SELECT_FROM (from (PERSISTER_SPACE (ENTITY_PERSISTER_REF Cat cat))) (SELECT (SELECT_LIST (SELECT_ITEM cat)))) "; expectParserSuccess("from Cat cat where name : 'Tom' ~ 4", expectedFrom + "(where (: (PATH name) (FT_TERM (CONST_STRING_VALUE Tom) 4)))))"); expectParserSuccess("from Cat cat where name : 'Tom' ~ 4 and surname='Doe'", expectedFrom + "(where (and (: (PATH name) (FT_TERM (CONST_STRING_VALUE Tom) 4)) (= (PATH surname) (CONST_STRING_VALUE Doe))))))"); expectParserSuccess("from Cat cat where name : 'Tom'~", expectedFrom + "(where (: (PATH name) (FT_TERM (CONST_STRING_VALUE Tom) ~)))))"); } @Test public void testParamsNotAllowedInSelect() { expectParserFailure("select :paramX from Bar b"); } @Test public void testParamsNotAllowedInOrderBy() { expectParserFailure("from Bar order by :paramX"); } @Test public void testParamsNotAllowedInGroupBy() { expectParserFailure("select max(b.diameter) from Bar b group by :paramX"); } @Test public void testConstantBooleanInWhere() { expectParserSuccess("from example.EntityName e where true"); expectParserSuccess("from example.EntityName e where false"); expectParserSuccess("from example.EntityName e where false and e.name > 'a'"); expectParserSuccess("from example.EntityName e where true and e.name > 'a'"); } @Test public void testSimpleFrom_11() { expectParserSuccess("from example.EntityName e"); } @Test public void testConstantUsage_13() { expectParserSuccess("from example.EntityName where prop = example.ParserTest.CONSTANT"); } @Test public void testConstantUsage_14() { expectParserSuccess("from example.EntityName where prop = compProp.subProp"); } @Test public void testVariousPropertyReferences_16() { expectParserSuccess("from A a where b = 1"); } @Test public void testVariousPropertyReferences_17() { expectParserSuccess("from A a where a.b.c = 1"); } @Test public void testVariousPropertyReferences_18() { expectParserSuccess("from X x where y[1].z = 2"); } @Test public void testVariousPropertyReferences_19() { expectParserSuccess("from X x where x.y[1].z = 2"); } @Test public void testEntityNamePathWithKeyword_21() { expectParserSuccess("from example.Inner"); } @Test public void testWhereClauseIdentPrimaryWithEmbeddedKeyword_23() { expectParserSuccess("from example.Inner i where i.outer.inner.middle = 'xyz'"); } @Test public void testDynamicInstantiation_26() { expectParserSuccess("from Animal join a.mate"); } @Test public void testDynamicInstantiation_27() { expectParserSuccess("from Animal, aaa , dddd"); } @Test public void testDynamicInstantiation_28() { expectParserSuccess("from Animal, aaa join fetch dddd"); } @Test public void testListOrMapKeywordReference_30() { expectParserSuccess("select p from eg.NameList nl, eg.Person p where p.name = some elements(nl.names)"); } @Test public void testListOrMapKeywordReference_31() { expectParserSuccess("select p from eg.NameList list, eg.Person p where p.name = some elements(list.names)"); } @Test public void testListOrMapKeywordReference_32() { expectParserSuccess("select p from eg.NameList map, eg.Person p where p.name = some elements(map.names)"); } @Test public void testExplicitPropertyJoin_34() { expectParserSuccess("from eg.Cat as cat inner join fetch cat.mate as m fetch all properties left join fetch cat.kittens as k"); } @Test public void testSection_9_2_from_38() { expectParserSuccess("from eg.Cat"); } @Test public void testSection_9_2_from_39() { expectParserSuccess("from eg.Cat as cat"); } @Test public void testSection_9_2_from_40() { expectParserSuccess("from eg.Cat cat"); } @Test public void testSection_9_2_from_41() { expectParserSuccess("from Formula, Parameter"); } @Test public void testSection_9_2_from_42() { expectParserSuccess("from Formula as form, Parameter as param"); } @Test public void testSection_9_3_Associations_and_joins_44() { expectParserSuccess("from eg.Cat as cat inner join cat.mate as mate left outer join cat.kittens as kitten"); } @Test public void testSection_9_3_Associations_and_joins_45() { expectParserSuccess("from eg.Cat as cat left join cat.mate.kittens as kittens"); } @Test public void testSection_9_3_Associations_and_joins_46() { expectParserSuccess("from Formula form full join form.parameter param"); } @Test public void testSection_9_3_Associations_and_joins_47() { expectParserSuccess("from eg.Cat as cat join cat.mate as mate left join cat.kittens as kitten"); } @Test public void testSection_9_3_Associations_and_joins_48() { expectParserSuccess("from eg.Cat as cat inner join fetch cat.mate left join fetch cat.kittens"); } @Test public void testSection_9_4_Select_50() { expectParserSuccess("select mate from eg.Cat as cat inner join cat.mate as mate"); } @Test public void testSection_9_4_Select_51() { expectParserSuccess("select cat.mate from eg.Cat cat"); } @Test public void testSection_9_4_Select_52() { expectParserSuccess("select elements(cat.kittens) from eg.Cat cat"); } @Test public void testSection_9_4_Select_53() { expectParserSuccess("select cat.name from eg.DomesticCat cat where cat.name like 'fri%'"); } @Test public void testSection_9_4_Select_54() { expectParserSuccess("select cust.name.firstName from Customer as cust"); } @Test public void testSection_9_4_Select_55() { expectParserSuccess("select mother, offspr, mate.name from eg.DomesticCat as mother inner join mother.mate as mate left outer join mother.kittens as offspr"); } @Test public void testSection_9_5_Aggregate_functions_58() { expectParserSuccess("select avg(cat.weight), sum(cat.weight), max(cat.weight), count(cat) from eg.Cat cat"); } @Test public void testSection_9_5_Aggregate_functions_59() { expectParserSuccess("select cat, count( elements(cat.kittens) ) from eg.Cat cat group by cat"); } @Test public void testSection_9_5_Aggregate_functions_60() { expectParserSuccess("select distinct cat.name from eg.Cat cat"); } @Test public void testSection_9_5_Aggregate_functions_61() { expectParserSuccess("select count(distinct cat.name), count(cat) from eg.Cat cat"); } @Test public void testSection_9_6_Polymorphism_63() { expectParserSuccess("from java.lang.Object o"); } @Test public void testSection_9_6_Polymorphism_64() { expectParserSuccess("from eg.Named n, eg.Named m where n.name = m.name"); } @Test public void testSection_9_7_Where_66() { expectParserSuccess("from eg.Cat as cat where cat.name='Fritz'"); } @Test public void testSection_9_7_Where_67() { expectParserSuccess("select foo from eg.Foo foo, eg.Bar bar where foo.startDate = bar.date"); } @Test public void testSection_9_7_Where_68() { expectParserSuccess("from eg.Cat cat where cat.mate.name is not null"); } @Test public void testSection_9_7_Where_69() { expectParserSuccess("from eg.Cat cat, eg.Cat rival where cat.mate = rival.mate"); } @Test public void testSection_9_7_Where_70() { expectParserSuccess("select cat, mate from eg.Cat cat, eg.Cat mate where cat.mate = mate"); } @Test public void testSection_9_7_Where_71() { expectParserSuccess("from eg.Cat as cat where cat.id = 123"); } @Test public void testSection_9_7_Where_72() { expectParserSuccess("from eg.Cat as cat where cat.mate.id = 69"); } @Test public void testSection_9_7_Where_73() { expectParserSuccess("from bank.Person person where person.id.country = 'AU' and person.id.medicareNumber = 123456"); expectParserSuccess("from bank.Person person where person.id.country = 'AU' && person.id.medicareNumber = 123456"); } @Test public void testSection_9_7_Where_74() { expectParserSuccess("from bank.Account account where account.owner.id.country = 'AU' and account.owner.id.medicareNumber = 123456"); } @Test public void testSection_9_7_Where_75() { expectParserSuccess("from eg.Cat cat where cat.class = eg.DomesticCat"); } @Test public void testSection_9_7_Where_76() { expectParserSuccess("from eg.AuditLog log, eg.Payment payment where log.item.class = 'eg.Payment' and log.item.id = payment.id"); } @Test public void testSection_9_8_Expressions_75() { expectParserSuccess("from eg.DomesticCat cat where cat.name between 'A' and 'B'", "(QUERY (QUERY_SPEC (SELECT_FROM (from (PERSISTER_SPACE (ENTITY_PERSISTER_REF eg.DomesticCat cat))) (SELECT (SELECT_LIST (SELECT_ITEM cat)))) (where (between (PATH (. cat name)) (BETWEEN_LIST (CONST_STRING_VALUE A) (CONST_STRING_VALUE B))))))"); } @Test public void testSection_9_7_Where_77() { expectParserFailure("from eg.Cat as cat where cat.name='Fritz' blah"); } @Test public void testSection_9_7_Where_78() { expectParserFailure("from eg.Cat as cat where cat.name='Fritz' blah blah blah"); } @Test public void testSection_9_7_Where_79() { expectParserFailure("from eg.Cat as cat where cat.name='Fritz' order by cat.age blah"); } @Test public void testSection_9_7_Where_80() { expectParserFailure("from eg.Cat as cat where cat.name='Fritz' order by cat.age blah blah"); } @Test public void testSection_9_8_Expressions_82() { expectParserSuccess("from eg.DomesticCat cat where cat.name between 'A' and 'B'"); } @Test public void testSection_9_8_Expressions_83() { expectParserSuccess("from eg.DomesticCat cat where cat.name in ( 'Foo', 'Bar', 'Baz' )"); } @Test public void testSection_9_8_Expressions_84() { expectParserSuccess("from eg.DomesticCat cat where cat.name not between 'A' and 'B'"); } @Test public void testSection_9_8_Expressions_85() { expectParserSuccess("from eg.DomesticCat cat where cat.name not in ( 'Foo', 'Bar', 'Baz' )"); } @Test public void testSection_9_8_Expressions_86() { expectParserSuccess("from eg.Cat cat where cat.kittens.size > 0"); } @Test public void testSection_9_8_Expressions_87() { expectParserSuccess("from eg.Cat cat where size(cat.kittens) > 0"); } @Test public void testSection_9_8_Expressions_88() { expectParserSuccess("from Order order where maxindex(order.items) > 100"); } @Test public void testSection_9_8_Expressions_89() { expectParserSuccess("from Order order where minelement(order.items) > 10000"); } @Test public void testSection_9_8_Expressions_90() { expectParserSuccess("from Order ord where maxindex(ord.items) > 100"); } @Test public void testSection_9_8_Expressions_91() { expectParserSuccess("from Order ord where minelement(ord.items) > 10000"); } @Test public void testSection_9_8_Expressions_92() { expectParserSuccess("select mother from eg.Cat as mother, eg.Cat as kit where kit in elements(foo.kittens)"); } @Test public void testSection_9_8_Expressions_93() { expectParserSuccess("select p from eg.NameList list, eg.Person p where p.name = some elements(list.names)"); } @Test public void testSection_9_8_Expressions_94() { expectParserSuccess("from eg.Cat cat where exists elements(cat.kittens)"); } @Test public void testSection_9_8_Expressions_95() { expectParserSuccess("from eg.Player p where 3 > all elements(p.scores)"); } @Test public void testSection_9_8_Expressions_96() { expectParserSuccess("from eg.Show show where 'fizard' in indices(show.acts)"); } @Test public void testSection_9_8_Expressions_97() { expectParserSuccess("from Order order where order.items[0].id = 1234"); } @Test public void testSection_9_8_Expressions_98() { expectParserSuccess("select person from Person person, Calendar calendar where calendar.holidays['national day'] = person.birthDay and person.nationality.calendar = calendar"); } @Test public void testSection_9_8_Expressions_99() { expectParserSuccess("select item from Item item, Order order where order.items[ order.deliveredItemIndices[0] ] = item and order.id = 11"); } @Test public void testSection_9_8_Expressions_100() { expectParserSuccess("select item from Item item, Order order where order.items[ maxindex(order.items) ] = item and order.id = 11"); } @Test public void testSection_9_8_Expressions_101() { expectParserSuccess("from Order ord where ord.items[0].id = 1234"); } @Test public void testSection_9_8_Expressions_102() { expectParserSuccess("select item from Item item, Order ord where ord.items[ ord.deliveredItemIndices[0] ] = item and ord.id = 11"); } @Test public void testSection_9_8_Expressions_103() { expectParserSuccess("select item from Item item, Order ord where ord.items[ maxindex(ord.items) ] = item and ord.id = 11"); } @Test public void testSection_9_8_Expressions_104() { expectParserSuccess("select item from Item item, Order ord where ord.items[ size(ord.items) ] = item"); } @Test public void testSection_9_8_Expressions_106() { expectParserSuccess("select cust from Product prod, Store store inner join store.customers cust where prod.name = 'widget' and store.location.name in ( 'Melbourne', 'Sydney' ) and prod = all elements(cust.currentOrder.lineItems)"); } @Test public void testDocoExamples99_108() { expectParserSuccess("from eg.DomesticCat cat order by cat.name asc, cat.weight desc, cat.birthdate"); } @Test public void testDocoExamples910_110() { expectParserSuccess("select cat.color, sum(cat.weight), count(cat) from eg.Cat cat group by cat.color"); } @Test public void testDocoExamples910_111() { expectParserSuccess("select foo.id, avg( elements(foo.names) ), max( indices(foo.names) ) from eg.Foo foo group by foo.id"); } @Test public void testDocoExamples910_112() { expectParserSuccess("select cat.color, sum(cat.weight), count(cat) from eg.Cat cat group by cat.color having cat.color in (eg.Color.TABBY, eg.Color.BLACK)"); } @Test public void testDocoExamples910_113() { expectParserSuccess("select cat from eg.Cat cat join cat.kittens kitten group by cat having avg(kitten.weight) > 100 order by count(kitten) asc, sum(kitten.weight) desc"); } @Test public void testDocoExamples912_133() { expectParserSuccess("select ord.id, sum(price.amount), count(item)" + " from Order as ord join ord.lineItems as item join item.product as product," + " Catalog as catalog join catalog.prices as price" + " where ord.paid = false and ord.customer = :customer" + " and price.product = product and catalog = :currentCatalog" + " group by ord having sum(price.amount) > :minAmount" + " order by sum(price.amount) desc"); } @Test public void testDocoExamples912_155() { expectParserSuccess("select count(payment), status.name " + " from Payment as payment" + " join payment.currentStatus as status" + " where payment.status.name <> PaymentStatus.AWAITING_APPROVAL" + " or payment.statusChanges[ maxIndex(payment.statusChanges) ].user <> :currentUser" + " group by status.name, status.sortOrder" + " order by status.sortOrder"); } @Test public void testDocoExamples912_162() { expectParserSuccess("select account, payment" + " from Account as account" + " left outer join account.payments as payment" + " where :currentUser in elements(account.holder.users)" + " and PaymentStatus.UNPAID = isNull(payment.currentStatus.name, PaymentStatus.UNPAID)" + " order by account.type.sortOrder, account.accountNumber, payment.dueDate"); } @Test public void testDocoExamples912_168() { expectParserSuccess("select account, payment" + " from Account as account" + " join account.holder.users as user" + " left outer join account.payments as payment" + " where :currentUser = user" + " and PaymentStatus.UNPAID = isNull(payment.currentStatus.name, PaymentStatus.UNPAID)" + " order by account.type.sortOrder, account.accountNumber, payment.dueDate"); } @Test public void testExamples1_177() { expectParserSuccess("select s.name, sysdate, trunc(s.pay), round(s.pay) from Simple s"); } @Test public void testExamples1_178() { expectParserSuccess("select abs(round(s.pay)) from Simple s"); } @Test public void testMultipleActualParameters_181() { expectParserSuccess("select round(s.pay, 2) from s"); } @Test public void testMultipleActualParameters_181_() { expectParserFailure("select round(, s.pay) from s"); } @Test public void testMultipleActualParameters_181__() { expectParserSuccess("select round() from s"); } @Test public void testMultipleFromClasses_183() { expectParserSuccess("from eg.mypackage.Cat qat, com.toadstool.Foo f"); } @Test public void testMultipleFromClasses_184() { expectParserSuccess("from eg.mypackage.Cat qat, org.jabberwocky.Dipstick"); } @Test public void testFromWithJoin_186() { expectParserSuccess("from eg.mypackage.Cat qat, com.toadstool.Foo f join net.sf.blurb.Blurb"); } @Test public void testFromWithJoin_187() { expectParserSuccess("from eg.mypackage.Cat qat left join com.multijoin.JoinORama , com.toadstool.Foo f join net.sf.blurb.Blurb"); } @Test public void testSelect_189() { expectParserSuccess("select f from eg.mypackage.Cat qat, com.toadstool.Foo f join net.sf.blurb.Blurb"); } @Test public void testSelect_189_() { expectParserFailure("from eg.mypackage.Cat order by :what"); } @Test public void testSelect_190() { expectParserSuccess("select distinct bar from eg.mypackage.Cat qat left join com.multijoin.JoinORama as bar, com.toadstool.Foo f join net.sf.blurb.Blurb"); } @Test public void testSelect_191() { expectParserSuccess("select count(*) from eg.mypackage.Cat qat"); } @Test public void testSelect_192() { expectParserSuccess("select avg(qat.weight) from eg.mypackage.Cat qat"); } @Test public void testWhere_194() { expectParserSuccess("from eg.mypackage.Cat qat where qat.name like '%fluffy%' or qat.toes > 5"); } @Test public void testWhere_195() { expectParserSuccess("from eg.mypackage.Cat qat where not qat.name like '%fluffy%' or qat.toes > 5"); } @Test public void testWhere_196() { expectParserSuccess("from eg.mypackage.Cat qat where not qat.name not like '%fluffy%'"); } @Test public void testWhere_197() { expectParserSuccess("from eg.mypackage.Cat qat where qat.name in ('crater','bean','fluffy')"); } @Test public void testWhere_198() { expectParserSuccess("from eg.mypackage.Cat qat where qat.name not in ('crater','bean','fluffy')"); } @Test public void testGroupBy_200() { expectParserSuccess("from eg.mypackage.Cat qat group by qat.breed"); } @Test public void testGroupBy_201() { expectParserSuccess("from eg.mypackage.Cat qat group by qat.breed, qat.eyecolor"); } @Test public void testOrderBy_203() { expectParserSuccess("from eg.mypackage.Cat qat order by avg(qat.toes)"); } @Test public void testDoubleLiteral_206() { expectParserSuccess("from eg.Cat as tinycat where fatcat.weight < 3.1415"); } @Test public void testDoubleLiteral_207() { expectParserSuccess("from eg.Cat as enormouscat where fatcat.weight > 3.1415e3"); } @Test public void testInNotIn_212() { expectParserSuccess("from foo where foo.bar in ('a' , 'b', 'c')"); } @Test public void testInNotIn_213() { expectParserSuccess("from foo where foo.bar not in ('a' , 'b', 'c')"); } @Test public void testUnitTestHql_223() { expectParserSuccess("select foo.id from example.Foo foo where foo.joinedProp = 'foo'"); } @Test public void testUnitTestHql_224() { expectParserSuccess("from example.Foo foo inner join fetch foo.foo"); } @Test public void testUnitTestHql_225() { expectParserSuccess("from example.Baz baz left outer join fetch baz.fooToGlarch"); } @Test public void testUnitTestHql_231() { expectParserSuccess("from example.Foo as foo where foo.component.glarch.name is not null"); } @Test public void testUnitTestHql_232() { expectParserSuccess("from example.Foo as foo left outer join foo.component.glarch as glarch where glarch.name = 'foo'"); } @Test public void testUnitTestHql_233() { expectParserSuccess("from example.Foo"); } @Test public void testUnitTestHql_234() { expectParserSuccess("from example.Foo foo left outer join foo.foo"); } @Test public void testUnitTestHql_235() { expectParserSuccess("from example.Foo, example.Bar"); } @Test public void testUnitTestHql_236() { expectParserSuccess("from example.Baz baz left join baz.fooToGlarch, example.Bar bar join bar.foo"); } @Test public void testUnitTestHql_237() { expectParserSuccess("from example.Baz baz left join baz.fooToGlarch join baz.fooSet"); } @Test public void testUnitTestHql_238() { expectParserSuccess("from example.Baz baz left join baz.fooToGlarch join fetch baz.fooSet foo left join fetch foo.foo"); } @Test public void testUnitTestHql_326() { expectParserSuccess("select index(date) from example.Baz baz join baz.stringDateMap as date"); } @Test public void testUnitTestHql_327() { expectParserSuccess("select index(date) from example.Baz baz join baz.stringDateMap date"); } @Test public void testUnitTestHql_329() { expectParserSuccess("from example.Baz baz inner join baz.collectionComponent.nested.foos foo where foo.string is null"); } @Test public void testUnitTestHql_331() { expectParserSuccess("from example.Baz baz where 'a' in elements(baz.collectionComponent.nested.foos) and 1.0 in elements(baz.collectionComponent.nested.floats)"); } @Test public void testUnitTestHql_332() { expectParserSuccess("from example.Foo foo join foo.foo where foo.foo in ('1','2','3')"); } @Test public void testUnitTestHql_333() { expectParserSuccess("select foo.foo from example.Foo foo where foo.foo in ('1','2','3')"); } @Test public void testUnitTestHql_334() { expectParserSuccess("select foo.foo.string from example.Foo foo where foo.foo in ('1','2','3')"); } @Test public void testUnitTestHql_335() { expectParserSuccess("select foo.foo.string from example.Foo foo where foo.foo.string in ('1','2','3')"); } @Test public void testUnitTestHql_336() { expectParserSuccess("select foo.foo.long from example.Foo foo where foo.foo.string in ('1','2','3')"); } @Test public void testUnitTestHql_337() { expectParserSuccess("select count(*) from example.Foo foo where foo.foo.string in ('1','2','3') or foo.foo.long in (1,2,3)"); } @Test public void testUnitTestHql_338() { expectParserSuccess("select count(*) from example.Foo foo where foo.foo.string in ('1','2','3') group by foo.foo.long"); } @Test public void testUnitTestHql_339() { expectParserSuccess("from example.Foo foo1 left join foo1.foo foo2 left join foo2.foo where foo1.string is not null"); } @Test public void testUnitTestHql_340() { expectParserSuccess("from example.Foo foo1 left join foo1.foo.foo where foo1.string is not null"); } @Test public void testUnitTestHql_341() { expectParserSuccess("from example.Foo foo1 left join foo1.foo foo2 left join foo1.foo.foo foo3 where foo1.string is not null"); } @Test public void testUnitTestHql_342() { expectParserSuccess("select foo.formula from example.Foo foo where foo.formula > 0"); } @Test public void testUnitTestHql_343() { expectParserSuccess("from example.Foo as foo join foo.foo as foo2 where foo2.id >'a' or foo2.id <'a'"); } @Test public void testUnitTestHql_344() { expectParserSuccess("from example.Holder"); } @Test public void testUnitTestHql_345() { expectParserSuccess("from example.Baz baz left outer join fetch baz.manyToAny"); } @Test public void testUnitTestHql_346() { expectParserSuccess("from example.Baz baz join baz.manyToAny"); } @Test public void testUnitTestHql_347() { expectParserSuccess("select baz from example.Baz baz join baz.manyToAny a where index(a) = 0"); } @Test public void testUnitTestHql_348() { expectParserSuccess("select bar from example.Bar bar where bar.baz.stringDateMap['now'] is not null"); } @Test public void testUnitTestHql_349() { expectParserSuccess("select bar from example.Bar bar join bar.baaz b where b.stringDateMap['big bang'] < b.stringDateMap['now'] and b.stringDateMap['now'] is not null"); } @Test public void testUnitTestHql_350() { expectParserSuccess("select bar from example.Bar bar where bar.baz.stringDateMap['big bang'] < bar.baz.stringDateMap['now'] and bar.baz.stringDateMap['now'] is not null"); } @Test public void testUnitTestHql_351() { expectParserSuccess("select foo.string, foo.component, foo.id from example.Bar foo"); } @Test public void testUnitTestHql_352() { expectParserSuccess("select elements(baz.components) from example.Baz baz"); } @Test public void testUnitTestHql_353() { expectParserSuccess("select bc.name from example.Baz baz join baz.components bc"); } @Test public void testUnitTestHql_354() { expectParserSuccess("from example.Foo foo where foo.integer < 10 order by foo.string"); } @Test public void testUnitTestHql_355() { expectParserSuccess("from example.Fee"); } @Test public void testUnitTestHql_356() { expectParserSuccess("from example.Holder h join h.otherHolder oh where h.otherHolder.name = 'bar'"); } @Test public void testUnitTestHql_357() { expectParserSuccess("from example.Baz baz join baz.fooSet foo join foo.foo.foo foo2 where foo2.string = 'foo'"); } @Test public void testUnitTestHql_358() { expectParserSuccess("from example.Baz baz join baz.fooArray foo join foo.foo.foo foo2 where foo2.string = 'foo'"); } @Test public void testUnitTestHql_359() { expectParserSuccess("from example.Baz baz join baz.stringDateMap date where index(date) = 'foo'"); } @Test public void testUnitTestHql_360() { expectParserSuccess("from example.Baz baz join baz.topGlarchez g where index(g) = 'A'"); } @Test public void testUnitTestHql_361() { expectParserSuccess("select index(g) from example.Baz baz join baz.topGlarchez g"); } @Test public void testUnitTestHql_362() { expectParserSuccess("from example.Baz baz left join baz.stringSet"); } @Test public void testUnitTestHql_363() { expectParserSuccess("from example.Baz baz join baz.stringSet str where str='foo'"); } @Test public void testUnitTestHql_364() { expectParserSuccess("from example.Baz baz left join fetch baz.stringSet"); } @Test public void testUnitTestHql_365() { expectParserSuccess("from example.Baz baz join baz.stringSet string where string='foo'"); } @Test public void testUnitTestHql_366() { expectParserSuccess("from example.Baz baz inner join baz.components comp where comp.name='foo'"); } @Test public void testUnitTestHql_367() { expectParserSuccess("from example.Glarch g inner join g.fooComponents comp where comp.fee is not null"); } @Test public void testUnitTestHql_368() { expectParserSuccess("from example.Glarch g inner join g.fooComponents comp join comp.fee fee where fee.count > 0"); } @Test public void testUnitTestHql_369() { expectParserSuccess("from example.Glarch g inner join g.fooComponents comp where comp.fee.count is not null"); } @Test public void testUnitTestHql_370() { expectParserSuccess("from example.Baz baz left join fetch baz.fooBag"); } @Test public void testUnitTestHql_371() { expectParserSuccess("from example.Glarch"); } @Test public void testUnitTestHql_372() { expectParserSuccess("from example.Baz baz left join fetch baz.sortablez order by baz.name asc"); } @Test public void testUnitTestHql_373() { expectParserSuccess("from example.Baz baz order by baz.name asc"); } @Test public void testUnitTestHql_374() { expectParserSuccess("from example.Foo foo, example.Baz baz left join fetch baz.fees"); } @Test public void testUnitTestHql_375() { expectParserSuccess("from example.Foo foo, example.Bar bar"); } @Test public void testUnitTestHql_376() { expectParserSuccess("from example.Foo foo"); } @Test public void testUnitTestHql_377() { expectParserSuccess("from example.Foo foo, example.Bar bar, example.Bar bar2"); } @Test public void testUnitTestHql_378() { expectParserSuccess("from example.X x"); } @Test public void testUnitTestHql_379() { expectParserSuccess("select distinct foo from example.Foo foo"); } @Test public void testUnitTestHql_380() { expectParserSuccess("from example.Glarch g where g.multiple.glarch=g and g.multiple.count=12"); } @Test public void testUnitTestHql_381() { expectParserSuccess("from example.Bar bar left join bar.baz baz left join baz.cascadingBars b where bar.name like 'Bar %'"); } @Test public void testUnitTestHql_382() { expectParserSuccess("select bar, b from example.Bar bar left join bar.baz baz left join baz.cascadingBars b where bar.name like 'Bar%'"); } @Test public void testUnitTestHql_383() { expectParserSuccess("select bar, b from example.Bar bar left join bar.baz baz left join baz.cascadingBars b where ( bar.name in (:nameList0_, :nameList1_, :nameList2_) or bar.name in (:nameList0_, :nameList1_, :nameList2_) ) and bar.string = :stringVal"); } @Test public void testUnitTestHql_384() { expectParserSuccess("select bar, b from example.Bar bar inner join bar.baz baz inner join baz.cascadingBars b where bar.name like 'Bar%'"); } @Test public void testUnitTestHql_385() { expectParserSuccess("select bar, b from example.Bar bar left join bar.baz baz left join baz.cascadingBars b where bar.name like :name and b.name like :name"); } @Test public void testUnitTestHql_386() { expectParserSuccess("select bar from example.Bar as bar where bar.x > ? or bar.short = 1 or bar.string = 'ff ? bb'"); } @Test public void testUnitTestHql_387() { expectParserSuccess("select bar from example.Bar as bar where bar.string = ' ? ' or bar.string = '?'"); expectParserSuccess("select bar from example.Bar as bar where bar.string = ' ? ' || bar.string = '?'"); } @Test public void testUnitTestHql_388() { expectParserSuccess("from example.Baz baz, baz.fooArray foo"); } @Test public void testUnitTestHql_398() { expectParserSuccess("select max( elements(bar.baz.fooArray) ) from example.Bar as bar"); } @Test public void testUnitTestHql_399() { expectParserSuccess("from example.Baz baz left join baz.fooToGlarch join fetch baz.fooArray foo left join fetch foo.foo"); } @Test public void testUnitTestHql_400() { expectParserSuccess("select baz.name from example.Bar bar inner join bar.baz baz inner join baz.fooSet foo where baz.name = bar.string"); } @Test public void testUnitTestHql_401() { expectParserSuccess("SELECT baz.name FROM example.Bar AS bar INNER JOIN bar.baz AS baz INNER JOIN baz.fooSet AS foo WHERE baz.name = bar.string"); } @Test public void testUnitTestHql_402() { expectParserSuccess("select baz.name from example.Bar bar join bar.baz baz left outer join baz.fooSet foo where baz.name = bar.string"); } @Test public void testUnitTestHql_403() { expectParserSuccess("select baz.name from example.Bar bar, bar.baz baz, baz.fooSet foo where baz.name = bar.string"); } @Test public void testUnitTestHql_404() { expectParserSuccess("SELECT baz.name FROM example.Bar AS bar, bar.baz AS baz, baz.fooSet AS foo WHERE baz.name = bar.string"); } @Test public void testUnitTestHql_405() { expectParserSuccess("select baz.name from example.Bar bar left join bar.baz baz left join baz.fooSet foo where baz.name = bar.string"); } @Test public void testUnitTestHql_406() { expectParserSuccess("select foo.string from example.Bar bar left join bar.baz.fooSet foo where bar.string = foo.string"); } @Test public void testUnitTestHql_407() { expectParserSuccess("select baz.name from example.Bar bar left join bar.baz baz left join baz.fooArray foo where baz.name = bar.string"); } @Test public void testUnitTestHql_408() { expectParserSuccess("select foo.string from example.Bar bar left join bar.baz.fooArray foo where bar.string = foo.string"); } @Test public void testUnitTestHql_413() { expectParserSuccess("from example.Bar bar join bar.baz.fooArray foo"); } @Test public void testUnitTestHql_426() { expectParserSuccess("from example.Foo foo where foo.component.glarch.id is not null"); } @Test public void testUnitTestHql_430() { expectParserSuccess("select count(*) from example.Bar"); } @Test public void testUnitTestHql_459() { expectParserSuccess("from example.Foo foo where foo.custom.s1 = 'one'"); } @Test public void testUnitTestHql_466() { expectParserSuccess("from example.Bar bar where bar.object.id = ? and bar.object.class = ?"); } @Test public void testUnitTestHql_467() { expectParserSuccess("select one from example.One one, example.Bar bar where bar.object.id = one.id and bar.object.class = 'O'"); } @Test public void testUnitTestHql_469() { expectParserSuccess("from example.Bar bar"); } @Test public void testUnitTestHql_470() { expectParserSuccess("From example.Bar bar"); } @Test public void testUnitTestHql_471() { expectParserSuccess("From example.Foo foo"); } @Test public void testUnitTestHql_475() { expectParserSuccess("from example.Outer o where o.id.detailId = ?"); } @Test public void testUnitTestHql_476() { expectParserSuccess("from example.Outer o where o.id.master.id.sup.dudu is not null"); } @Test public void testUnitTestHql_477() { expectParserSuccess("from example.Outer o where o.id.master.id.sup.id.akey is not null"); } @Test public void testUnitTestHql_478() { expectParserSuccess("select o.id.master.id.sup.dudu from example.Outer o where o.id.master.id.sup.dudu is not null"); } @Test public void testUnitTestHql_479() { expectParserSuccess("select o.id.master.id.sup.id.akey from example.Outer o where o.id.master.id.sup.id.akey is not null"); } @Test public void testUnitTestHql_480() { expectParserSuccess("from example.Outer o where o.id.master.bla = ''"); } @Test public void testUnitTestHql_481() { expectParserSuccess("from example.Outer o where o.id.master.id.one = ''"); } @Test public void testUnitTestHql_482() { expectParserSuccess("from example.Inner inn where inn.id.bkey is not null and inn.backOut.id.master.id.sup.id.akey > 'a'"); } @Test public void testUnitTestHql_483() { expectParserSuccess("from example.Outer as o left join o.id.master m left join m.id.sup where o.bubu is not null"); } @Test public void testUnitTestHql_484() { expectParserSuccess("from example.Outer as o left join o.id.master.id.sup s where o.bubu is not null"); } @Test public void testUnitTestHql_485() { expectParserSuccess("from example.Outer as o left join o.id.master m left join o.id.master.id.sup s where o.bubu is not null"); } @Test public void testUnitTestHql_491() { expectParserSuccess("from example.Category cat where cat.name='new foo'"); } @Test public void testUnitTestHql_492() { expectParserSuccess("from example.Category cat where cat.name='new sub'"); } @Test public void testUnitTestHql_493() { expectParserSuccess("from example.Up up order by up.id2 asc"); } @Test public void testUnitTestHql_494() { expectParserSuccess("from example.Down down"); } @Test public void testUnitTestHql_495() { expectParserSuccess("from example.Up up"); } @Test public void testUnitTestHql_511() { expectParserSuccess("select c from example.Container c where c.manyToMany[ c.oneToMany[0].count ].name = 's'"); } @Test public void testUnitTestHql_512() { expectParserSuccess("select count(comp.name) from example.Container c join c.components comp"); } @Test public void testUnitTestHql_513() { expectParserSuccess("from example.Parent p left join fetch p.child"); } @Test public void testUnitTestHql_514() { expectParserSuccess("from example.Parent p join p.child c where c.x > 0"); } @Test public void testUnitTestHql_515() { expectParserSuccess("from example.Child c join c.parent p where p.x > 0"); } @Test public void testUnitTestHql_516() { expectParserSuccess("from example.Child"); } @Test public void testUnitTestHql_517() { expectParserSuccess("from example.MoreStuff"); } @Test public void testUnitTestHql_518() { expectParserSuccess("from example.Many"); } @Test public void testUnitTestHql_519() { expectParserSuccess("from example.Qux"); } @Test public void testUnitTestHql_520() { expectParserSuccess("from example.Fumm"); } @Test public void testUnitTestHql_521() { expectParserSuccess("from example.Parent"); } @Test public void testUnitTestHql_522() { expectParserSuccess("from example.Simple"); } @Test public void testUnitTestHql_523() { expectParserSuccess("from example.Part"); } @Test public void testUnitTestHql_524() { expectParserSuccess("from example.Baz"); } @Test public void testUnitTestHql_525() { expectParserSuccess("from example.Vetoer"); } @Test public void testUnitTestHql_526() { expectParserSuccess("from example.Sortable"); } @Test public void testUnitTestHql_527() { expectParserSuccess("from example.Contained"); } @Test public void testUnitTestHql_528() { expectParserSuccess("from example.Circular"); } @Test public void testUnitTestHql_529() { expectParserSuccess("from example.Stuff"); } @Test public void testUnitTestHql_530() { expectParserSuccess("from example.Immutable"); } @Test public void testUnitTestHql_531() { expectParserSuccess("from example.Container"); } @Test public void testUnitTestHql_532() { expectParserSuccess("from example.One"); } @Test public void testUnitTestHql_533() { expectParserSuccess("from example.Fo"); } @Test public void testUnitTestHql_534() { expectParserSuccess("from example.Glarch"); } @Test public void testUnitTestHql_535() { expectParserSuccess("from example.Fum"); } @Test public void testUnitTestHql_536() { expectParserSuccess("from example.Glarch g"); } @Test public void testUnitTestHql_537() { expectParserSuccess("from example.Baz baz join baz.parts"); } @Test public void testUnitTestHql_539() { expectParserSuccess("from example.Parent p join p.child c where p.count=66"); } @Test public void testUnitTestHql_544() { expectParserSuccess("select count(*) from example.Container as c join c.components as ce join ce.simple as s where ce.name='foo'"); } @Test public void testUnitTestHql_545() { expectParserSuccess("select c, s from example.Container as c join c.components as ce join ce.simple as s where ce.name='foo'"); } @Test public void testUnitTestHql_555() { expectParserSuccess("from example.E e join e.reverse as b where b.count=1"); } @Test public void testUnitTestHql_556() { expectParserSuccess("from example.E e join e.as as b where b.count=1"); } @Test public void testUnitTestHql_557() { expectParserSuccess("from example.B"); } @Test public void testUnitTestHql_558() { expectParserSuccess("from example.C1"); } @Test public void testUnitTestHql_559() { expectParserSuccess("from example.C2"); } @Test public void testUnitTestHql_560() { expectParserSuccess("from example.E e, example.A a where e.reverse = a.forward and a = ?"); } @Test public void testUnitTestHql_561() { expectParserSuccess("from example.E e join fetch e.reverse"); } @Test public void testUnitTestHql_562() { expectParserSuccess("from example.E e"); } @Test public void testUnitTestHql_569() { expectParserSuccess("from example.Simple s where s.name=?"); } @Test public void testUnitTestHql_570() { expectParserSuccess("from example.Simple s where s.name=:name"); } @Test public void testUnitTestHql_587() { expectParserSuccess("from example.Simple s"); } @Test public void testUnitTestHql_588() { expectParserSuccess("from example.Assignable"); } @Test public void testUnitTestHql_589() { expectParserSuccess("from example.Category"); } @Test public void testUnitTestHql_590() { expectParserSuccess("from example.A"); } @Test public void testUnitTestHql_593() { expectParserSuccess("from example.Po po, example.Lower low where low.mypo = po"); } @Test public void testUnitTestHql_594() { expectParserSuccess("from example.Po po join po.set as sm where sm.amount > 0"); } @Test public void testUnitTestHql_595() { expectParserSuccess("from example.Po po join po.top as low where low.foo = 'po'"); } @Test public void testUnitTestHql_596() { expectParserSuccess("from example.SubMulti sm join sm.children smc where smc.name > 'a'"); } @Test public void testUnitTestHql_597() { expectParserSuccess("select s, ya from example.Lower s join s.yetanother ya"); } @Test public void testUnitTestHql_598() { expectParserSuccess("from example.Lower s1 join s1.bag s2"); } @Test public void testUnitTestHql_599() { expectParserSuccess("from example.Lower s1 left join s1.bag s2"); } @Test public void testUnitTestHql_600() { expectParserSuccess("select s, a from example.Lower s join s.another a"); } @Test public void testUnitTestHql_601() { expectParserSuccess("select s, a from example.Lower s left join s.another a"); } @Test public void testUnitTestHql_602() { expectParserSuccess("from example.Top s, example.Lower ls"); } @Test public void testUnitTestHql_603() { expectParserSuccess("from example.Lower ls join ls.set s where s.name > 'a'"); } @Test public void testUnitTestHql_604() { expectParserSuccess("from example.Po po join po.list sm where sm.name > 'a'"); } @Test public void testUnitTestHql_605() { expectParserSuccess("from example.Lower ls inner join ls.another s where s.name is not null"); } @Test public void testUnitTestHql_606() { expectParserSuccess("from example.Lower ls where ls.other.another.name is not null"); } @Test public void testUnitTestHql_607() { expectParserSuccess("from example.Multi m where m.derived like 'F%'"); } @Test public void testUnitTestHql_608() { expectParserSuccess("from example.SubMulti m where m.derived like 'F%'"); } @Test public void testUnitTestHql_609() { expectParserSuccess("select s from example.SubMulti as sm join sm.children as s where s.amount>-1 and s.name is null"); } @Test public void testUnitTestHql_610() { expectParserSuccess("select elements(sm.children) from example.SubMulti as sm"); } @Test public void testUnitTestHql_611() { expectParserSuccess("select distinct sm from example.SubMulti as sm join sm.children as s where s.amount>-1 and s.name is null"); } @Test public void testUnitTestHql_638() { expectParserSuccess("from ChildMap cm where cm.parent is not null"); } @Test public void testUnitTestHql_639() { expectParserSuccess("from ParentMap cm where cm.child is not null"); } @Test public void testUnitTestHql_640() { expectParserSuccess("from example.Componentizable"); } @Test public void testUnnamedParameter_642() { expectParserSuccess("select foo, bar from example.Foo foo left outer join foo.foo bar where foo = ?"); } @Test public void testInElements_645() { expectParserSuccess("from example.Bar bar, foo in elements(bar.baz.fooArray)"); } @Test public void testDotElements_650() { expectParserSuccess("from example.Baz baz where 'b' in elements(baz.collectionComponent.nested.foos) and 1.0 in elements(baz.collectionComponent.nested.floats)"); } @Test public void testNot_652() { expectParserSuccess("from eg.Cat cat where not ( cat.kittens.size < 1 )"); } @Test public void testNot_653() { expectParserSuccess("from eg.Cat cat where not ( cat.kittens.size > 1 )"); } @Test public void testNot_654() { expectParserSuccess("from eg.Cat cat where not ( cat.kittens.size >= 1 )"); } @Test public void testNot_655() { expectParserSuccess("from eg.Cat cat where not ( cat.kittens.size <= 1 )"); } @Test public void testNot_656() { expectParserSuccess("from eg.DomesticCat cat where not ( cat.name between 'A' and 'B' )"); } @Test public void testNot_657() { expectParserSuccess("from eg.DomesticCat cat where not ( cat.name not between 'A' and 'B' )"); } @Test public void testNot_658() { expectParserSuccess("from eg.Cat cat where not ( not cat.kittens.size <= 1 )"); } @Test public void testNot_659() { expectParserSuccess("from eg.Cat cat where not not ( not cat.kittens.size <= 1 )"); } @Test public void testOtherSyntax_661() { expectParserSuccess("select bar from example.Bar bar order by ((bar.x))"); } @Test public void testOtherSyntax_662() { expectParserSuccess("from example.Bar bar, foo in elements(bar.baz.fooSet)"); } @Test public void testOtherSyntax_664() { expectParserSuccess("from example.Inner _inner join _inner.middles middle"); } @Test public void testEjbqlExtensions_675() { expectParserSuccess("select object(a) from Animal a where a.mother member of a.offspring"); } @Test public void testEjbqlExtensions_676() { expectParserSuccess("select object(a) from Animal a where a.offspring is empty"); } @Test public void testKeywordInPath_680() { expectParserSuccess("from Customer c where c.order.status = 'argh'"); } @Test public void testKeywordInPath_681() { expectParserSuccess("from Customer c where c.order.count > 3"); } @Test public void testKeywordInPath_682() { expectParserSuccess("select c.where from Customer c where c.order.count > 3"); } @Test public void testKeywordInPath_683() { expectParserSuccess("from Interval i where i.end <:end"); } @Test public void testKeywordInPath_684() { expectParserSuccess("from Letter l where l.case = :case"); } @Test public void testPathologicalKeywordAsIdentifier_686() { expectParserSuccess("from Order order"); } @Test public void testPathologicalKeywordAsIdentifier_687() { expectParserSuccess("from Order order join order.group"); } @Test public void testPathologicalKeywordAsIdentifier_688() { expectParserSuccess("from X x order by x.group.by.from"); } @Test public void testPathologicalKeywordAsIdentifier_689() { expectParserSuccess("from Order x order by x.order.group.by.from"); } @Test public void testPathologicalKeywordAsIdentifier_690() { expectParserSuccess("select order.id from Order order"); } @Test public void testPathologicalKeywordAsIdentifier_691() { expectParserSuccess("select order from Order order"); } @Test public void testPathologicalKeywordAsIdentifier_692() { expectParserSuccess("from Order order where order.group.by.from is not null"); } @Test public void testPathologicalKeywordAsIdentifier_693() { expectParserSuccess("from Order order order by order.group.by.from"); } @Test public void testPathologicalKeywordAsIdentifier_694() { expectParserSuccess("from Group as group group by group.by.from"); } @Test public void testHHH354_696() { expectParserSuccess("from Foo f where f.full = 'yep'"); } @Test public void testWhereAsIdentifier_698() { expectParserSuccess("from where.Order"); } @Test public void testMultiByteCharacters_702() { expectParserSuccess("from User user where user.name like '%nn\u4e2dnn%'"); } @Test public void testHHH719_706() { expectParserSuccess("from Foo f order by com.fooco.SpecialFunction(f.id)"); } @Test public void testHHH1107_708() { expectParserSuccess("from Animal where zoo.address.street = '123 Bogus St.'"); } @Test public void testHHH1247_710() { expectParserSuccess("select distinct user.party from com.itf.iceclaims.domain.party.user.UserImpl user inner join user.party.$RelatedWorkgroups relatedWorkgroups where relatedWorkgroups.workgroup.id = :workgroup and relatedWorkgroups.effectiveTime.start <= :datesnow and relatedWorkgroups.effectiveTime.end > :dateenow "); } @Test public void testLineAndColumnNumber_712() { expectParserSuccess("from Foo f where f.name = 'fred'"); } @Test public void testLineAndColumnNumber_713() { expectParserSuccess("from Animal a where a.bodyWeight = ?1"); } @Test public void testLineAndColumnNumber_714() { expectParserSuccess("select object(m) from Model m"); } @Test public void testLineAndColumnNumber_715() { expectParserSuccess("select o from Animal a inner join a.offspring o"); } @Test public void testLineAndColumnNumber_716() { expectParserSuccess("select object(o) from Animal a, in(a.offspring) o"); } @Test public void testLineAndColumnNumber_717() { expectParserSuccess("from Animal a where not exists elements(a.offspring)"); } @Test public void testLineAndColumnNumber_719() { expectParserSuccess("select object(a) from Animal a where a.mother.father.offspring is not empty"); } @Test public void testLineAndColumnNumber_722() { expectParserSuccess("select object(a) from Animal a where a.mother not member of a.offspring"); } @Test public void testLineAndColumnNumber_723() { expectParserSuccess("select object(a) from Animal a where a.description = concat('1', concat('2','3'), '45')"); } @Test public void testLineAndColumnNumber_724() { expectParserSuccess("from Animal a where substring(a.description, 1, 3) = :p1"); } @Test public void testLineAndColumnNumber_725() { expectParserSuccess("select substring(a.description, 1, 3) from Animal a"); } @Test public void testLineAndColumnNumber_728() { expectParserSuccess("from Animal a where length(a.description) = :p1"); } @Test public void testLineAndColumnNumber_729() { expectParserSuccess("select length(a.description) from Animal a"); } @Test public void testLineAndColumnNumber_730() { expectParserSuccess("from Animal a where locate(a.description, 'abc', 2) = :p1"); } @Test public void testLineAndColumnNumber_731() { expectParserSuccess("select locate(a.description, :p1, 2) from Animal a"); } @Test public void testLineAndColumnNumber_742() { expectParserSuccess("select object(a) from Animal a where a.bodyWeight like '%a%'"); } @Test public void testLineAndColumnNumber_743() { expectParserSuccess("select object(a) from Animal a where a.bodyWeight not like '%a%'"); } @Test public void testLineAndColumnNumber_744() { expectParserSuccess("select object(a) from Animal a where a.bodyWeight like '%a%' escape '%'"); } @Test public void testLineAndColumnNumber_745() { expectParserFailure("from Human h where h.pregnant is true"); } @Test public void testLineAndColumnNumber_746() { expectParserSuccess("from Human h where h.pregnant = true"); } @Test public void testLineAndColumnNumber_747() { expectParserFailure("from Human h where h.pregnant is false"); } @Test public void testLineAndColumnNumber_748() { expectParserSuccess("from Human h where h.pregnant = false"); } @Test public void testLineAndColumnNumber_749() { expectParserFailure("from Human h where not(h.pregnant is true)"); } @Test public void testLineAndColumnNumber_750() { expectParserSuccess("from Human h where not( h.pregnant=true )"); } @Test public void testLineAndColumnNumber_754() { expectParserFailure("select * from Address a join Person p on a.pid = p.id, Person m join Address b on b.pid = m.id where p.mother = m.id and p.name like ?"); } @Test public void testHQLTestInvalidCollectionDereferencesFail_757() { expectParserSuccess("from Animal a where a.offspring.description = 'xyz'"); } @Test public void testHQLTestInvalidCollectionDereferencesFail_758() { expectParserSuccess("from Animal a where a.offspring.father.description = 'xyz'"); } @Test public void testHQLTestSubComponentReferences_760() { expectParserSuccess("select c.address.zip.code from ComponentContainer c"); } @Test public void testHQLTestSubComponentReferences_761() { expectParserSuccess("select c.address.zip from ComponentContainer c"); } @Test public void testHQLTestSubComponentReferences_762() { expectParserSuccess("select c.address from ComponentContainer c"); } @Test public void testHQLTestManyToAnyReferences_764() { expectParserSuccess("from PropertySet p where p.someSpecificProperty.id is not null"); } @Test public void testHQLTestManyToAnyReferences_765() { expectParserSuccess("from PropertySet p join p.generalProperties gp where gp.id is not null"); } @Test public void testHQLTestEmptyInListFailureExpected_770() { expectParserFailure("select a from Animal a where a.description in ()"); } @Test public void testHQLTestEmptyInListFailureExpected_771() { expectParserSuccess("select o.orderDate from Order o"); } @Test public void testHQLTestDateTimeArithmeticReturnTypesAndParameterGuessing_775() { expectParserSuccess("from Order o where o.orderDate > ?"); } @Test public void testHQLTestReturnMetadata_778() { expectParserSuccess("select a as animal from Animal a"); } @Test public void testHQLTestReturnMetadata_779() { expectParserSuccess("select o as entity from java.lang.Object o"); } @Test public void testHQLTestImplicitJoinsAlongWithCartesianProduct_781() { expectParserSuccess("select foo.foo from Foo foo, Foo foo2"); } @Test public void testHQLTestImplicitJoinsAlongWithCartesianProduct_782() { expectParserSuccess("select foo.foo.foo from Foo foo, Foo foo2"); } @Test public void testHQLTestFetchOrderBy_790() { expectParserSuccess("from Animal a left outer join fetch a.offspring where a.mother.id = :mid order by a.description"); } @Test public void testHQLTestCollectionOrderBy_792() { expectParserSuccess("from Animal a join a.offspring o order by a.description"); } @Test public void testHQLTestCollectionOrderBy_793() { expectParserSuccess("from Animal a join fetch a.offspring order by a.description"); } @Test public void testHQLTestCollectionOrderBy_794() { expectParserSuccess("from Animal a join fetch a.offspring o order by o.description"); } @Test public void testHQLTestCollectionOrderBy_795() { expectParserSuccess("from Animal a join a.offspring o order by a.description, o.description"); } @Test public void testHQLTestExpressionWithParamInFunction_797() { expectParserSuccess("from Animal a where abs(:param) < 2.0"); } @Test public void testHQLTestExpressionWithParamInFunction_798() { expectParserSuccess("from Animal a where abs(a.bodyWeight) < 2.0"); } @Test public void testHQLTestCompositeKeysWithPropertyNamedId_800() { expectParserSuccess("select e.id.id from EntityWithCrazyCompositeKey e"); } @Test public void testHQLTestCompositeKeysWithPropertyNamedId_801() { expectParserSuccess("select max(e.id.id) from EntityWithCrazyCompositeKey e"); } @Test public void testHQLTestMaxindexHqlFunctionInElementAccessorFailureExpected_803() { expectParserSuccess("select c from ContainerX c where c.manyToMany[ maxindex(c.manyToMany) ].count = 2"); } @Test public void testHQLTestMaxindexHqlFunctionInElementAccessorFailureExpected_804() { expectParserSuccess("select c from Container c where c.manyToMany[ maxIndex(c.manyToMany) ].count = 2"); } @Test public void testHQLTestMultipleElementAccessorOperatorsFailureExpected_806() { expectParserSuccess("select c from ContainerX c where c.oneToMany[ c.manyToMany[0].count ].name = 's'"); } @Test public void testHQLTestKeyManyToOneJoinFailureExpected_808() { expectParserSuccess("from Order o left join fetch o.lineItems li left join fetch li.product p"); } @Test public void testHQLTestKeyManyToOneJoinFailureExpected_809() { expectParserSuccess("from Outer o where o.id.master.id.sup.dudu is not null"); } @Test public void testHQLTestDuplicateExplicitJoinFailureExpected_811() { expectParserSuccess("from Animal a join a.mother m1 join a.mother m2"); } @Test public void testHQLTestDuplicateExplicitJoinFailureExpected_812() { expectParserSuccess("from Zoo zoo join zoo.animals an join zoo.mammals m"); } @Test public void testHQLTestDuplicateExplicitJoinFailureExpected_813() { expectParserSuccess("from Zoo zoo join zoo.mammals an join zoo.mammals m"); } @Test public void testHQLTestIndexWithExplicitJoin_815() { expectParserSuccess("from Zoo zoo join zoo.animals an where zoo.mammals[ index(an) ] = an"); } @Test public void testHQLTestIndexWithExplicitJoin_816() { expectParserSuccess("from Zoo zoo join zoo.mammals dog where zoo.mammals[ index(dog) ] = dog"); } @Test public void testHQLTestIndexWithExplicitJoin_817() { expectParserSuccess("from Zoo zoo join zoo.mammals dog where dog = zoo.mammals[ index(dog) ]"); } @Test public void testHQLTestOneToManyMapIndex_819() { expectParserSuccess("from Zoo zoo where zoo.mammals['dog'].description like '%black%'"); } @Test public void testHQLTestOneToManyMapIndex_820() { expectParserSuccess("from Zoo zoo where zoo.mammals['dog'].father.description like '%black%'"); } @Test public void testHQLTestOneToManyMapIndex_821() { expectParserSuccess("from Zoo zoo where zoo.mammals['dog'].father.id = 1234"); } @Test public void testHQLTestOneToManyMapIndex_822() { expectParserSuccess("from Zoo zoo where zoo.animals['1234'].description like '%black%'"); } @Test public void testHQLTestExplicitJoinMapIndex_824() { expectParserSuccess("from Zoo zoo, Dog dog where zoo.mammals['dog'] = dog"); } @Test public void testHQLTestExplicitJoinMapIndex_825() { expectParserSuccess("from Zoo zoo join zoo.mammals dog where zoo.mammals['dog'] = dog"); } @Test public void testHQLTestIndexFunction_827() { expectParserSuccess("from Zoo zoo join zoo.mammals dog where index(dog) = 'dog'"); } @Test public void testHQLTestIndexFunction_828() { expectParserSuccess("from Zoo zoo join zoo.animals an where index(an) = '1234'"); } @Test public void testHQLTestSelectCollectionOfValues_830() { expectParserSuccess("select baz, date from Baz baz join baz.stringDateMap date where index(date) = 'foo'"); } @Test public void testHQLTestCollectionOfValues_832() { expectParserSuccess("from Baz baz join baz.stringDateMap date where index(date) = 'foo'"); } @Test public void testHQLTestHHH719_834() { expectParserSuccess("from Baz b order by org.bazco.SpecialFunction(b.id)"); } @Test public void testHQLTestHHH719_835() { expectParserSuccess("from Baz b order by anypackage.anyFunction(b.id)"); } @Test public void testHQLTestParameterListExpansion_837() { expectParserSuccess("from Animal as animal where animal.id in (:idList_1, :idList_2)"); } @Test public void testHQLTestComponentManyToOneDereferenceShortcut_839() { expectParserSuccess("from Zoo z where z.address.stateProvince.id is null"); } @Test public void testHQLTestNestedCollectionImplicitJoins_841() { expectParserSuccess("select h.friends.offspring from Human h"); } @Test public void testHQLTestImplicitJoinsInGroupBy_845() { expectParserSuccess("select o.mother.bodyWeight, count(distinct o) from Animal an join an.offspring as o group by o.mother.bodyWeight"); } @Test public void testHQLTestCrazyIdFieldNames_847() { expectParserSuccess("select e.heresAnotherCrazyIdFieldName from MoreCrazyIdFieldNameStuffEntity e where e.heresAnotherCrazyIdFieldName is not null"); } @Test public void testHQLTestCrazyIdFieldNames_848() { expectParserSuccess("select e.heresAnotherCrazyIdFieldName.heresAnotherCrazyIdFieldName from MoreCrazyIdFieldNameStuffEntity e where e.heresAnotherCrazyIdFieldName is not null"); } @Test public void testHQLTestSizeFunctionAndProperty_850() { expectParserSuccess("from Animal a where a.offspring.size > 0"); } @Test public void testHQLTestSizeFunctionAndProperty_851() { expectParserSuccess("from Animal a join a.offspring where a.offspring.size > 1"); } @Test public void testHQLTestSizeFunctionAndProperty_852() { expectParserSuccess("from Animal a where size(a.offspring) > 0"); } @Test public void testHQLTestSizeFunctionAndProperty_853() { expectParserSuccess("from Animal a join a.offspring o where size(a.offspring) > 1"); } @Test public void testHQLTestSizeFunctionAndProperty_854() { expectParserSuccess("from Animal a where size(a.offspring) > 1 and size(a.offspring) < 100"); } @Test public void testHQLTestSizeFunctionAndProperty_855() { expectParserSuccess("from Human a where a.family.size > 0"); } @Test public void testHQLTestSizeFunctionAndProperty_856() { expectParserSuccess("from Human a join a.family where a.family.size > 1"); } @Test public void testHQLTestSizeFunctionAndProperty_857() { expectParserSuccess("from Human a where size(a.family) > 0"); } @Test public void testHQLTestSizeFunctionAndProperty_858() { expectParserSuccess("from Human a join a.family o where size(a.family) > 1"); } @Test public void testHQLTestSizeFunctionAndProperty_859() { expectParserSuccess("from Human a where a.family.size > 0 and a.family.size < 100"); } @Test public void testHQLTestFromOnly_861() { expectParserSuccess("from Animal"); } @Test public void testHQLTestJoinPathEndingInValueCollection_864() { expectParserSuccess("select h from Human as h join h.nickNames as nn where h.nickName=:nn1 and (nn=:nn2 or nn=:nn3)"); } @Test public void testHQLTestSerialJoinPathEndingInValueCollection_866() { expectParserSuccess("select h from Human as h join h.friends as f join f.nickNames as nn where h.nickName=:nn1 and (nn=:nn2 or nn=:nn3)"); } @Test public void testHQLTestImplicitJoinContainedByCollectionFunction_868() { expectParserSuccess("from Human as h where 'shipping' in indices(h.father.addresses)"); } @Test public void testHQLTestImplicitJoinContainedByCollectionFunction_869() { expectParserSuccess("from Human as h where 'shipping' in indices(h.father.father.addresses)"); } @Test public void testHQLTestImplicitJoinContainedByCollectionFunction_870() { expectParserSuccess("from Human as h where 'sparky' in elements(h.father.nickNames)"); } @Test public void testHQLTestImplicitJoinContainedByCollectionFunction_871() { expectParserSuccess("from Human as h where 'sparky' in elements(h.father.father.nickNames)"); } @Test public void testHQLTestCollectionOfValuesSize_877() { expectParserSuccess("select size(baz.stringDateMap) from example.legacy.Baz baz"); } @Test public void testHQLTestCollectionFunctions_879() { expectParserSuccess("from Zoo zoo where size(zoo.animals) > 100"); } @Test public void testHQLTestCollectionFunctions_880() { expectParserSuccess("from Zoo zoo where maxindex(zoo.mammals) = 'dog'"); } @Test public void testHQLTestImplicitJoinInExplicitJoin_882() { expectParserSuccess("from Animal an inner join an.mother.mother gm"); } @Test public void testHQLTestImplicitJoinInExplicitJoin_883() { expectParserSuccess("from Animal an inner join an.mother.mother.mother ggm"); } @Test public void testHQLTestImplicitJoinInExplicitJoin_884() { expectParserSuccess("from Animal an inner join an.mother.mother.mother.mother gggm"); } @Test public void testHQLTestImpliedManyToManyProperty_886() { expectParserSuccess("select c from ContainerX c where c.manyToMany[0].name = 's'"); } @Test public void testHQLTestImpliedManyToManyProperty_887() { expectParserSuccess("select size(zoo.animals) from Zoo zoo"); } @Test public void testHQLTestCollectionIndexFunctionsInSelect_889() { expectParserSuccess("select maxindex(zoo.animals) from Zoo zoo"); } @Test public void testHQLTestCollectionIndexFunctionsInSelect_890() { expectParserSuccess("select minindex(zoo.animals) from Zoo zoo"); } @Test public void testHQLTestCollectionIndexFunctionsInSelect_891() { expectParserSuccess("select indices(zoo.animals) from Zoo zoo"); } @Test public void testHQLTestCollectionElementFunctionsInSelect_893() { expectParserSuccess("select maxelement(zoo.animals) from Zoo zoo"); } @Test public void testHQLTestCollectionElementFunctionsInSelect_894() { expectParserSuccess("select minelement(zoo.animals) from Zoo zoo"); } @Test public void testHQLTestCollectionElementFunctionsInSelect_895() { expectParserSuccess("select elements(zoo.animals) from Zoo zoo"); } @Test public void testHQLTestFetchCollectionOfValues_897() { expectParserSuccess("from Baz baz left join fetch baz.stringSet"); } @Test public void testHQLTestFetchList_899() { expectParserSuccess("from User u join fetch u.permissions"); } @Test public void testHQLTestCollectionFetchWithExplicitThetaJoin_901() { expectParserSuccess("select m from Master m1, Master m left join fetch m.details where m.name=m1.name"); } @Test public void testHQLTestListElementFunctionInSelect_903() { expectParserSuccess("select maxelement(u.permissions) from User u"); } @Test public void testHQLTestListElementFunctionInSelect_904() { expectParserSuccess("select elements(u.permissions) from User u"); } @Test public void testHQLTestListElementFunctionInWhere_906() { expectParserSuccess("from User u where 'read' in elements(u.permissions)"); } @Test public void testHQLTestListElementFunctionInWhere_907() { expectParserSuccess("from User u where 'write' <> all elements(u.permissions)"); } @Test public void testHQLTestManyToManyElementFunctionInSelect_909() { expectParserSuccess("select maxelement(human.friends) from Human human"); } @Test public void testHQLTestManyToManyElementFunctionInSelect_910() { expectParserSuccess("select elements(human.friends) from Human human"); } @Test public void testHQLTestManyToManyMaxElementFunctionInWhere_912() { expectParserSuccess("from Human human where 5 = maxelement(human.friends)"); } @Test public void testHQLTestCollectionIndexFunctionsInWhere_914() { expectParserSuccess("from Zoo zoo where 4 = maxindex(zoo.animals)"); } @Test public void testHQLTestCollectionIndexFunctionsInWhere_915() { expectParserSuccess("from Zoo zoo where 2 = minindex(zoo.animals)"); } @Test public void testHQLTestCollectionIndicesInWhere_917() { expectParserSuccess("from Zoo zoo where 4 > some indices(zoo.animals)"); } @Test public void testHQLTestCollectionIndicesInWhere_918() { expectParserSuccess("from Zoo zoo where 4 > all indices(zoo.animals)"); } @Test public void testHQLTestIndicesInWhere_920() { expectParserSuccess("from Zoo zoo where 4 in indices(zoo.animals)"); } @Test public void testHQLTestIndicesInWhere_921() { expectParserSuccess("from Zoo zoo where exists indices(zoo.animals)"); } @Test public void testHQLTestCollectionElementInWhere_923() { expectParserSuccess("from Zoo zoo where 4 > some elements(zoo.animals)"); } @Test public void testHQLTestCollectionElementInWhere_924() { expectParserSuccess("from Zoo zoo where 4 > all elements(zoo.animals)"); } @Test public void testHQLTestElementsInWhere_926() { expectParserSuccess("from Zoo zoo where 4 in elements(zoo.animals)"); } @Test public void testHQLTestElementsInWhere_927() { expectParserSuccess("from Zoo zoo where exists elements(zoo.animals)"); } @Test public void testHQLTestNull_929() { expectParserSuccess("from Human h where h.nickName is null"); } @Test public void testHQLTestNull_930() { expectParserSuccess("from Human h where h.nickName is not null"); } @Test public void testHQLTestSubstitutions_932() { expectParserSuccess("from Human h where h.pregnant = yes"); } @Test public void testHQLTestSubstitutions_933() { expectParserSuccess("from Human h where h.pregnant = foo"); } @Test public void testHQLTestEscapedQuote_935() { expectParserSuccess("from Human h where h.nickName='1 ov''tha''few'"); } @Test public void testHQLTestInvalidHql_941() { expectParserSuccess("from Animal foo where an.bodyWeight > 10"); } @Test public void testHQLTestInvalidHql_942() { expectParserSuccess("select an.name from Animal foo"); } @Test public void testHQLTestInvalidHql_943() { expectParserSuccess("from Animal foo where an.verybogus > 10"); } @Test public void testHQLTestInvalidHql_944() { expectParserSuccess("select an.boguspropertyname from Animal foo"); } @Test public void testHQLTestInvalidHql_945() { expectParserFailure("select an.name"); } @Test public void testHQLTestInvalidHql_946() { expectParserFailure("from Animal an where (((an.bodyWeight > 10 and an.bodyWeight < 100)) or an.bodyWeight is null"); } @Test public void testHQLTestInvalidHql_947() { expectParserFailure("from Animal an where an.bodyWeight is null where an.bodyWeight is null"); } @Test public void testHQLTestInvalidHql_948() { expectParserFailure("from where name='foo'"); } @Test public void testHQLTestInvalidHql_949() { expectParserSuccess("from NonexistentClass where name='foo'"); } @Test public void testHQLTestWhereBetween_953() { expectParserSuccess("from Animal an where an.bodyWeight between 1 and 10"); } @Test public void testHQLTestWhereLike_957() { expectParserSuccess("from Animal a where a.description like '%black%'"); } @Test public void testHQLTestWhereLike_958() { expectParserSuccess("from Animal an where an.description like '%fat%'"); } @Test public void testHQLTestWhereIn_961() { expectParserSuccess("from Animal an where an.description in ('fat', 'skinny')"); } @Test public void testHQLTestLiteralInFunction_963() { expectParserSuccess("from Animal an where an.bodyWeight > abs(5)"); } @Test public void testHQLTestLiteralInFunction_964() { expectParserSuccess("from Animal an where an.bodyWeight > abs(-5)"); } @Test public void testHQLTestNotOrWhereClause_971() { expectParserSuccess("from Simple s where 'foo'='bar' or not 'foo'='foo'"); } @Test public void testHQLTestNotOrWhereClause_972() { expectParserSuccess("from Simple s where 'foo'='bar' or not ('foo'='foo')"); } @Test public void testHQLTestNotOrWhereClause_973() { expectParserSuccess("from Simple s where not ( 'foo'='bar' or 'foo'='foo' )"); } @Test public void testHQLTestNotOrWhereClause_974() { expectParserSuccess("from Simple s where not ( 'foo'='bar' and 'foo'='foo' )"); } @Test public void testHQLTestNotOrWhereClause_975() { expectParserSuccess("from Simple s where not ( 'foo'='bar' and 'foo'='foo' ) or not ('x'='y')"); } @Test public void testHQLTestNotOrWhereClause_976() { expectParserSuccess("from Simple s where not ( 'foo'='bar' or 'foo'='foo' ) and not ('x'='y')"); } @Test public void testHQLTestNotOrWhereClause_977() { expectParserSuccess("from Simple s where not ( 'foo'='bar' or 'foo'='foo' ) and 'x'='y'"); } @Test public void testHQLTestNotOrWhereClause_978() { expectParserSuccess("from Simple s where not ( 'foo'='bar' and 'foo'='foo' ) or 'x'='y'"); } @Test public void testHQLTestNotOrWhereClause_979() { expectParserSuccess("from Simple s where 'foo'='bar' and 'foo'='foo' or not 'x'='y'"); } @Test public void testHQLTestNotOrWhereClause_980() { expectParserSuccess("from Simple s where 'foo'='bar' or 'foo'='foo' and not 'x'='y'"); } @Test public void testHQLTestNotOrWhereClause_981() { expectParserSuccess("from Simple s where ('foo'='bar' and 'foo'='foo') or 'x'='y'"); } @Test public void testHQLTestNotOrWhereClause_982() { expectParserSuccess("from Simple s where ('foo'='bar' or 'foo'='foo') and 'x'='y'"); } @Test public void testHQLTestOrderBy_991() { expectParserSuccess("from Animal an order by an.bodyWeight"); } @Test public void testHQLTestOrderBy_992() { expectParserSuccess("from Animal an order by an.bodyWeight asc"); } @Test public void testHQLTestOrderBy_993() { expectParserSuccess("from Animal an order by an.bodyWeight desc"); } @Test public void testHQLTestOrderBy_995() { expectParserSuccess("from Animal an order by an.mother.bodyWeight"); } @Test public void testHQLTestOrderBy_996() { expectParserSuccess("from Animal an order by an.bodyWeight, an.description"); } @Test public void testHQLTestOrderBy_997() { expectParserSuccess("from Animal an order by an.bodyWeight asc, an.description desc"); } @Test public void testHQLTestGroupByFunction_1000() { expectParserSuccess("select count(*) from Human h group by year(h.birthdate)"); } @Test public void testHQLTestGroupByFunction_1002() { expectParserSuccess("select count(*) from Human h group by year(sysdate)"); } @Test public void testHQLTestPolymorphism_1004() { expectParserSuccess("from Mammal"); } @Test public void testHQLTestPolymorphism_1005() { expectParserSuccess("from Dog"); } @Test public void testHQLTestPolymorphism_1006() { expectParserSuccess("from Mammal m where m.pregnant = false and m.bodyWeight > 10"); } @Test public void testHQLTestPolymorphism_1007() { expectParserSuccess("from Dog d where d.pregnant = false and d.bodyWeight > 10"); } @Test public void testHQLTestProduct_1009() { expectParserSuccess("from Animal, Animal"); } @Test public void testHQLTestProduct_1010() { expectParserSuccess("from Animal x, Animal y where x.bodyWeight = y.bodyWeight"); } @Test public void testHQLTestProduct_1011() { expectParserSuccess("from Animal x, Mammal y where x.bodyWeight = y.bodyWeight and not y.pregnant = true"); } @Test public void testHQLTestProduct_1012() { expectParserSuccess("from Mammal, Mammal"); } @Test public void testHQLTestJoinedSubclassProduct_1014() { expectParserSuccess("from PettingZoo, PettingZoo"); } @Test public void testHQLTestProjectProduct_1016() { expectParserSuccess("select x from Human x, Human y where x.nickName = y.nickName"); } @Test public void testHQLTestProjectProduct_1017() { expectParserSuccess("select x, y from Human x, Human y where x.nickName = y.nickName"); } @Test public void testHQLTestExplicitEntityJoins_1019() { expectParserSuccess("from Animal an inner join an.mother mo"); } @Test public void testHQLTestExplicitEntityJoins_1020() { expectParserSuccess("from Animal an left outer join an.mother mo"); } @Test public void testHQLTestExplicitEntityJoins_1021() { expectParserSuccess("from Animal an left outer join fetch an.mother"); } @Test public void testHQLTestMultipleExplicitEntityJoins_1023() { expectParserSuccess("from Animal an inner join an.mother mo inner join mo.mother gm"); } @Test public void testHQLTestMultipleExplicitEntityJoins_1024() { expectParserSuccess("from Animal an left outer join an.mother mo left outer join mo.mother gm"); } @Test public void testHQLTestMultipleExplicitEntityJoins_1025() { expectParserSuccess("from Animal an inner join an.mother m inner join an.father f"); } @Test public void testHQLTestMultipleExplicitEntityJoins_1026() { expectParserSuccess("from Animal an left join fetch an.mother m left join fetch an.father f"); } @Test public void testHQLTestMultipleExplicitJoins_1028() { expectParserSuccess("from Animal an inner join an.mother mo inner join an.offspring os"); } @Test public void testHQLTestMultipleExplicitJoins_1029() { expectParserSuccess("from Animal an left outer join an.mother mo left outer join an.offspring os"); } @Test public void testHQLTestExplicitEntityJoinsWithRestriction_1031() { expectParserSuccess("from Animal an inner join an.mother mo where an.bodyWeight < mo.bodyWeight"); } @Test public void testHQLTestIdProperty_1033() { expectParserSuccess("from Animal a where a.mother.id = 12"); } @Test public void testHQLTestSubclassAssociation_1035() { expectParserSuccess("from DomesticAnimal da join da.owner o where o.nickName = 'Gavin'"); } @Test public void testHQLTestSubclassAssociation_1036() { expectParserSuccess("from DomesticAnimal da left join fetch da.owner"); } @Test public void testHQLTestSubclassAssociation_1037() { expectParserSuccess("from Human h join h.pets p where p.pregnant = 1"); } @Test public void testHQLTestSubclassAssociation_1038() { expectParserSuccess("from Human h join h.pets p where p.bodyWeight > 100"); } @Test public void testHQLTestSubclassAssociation_1039() { expectParserSuccess("from Human h left join fetch h.pets"); } @Test public void testHQLTestExplicitCollectionJoins_1041() { expectParserSuccess("from Animal an inner join an.offspring os"); } @Test public void testHQLTestExplicitCollectionJoins_1042() { expectParserSuccess("from Animal an left outer join an.offspring os"); } @Test public void testHQLTestExplicitOuterJoinFetch_1044() { expectParserSuccess("from Animal an left outer join fetch an.offspring"); } @Test public void testHQLTestExplicitOuterJoinFetchWithSelect_1046() { expectParserSuccess("select an from Animal an left outer join fetch an.offspring"); } @Test public void testHQLTestExplicitJoins_1048() { expectParserSuccess("from Zoo zoo join zoo.mammals mam where mam.pregnant = true and mam.description like '%white%'"); } @Test public void testHQLTestExplicitJoins_1049() { expectParserSuccess("from Zoo zoo join zoo.animals an where an.description like '%white%'"); } @Test public void testHQLTestMultibyteCharacterConstant_1051() { expectParserSuccess("from Zoo zoo join zoo.animals an where an.description like '%\u4e2d%'"); } @Test public void testHQLTestImplicitJoins_1053() { expectParserSuccess("from Animal an where an.mother.bodyWeight > ?"); } @Test public void testHQLTestImplicitJoins_1054() { expectParserSuccess("from Animal an where an.mother.bodyWeight > 10"); } @Test public void testHQLTestImplicitJoins_1055() { expectParserSuccess("from Dog dog where dog.mother.bodyWeight > 10"); } @Test public void testHQLTestImplicitJoins_1056() { expectParserSuccess("from Animal an where an.mother.mother.bodyWeight > 10"); } @Test public void testHQLTestImplicitJoins_1057() { expectParserSuccess("from Animal an where an.mother is not null"); } @Test public void testHQLTestImplicitJoins_1058() { expectParserSuccess("from Animal an where an.mother.id = 123"); } @Test public void testHQLTestImplicitJoinInSelect_1060() { expectParserSuccess("select foo, foo.long from Foo foo"); } @Test public void testHQLTestImplicitJoinInSelect_1061() { expectParserSuccess("select foo.foo from Foo foo"); } @Test public void testHQLTestImplicitJoinInSelect_1062() { expectParserSuccess("select foo, foo.foo from Foo foo"); } @Test public void testHQLTestImplicitJoinInSelect_1063() { expectParserSuccess("select foo.foo from Foo foo where foo.foo is not null"); } @Test public void testHQLTestSelectExpressions_1065() { expectParserSuccess("select an.mother.mother from Animal an"); } @Test public void testHQLTestSelectExpressions_1066() { expectParserSuccess("select an.mother.mother.mother from Animal an"); } @Test public void testHQLTestSelectExpressions_1067() { expectParserSuccess("select an.mother.mother.bodyWeight from Animal an"); } @Test public void testHQLTestSelectExpressions_1068() { expectParserSuccess("select an.mother.zoo.id from Animal an"); } @Test public void testHQLTestSelectExpressions_1069() { expectParserSuccess("select user.human.zoo.id from User user"); } @Test public void testHQLTestSelectExpressions_1070() { expectParserSuccess("select u.userName, u.human.name.first from User u"); } @Test public void testHQLTestSelectExpressions_1071() { expectParserSuccess("select u.human.name.last, u.human.name.first from User u"); } @Test public void testHQLTestSelectExpressions_1072() { expectParserSuccess("select bar.baz.name from Bar bar"); } @Test public void testHQLTestSelectExpressions_1073() { expectParserSuccess("select bar.baz.name, bar.baz.count from Bar bar"); } @Test public void testHQLTestMapIndex_1077() { expectParserSuccess("from User u where u.permissions['datagrid']='read'"); } @Test public void testHQLTestCollectionFunctionsInSelect_1079() { expectParserSuccess("select baz, size(baz.stringSet), count( distinct elements(baz.stringSet) ), max( elements(baz.stringSet) ) from Baz baz group by baz"); } @Test public void testHQLTestCollectionFunctionsInSelect_1080() { expectParserSuccess("select elements(fum1.friends) from example.legacy.Fum fum1"); } @Test public void testHQLTestCollectionFunctionsInSelect_1081() { expectParserSuccess("select elements(one.manies) from example.legacy.One one"); } @Test public void testHQLTestNamedParameters_1083() { expectParserSuccess("from Animal an where an.mother.bodyWeight > :weight"); } @Test public void testHQLTestClassProperty_1085() { expectParserSuccess("from Animal a where a.mother.class = Reptile"); } @Test public void testHQLTestComponent_1087() { expectParserSuccess("from Human h where h.name.first = 'Gavin'"); } @Test public void testHQLTestSelectEntity_1089() { expectParserSuccess("select an from Animal an inner join an.mother mo where an.bodyWeight < mo.bodyWeight"); } @Test public void testHQLTestSelectEntity_1090() { expectParserSuccess("select mo, an from Animal an inner join an.mother mo where an.bodyWeight < mo.bodyWeight"); } @Test public void testHQLTestValueAggregate_1092() { expectParserSuccess("select max(p), min(p) from User u join u.permissions p"); } @Test public void testHQLTestAggregation_1094() { expectParserSuccess("select count(an) from Animal an"); } @Test public void testHQLTestAggregation_1095() { expectParserSuccess("select count(distinct an) from Animal an"); } @Test public void testHQLTestAggregation_1096() { expectParserSuccess("select count(distinct an.id) from Animal an"); } @Test public void testHQLTestAggregation_1097() { expectParserSuccess("select count(all an.id) from Animal an"); } @Test public void testHQLTestSelectProperty_1099() { expectParserSuccess("select an.bodyWeight, mo.bodyWeight from Animal an inner join an.mother mo where an.bodyWeight < mo.bodyWeight"); } @Test public void testHQLTestSelectEntityProperty_1101() { expectParserSuccess("select an.mother from Animal an"); } @Test public void testHQLTestSelectEntityProperty_1102() { expectParserSuccess("select an, an.mother from Animal an"); } @Test public void testHQLTestSelectDistinctAll_1104() { expectParserSuccess("select distinct an.description, an.bodyWeight from Animal an"); } @Test public void testHQLTestSelectDistinctAll_1105() { expectParserSuccess("select all an from Animal an"); } @Test public void testHQLTestSelectAssociatedEntityId_1107() { expectParserSuccess("select an.mother.id from Animal an"); } @Test public void testHQLTestGroupBy_1109() { expectParserSuccess("select an.mother.id, max(an.bodyWeight) from Animal an group by an.mother.id having max(an.bodyWeight)>1.0"); } @Test public void testHQLTestGroupByMultiple_1111() { expectParserSuccess("select s.id, s.count, count(t), max(t.date) from example.legacy.Simple s, example.legacy.Simple t where s.count = t.count group by s.id, s.count order by s.count"); } @Test public void testHQLTestManyToMany_1113() { expectParserSuccess("from Human h join h.friends f where f.nickName = 'Gavin'"); } @Test public void testHQLTestManyToMany_1114() { expectParserSuccess("from Human h join h.friends f where f.bodyWeight > 100"); } @Test public void testHQLTestManyToManyElementFunctionInWhere_1116() { expectParserSuccess("from Human human where human in elements(human.friends)"); } @Test public void testHQLTestManyToManyElementFunctionInWhere_1117() { expectParserSuccess("from Human human where human = some elements(human.friends)"); } @Test public void testHQLTestManyToManyElementFunctionInWhere2_1119() { expectParserSuccess("from Human h1, Human h2 where h2 in elements(h1.family)"); } @Test public void testHQLTestManyToManyElementFunctionInWhere2_1120() { expectParserSuccess("from Human h1, Human h2 where 'father' in indices(h1.family)"); } @Test public void testHQLTestManyToManyFetch_1122() { expectParserSuccess("from Human h left join fetch h.friends"); } @Test public void testHQLTestManyToManyIndexAccessor_1124() { expectParserSuccess("select c from ContainerX c, Simple s where c.manyToMany[2] = s"); } @Test public void testHQLTestManyToManyIndexAccessor_1125() { expectParserSuccess("select s from ContainerX c, Simple s where c.manyToMany[2] = s"); } @Test public void testHQLTestManyToManyIndexAccessor_1126() { expectParserSuccess("from ContainerX c, Simple s where c.manyToMany[2] = s"); } @Test public void testHQLTestPositionalParameters_1154() { expectParserSuccess("from Animal an where an.bodyWeight > ?"); } @Test public void testHQLTestKeywordPropertyName_1156() { expectParserSuccess("from Glarch g order by g.order asc"); } @Test public void testHQLTestKeywordPropertyName_1157() { expectParserSuccess("select g.order from Glarch g where g.order = 3"); } @Test public void testHQLTestJavaConstant_1159() { expectParserSuccess("from example.legacy.Category c where c.name = example.legacy.Category.ROOT_CATEGORY"); } @Test public void testHQLTestJavaConstant_1160() { expectParserSuccess("from example.legacy.Category c where c.id = example.legacy.Category.ROOT_ID"); } @Test public void testHQLTestJavaConstant_1161() { expectParserSuccess("from Category c where c.name = Category.ROOT_CATEGORY"); } @Test public void testHQLTestJavaConstant_1162() { expectParserSuccess("select c.name, Category.ROOT_ID from Category as c"); } @Test public void testHQLTestClassName_1164() { expectParserSuccess("from Zoo zoo where zoo.class = PettingZoo"); } @Test public void testHQLTestClassName_1165() { expectParserSuccess("from DomesticAnimal an where an.class = Dog"); } @Test public void testHQLTestSelectDialectFunction_1170() { expectParserSuccess("select max(a.bodyWeight) from Animal a"); } @Test public void testHQLTestTwoJoins_1172() { expectParserSuccess("from Human human join human.friends, Human h join h.mother"); } @Test public void testHQLTestTwoJoins_1173() { expectParserSuccess("from Human human join human.friends f, Animal an join an.mother m where f=m"); } @Test public void testHQLTestTwoJoins_1174() { expectParserSuccess("from Baz baz left join baz.fooToGlarch, Bar bar join bar.foo"); } @Test public void testHQLTestToOneToManyManyJoinSequence_1176() { expectParserSuccess("from Dog d join d.owner h join h.friends f where f.name.first like 'joe%'"); } @Test public void testHQLTestToOneToManyJoinSequence_1178() { expectParserSuccess("from Animal a join a.mother m join m.offspring"); } @Test public void testHQLTestToOneToManyJoinSequence_1179() { expectParserSuccess("from Dog d join d.owner m join m.offspring"); } @Test public void testHQLTestToOneToManyJoinSequence_1180() { expectParserSuccess("from Animal a join a.mother m join m.offspring o where o.bodyWeight > a.bodyWeight"); } @Test public void testHQLTestSubclassExplicitJoin_1182() { expectParserSuccess("from DomesticAnimal da join da.owner o where o.nickName = 'gavin'"); } @Test public void testHQLTestSubclassExplicitJoin_1183() { expectParserSuccess("from DomesticAnimal da join da.owner o where o.bodyWeight > 0"); } @Test public void testHQLTestMultipleExplicitCollectionJoins_1185() { expectParserSuccess("from Animal an inner join an.offspring os join os.offspring gc"); } @Test public void testHQLTestMultipleExplicitCollectionJoins_1186() { expectParserSuccess("from Animal an left outer join an.offspring os left outer join os.offspring gc"); } @Test public void testHQLTestSelectDistinctComposite_1188() { expectParserSuccess("select distinct p from example.compositeelement.Parent p join p.children c where c.name like 'Child%'"); } @Test public void testHQLTestDotComponent_1190() { expectParserSuccess("select fum.id from example.legacy.Fum as fum where not fum.fum='FRIEND'"); } @Test public void testHQLTestOrderByCount_1192() { expectParserSuccess("from Animal an group by an.zoo.id order by an.zoo.id, count(*)"); } @Test public void testHQLTestHavingCount_1194() { expectParserSuccess("from Animal an group by an.zoo.id having count(an.zoo.id) > 1"); } @Test public void testHQLTest_selectWhereElements_1196() { expectParserSuccess("select foo from Foo foo, Baz baz where foo in elements(baz.fooArray)"); } @Test public void testHQLTestCollectionOfComponents_1198() { expectParserSuccess("from Baz baz inner join baz.components comp where comp.name='foo'"); } @Test public void testHQLTestOneToOneJoinedFetch_1200() { expectParserSuccess("from example.onetoone.joined.Person p join fetch p.address left join fetch p.mailingAddress"); } @Test public void testHQLTestSubclassImplicitJoin_1202() { expectParserSuccess("from DomesticAnimal da where da.owner.nickName like 'Gavin%'"); } @Test public void testHQLTestSubclassImplicitJoin_1203() { expectParserSuccess("from DomesticAnimal da where da.owner.nickName = 'gavin'"); } @Test public void testHQLTestSubclassImplicitJoin_1204() { expectParserSuccess("from DomesticAnimal da where da.owner.bodyWeight > 0"); } @Test public void testHQLTestComponent2_1206() { expectParserSuccess("from Dog dog where dog.owner.name.first = 'Gavin'"); } @Test public void testHQLTestOneToOne_1208() { expectParserSuccess("from User u where u.human.nickName='Steve'"); } @Test public void testHQLTestOneToOne_1209() { expectParserSuccess("from User u where u.human.name.first='Steve'"); } @Test public void testHQLTestSelectClauseImplicitJoin_1211() { expectParserSuccess("select d.owner.mother from Dog d"); } @Test public void testHQLTestSelectClauseImplicitJoin_1212() { expectParserSuccess("select d.owner.mother.description from Dog d"); } @Test public void testHQLTestSelectClauseImplicitJoin_1213() { expectParserSuccess("select d.owner.mother from Dog d, Dog h"); } @Test public void testHQLTestFromClauseImplicitJoin_1215() { expectParserSuccess("from DomesticAnimal da join da.owner.mother m where m.bodyWeight > 10"); } @Test public void testHQLTestImplicitJoinInFrom_1217() { expectParserSuccess("from Human h join h.mother.mother.offspring o"); } @Test public void testHQLTestDuplicateImplicitJoinInSelect_1219() { expectParserSuccess("select an.mother.bodyWeight from Animal an join an.mother m where an.mother.bodyWeight > 10"); } @Test public void testHQLTestDuplicateImplicitJoinInSelect_1220() { expectParserSuccess("select an.mother.bodyWeight from Animal an where an.mother.bodyWeight > 10"); } @Test public void testHQLTestDuplicateImplicitJoinInSelect_1221() { expectParserSuccess("select an.mother from Animal an where an.mother.bodyWeight is not null"); } @Test public void testHQLTestDuplicateImplicitJoinInSelect_1222() { expectParserSuccess("select an.mother.bodyWeight from Animal an order by an.mother.bodyWeight"); } @Test public void testHQLTestSelectProperty2_1224() { expectParserSuccess("select an, mo.bodyWeight from Animal an inner join an.mother mo where an.bodyWeight < mo.bodyWeight"); } @Test public void testHQLTestSelectProperty2_1225() { expectParserSuccess("select an, mo, an.bodyWeight, mo.bodyWeight from Animal an inner join an.mother mo where an.bodyWeight < mo.bodyWeight"); } @Test public void testHQLTestSubclassWhere_1227() { expectParserSuccess("from PettingZoo pz1, PettingZoo pz2 where pz1.id = pz2.id"); } @Test public void testHQLTestSubclassWhere_1228() { expectParserSuccess("from PettingZoo pz1, PettingZoo pz2 where pz1.id = pz2"); } @Test public void testHQLTestSubclassWhere_1229() { expectParserSuccess("from PettingZoo pz where pz.id > 0 "); } @Test public void testHQLTestNestedImplicitJoinsInSelect_1231() { expectParserSuccess("select foo.foo.foo.foo.string from example.legacy.Foo foo where foo.foo.foo = 'bar'"); } @Test public void testHQLTestNestedImplicitJoinsInSelect_1232() { expectParserSuccess("select foo.foo.foo.foo.string from example.legacy.Foo foo"); } @Test public void testHQLTestNestedComponent_1234() { expectParserSuccess("from example.legacy.Foo foo where foo.component.subcomponent.name='bar'"); } @Test public void testHQLTestNull2_1236() { expectParserSuccess("from Human h where not( h.nickName is null )"); } @Test public void testHQLTestNull2_1237() { expectParserSuccess("from Human h where not( h.nickName is not null )"); } @Test public void testHQLTestUnknownFailureFromMultiTableTest_1239() { expectParserSuccess("from Lower s where s.yetanother.name='name'"); } @Test public void testHQLTestJoinedSubclassImplicitJoin_1244() { expectParserSuccess("from example.legacy.Lower s where s.yetanother.name='name'"); } @Test public void testHQLTestProjectProductJoinedSubclass_1246() { expectParserSuccess("select zoo from Zoo zoo, PettingZoo pz where zoo=pz"); } @Test public void testHQLTestProjectProductJoinedSubclass_1247() { expectParserSuccess("select zoo, pz from Zoo zoo, PettingZoo pz where zoo=pz"); } @Test public void testHQLTestFetch_1253() { expectParserSuccess("from Zoo zoo left join zoo.mammals"); } @Test public void testHQLTestFetch_1254() { expectParserSuccess("from Zoo zoo left join fetch zoo.mammals"); } @Test public void testHQLTestOneToManyElementFunctionInWhere_1256() { expectParserSuccess("from Zoo zoo where 'dog' in indices(zoo.mammals)"); } @Test public void testHQLTestOneToManyElementFunctionInWhere_1257() { expectParserSuccess("from Zoo zoo, Dog dog where dog in elements(zoo.mammals)"); } @Test public void testHQLTestManyToManyElementFunctionInSelect_1259() { expectParserSuccess("select elements(zoo.mammals) from Zoo zoo"); } @Test public void testHQLTestManyToManyElementFunctionInSelect_1260() { expectParserSuccess("select indices(zoo.mammals) from Zoo zoo"); } @Test public void testHQLTestManyToManyInJoin_1262() { expectParserSuccess("select x.id from Human h1 join h1.family x"); } @Test public void testHQLTestManyToManyInJoin_1263() { expectParserSuccess("select index(h2) from Human h1 join h1.family h2"); } @Test public void testHQLTestOneToManyIndexAccess_1267() { expectParserSuccess("from Zoo zoo where zoo.mammals['dog'] is not null"); } @Test public void testHQLTestImpliedSelect_1269() { expectParserSuccess("select zoo from Zoo zoo"); } @Test public void testHQLTestImpliedSelect_1270() { expectParserSuccess("from Zoo zoo"); } @Test public void testHQLTestImpliedSelect_1271() { expectParserSuccess("from Zoo zoo join zoo.mammals m"); } @Test public void testHQLTestImpliedSelect_1272() { expectParserSuccess("from Zoo"); } @Test public void testHQLTestImpliedSelect_1273() { expectParserSuccess("from Zoo zoo join zoo.mammals"); } @Test public void testHQLTestCollectionsInSelect2_1279() { expectParserSuccess("select foo.string from Bar bar left join bar.baz.fooArray foo where bar.string = foo.string"); } @Test public void testHQLTestAssociationPropertyWithoutAlias_1281() { expectParserSuccess("from Animal where zoo is null"); } @Test public void testHQLTestComponentNoAlias_1283() { expectParserSuccess("from Human where name.first = 'Gavin'"); } @Test public void testASTParserLoadingTestComponentNullnessChecks_1285() { expectParserSuccess("from Human where name is null"); } @Test public void testASTParserLoadingTestComponentNullnessChecks_1286() { expectParserSuccess("from Human where name is not null"); } @Test public void testASTParserLoadingTestComponentNullnessChecks_1288() { expectParserSuccess("from Human where ? is null"); } @Test public void testASTParserLoadingTestInvalidCollectionDereferencesFail_1290() { expectParserSuccess("from Animal a join a.offspring o where o.description = 'xyz'"); } @Test public void testASTParserLoadingTestInvalidCollectionDereferencesFail_1291() { expectParserSuccess("from Animal a join a.offspring o where o.father.description = 'xyz'"); } @Test public void testASTParserLoadingTestInvalidCollectionDereferencesFail_1292() { expectParserSuccess("from Animal a join a.offspring o order by o.description"); } @Test public void testASTParserLoadingTestInvalidCollectionDereferencesFail_1293() { expectParserSuccess("from Animal a join a.offspring o order by o.father.description"); } @Test public void testASTParserLoadingTestInvalidCollectionDereferencesFail_1294() { expectParserSuccess("from Animal a order by a.offspring.description"); } @Test public void testASTParserLoadingTestInvalidCollectionDereferencesFail_1295() { expectParserSuccess("from Animal a order by a.offspring.father.description"); } @Test public void testASTParserLoadingTestCrazyIdFieldNames_1308() { expectParserSuccess("select e.heresAnotherCrazyIdFieldName from MoreCrazyIdFieldNameStuffEntity e"); } @Test public void testASTParserLoadingTestImplicitJoinsInDifferentClauses_1310() { expectParserSuccess("select e.owner from SimpleAssociatedEntity e"); } @Test public void testASTParserLoadingTestImplicitJoinsInDifferentClauses_1311() { expectParserSuccess("select e.id, e.owner from SimpleAssociatedEntity e"); } @Test public void testASTParserLoadingTestImplicitJoinsInDifferentClauses_1312() { expectParserSuccess("from SimpleAssociatedEntity e order by e.owner"); } @Test public void testASTParserLoadingTestImplicitJoinsInDifferentClauses_1313() { expectParserSuccess("select e.owner.id, count(*) from SimpleAssociatedEntity e group by e.owner"); } @Test public void testASTParserLoadingTestNestedComponentIsNull_1315() { expectParserSuccess("from Commento c where c.marelo.commento.mcompr is null"); } @Test public void testASTParserLoadingTestSpecialClassPropertyReference_1317() { expectParserSuccess("select a.description from Animal a where a.class = Mammal"); } @Test public void testASTParserLoadingTestSpecialClassPropertyReference_1318() { expectParserSuccess("select a.class from Animal a"); } @Test public void testASTParserLoadingTestSpecialClassPropertyReference_1319() { expectParserSuccess("from Animal an where an.class = Dog"); } @Test public void testASTParserLoadingTestSpecialClassPropertyReferenceFQN_1321() { expectParserSuccess("from Zoo zoo where zoo.class = example.PettingZoo"); } @Test public void testASTParserLoadingTestSpecialClassPropertyReferenceFQN_1322() { expectParserSuccess("select a.description from Animal a where a.class = example.Mammal"); } @Test public void testASTParserLoadingTestSpecialClassPropertyReferenceFQN_1323() { expectParserSuccess("from DomesticAnimal an where an.class = example.Dog"); } @Test public void testASTParserLoadingTestSpecialClassPropertyReferenceFQN_1324() { expectParserSuccess("from Animal an where an.class = example.Dog"); } @Test public void testASTParserLoadingTestSubclassOrSuperclassPropertyReferenceInJoinedSubclass_1326() { expectParserSuccess("from Zoo z join z.mammals as m where m.name.first = 'John'"); } @Test public void testASTParserLoadingTestSubclassOrSuperclassPropertyReferenceInJoinedSubclass_1327() { expectParserSuccess("from Zoo z join z.mammals as m where m.pregnant = false"); } @Test public void testASTParserLoadingTestSubclassOrSuperclassPropertyReferenceInJoinedSubclass_1328() { expectParserSuccess("select m.pregnant from Zoo z join z.mammals as m where m.pregnant = false"); } @Test public void testASTParserLoadingTestSubclassOrSuperclassPropertyReferenceInJoinedSubclass_1329() { expectParserSuccess("from Zoo z join z.mammals as m where m.description = 'tabby'"); } @Test public void testASTParserLoadingTestSubclassOrSuperclassPropertyReferenceInJoinedSubclass_1330() { expectParserSuccess("select m.description from Zoo z join z.mammals as m where m.description = 'tabby'"); } @Test public void testASTParserLoadingTestSubclassOrSuperclassPropertyReferenceInJoinedSubclass_1331() { expectParserSuccess("select m.name from Zoo z join z.mammals as m where m.name.first = 'John'"); } @Test public void testASTParserLoadingTestSubclassOrSuperclassPropertyReferenceInJoinedSubclass_1332() { expectParserSuccess("select m.pregnant from Zoo z join z.mammals as m"); } @Test public void testASTParserLoadingTestSubclassOrSuperclassPropertyReferenceInJoinedSubclass_1333() { expectParserSuccess("select m.description from Zoo z join z.mammals as m"); } @Test public void testASTParserLoadingTestSubclassOrSuperclassPropertyReferenceInJoinedSubclass_1334() { expectParserSuccess("select m.name from Zoo z join z.mammals as m"); } @Test public void testASTParserLoadingTestSubclassOrSuperclassPropertyReferenceInJoinedSubclass_1335() { expectParserSuccess("from DomesticAnimal da join da.owner as o where o.nickName = 'Gavin'"); } @Test public void testASTParserLoadingTestSubclassOrSuperclassPropertyReferenceInJoinedSubclass_1336() { expectParserSuccess("select da.father from DomesticAnimal da join da.owner as o where o.nickName = 'Gavin'"); } @Test public void testASTParserLoadingTestJPAPositionalParameterList_1338() { expectParserSuccess("from Human where name.last in (?1)"); } @Test public void testASTParserLoadingTestComponentQueries_1340() { expectParserSuccess("select h.name from Human h"); } @Test public void testASTParserLoadingTestComponentQueries_1341() { expectParserSuccess("from Human h where h.name = h.name"); } @Test public void testASTParserLoadingTestComponentQueries_1342() { expectParserSuccess("from Human h where h.name = :name"); } @Test public void testASTParserLoadingTestComponentQueries_1343() { expectParserSuccess("from Human where name = :name"); } @Test public void testASTParserLoadingTestComponentQueries_1344() { expectParserSuccess("from Human h where :name = h.name"); } @Test public void testASTParserLoadingTestComponentQueries_1345() { expectParserSuccess("from Human h where :name <> h.name"); } @Test public void testASTParserLoadingTestComponentQueries_1346() { expectParserSuccess("from Human h where h.name = ('John', 'X', 'Doe')"); } @Test public void testASTParserLoadingTestComponentQueries_1347() { expectParserSuccess("from Human h where ('John', 'X', 'Doe') = h.name"); } @Test public void testASTParserLoadingTestComponentQueries_1348() { expectParserSuccess("from Human h where ('John', 'X', 'Doe') <> h.name"); } @Test public void testASTParserLoadingTestComponentQueries_1349() { expectParserSuccess("from Human h where ('John', 'X', 'Doe') >= h.name"); } @Test public void testASTParserLoadingTestComponentQueries_1350() { expectParserSuccess("from Human h order by h.name"); } @Test public void testASTParserLoadingTestComponentParameterBinding_1352() { expectParserSuccess("from Order o where o.customer.name =:name and o.id = :id"); } @Test public void testASTParserLoadingTestComponentParameterBinding_1353() { expectParserSuccess("from Order o where o.id = :id and o.customer.name =:name "); } @Test public void testASTParserLoadingTestAnyMappingReference_1355() { expectParserSuccess("from PropertySet p where p.someSpecificProperty = :ssp"); } @Test public void testASTParserLoadingTestJdkEnumStyleEnumConstant_1357() { expectParserSuccess("from Zoo z where z.classification = example.Classification.LAME"); } @Test public void testASTParserLoadingTestParameterTypeMismatchFailureExpected_1359() { expectParserSuccess("from Animal a where a.description = :nonstring"); } @Test public void testASTParserLoadingTestMultipleBagFetchesFail_1361() { expectParserSuccess("from Human h join fetch h.friends f join fetch f.friends fof"); } @Test public void testASTParserLoadingTestCollectionFetchWithDistinctionAndLimit_1366() { expectParserSuccess("select distinct p from Animal p inner join fetch p.offspring"); } @Test public void testASTParserLoadingTestCollectionFetchWithDistinctionAndLimit_1367() { expectParserSuccess("select p from Animal p inner join fetch p.offspring order by p.id"); } @Test public void testASTParserLoadingTestQueryMetadataRetrievalWithFetching_1371() { expectParserSuccess("from Animal a inner join fetch a.mother"); } @Test public void testASTParserLoadingTestSuperclassPropertyReferenceAfterCollectionIndexedAccess_1373() { expectParserSuccess("from Zoo zoo where zoo.mammals['tiger'].mother.bodyWeight > 3.0f"); } @Test public void testASTParserLoadingTestJoinFetchCollectionOfValues_1375() { expectParserSuccess("select h from Human as h join fetch h.nickNames"); } @Test public void testASTParserLoadingTestIntegerLiterals_1377() { expectParserSuccess("from Foo where long = 1"); } @Test public void testASTParserLoadingTestIntegerLiterals_1378() { expectParserSuccess("from Foo where long = 1L"); } @Test public void testASTParserLoadingTestDecimalLiterals_1380() { expectParserSuccess("from Animal where bodyWeight > 100.0e-10"); } @Test public void testASTParserLoadingTestDecimalLiterals_1381() { expectParserSuccess("from Animal where bodyWeight > 100.0E-10"); } @Test public void testASTParserLoadingTestDecimalLiterals_1382() { expectParserSuccess("from Animal where bodyWeight > 100.001f"); } @Test public void testASTParserLoadingTestDecimalLiterals_1383() { expectParserSuccess("from Animal where bodyWeight > 100.001F"); } @Test public void testASTParserLoadingTestDecimalLiterals_1384() { expectParserSuccess("from Animal where bodyWeight > 100.001d"); } @Test public void testASTParserLoadingTestDecimalLiterals_1385() { expectParserSuccess("from Animal where bodyWeight > 100.001D"); } @Test public void testASTParserLoadingTestDecimalLiterals_1386() { expectParserSuccess("from Animal where bodyWeight > .001f"); } @Test public void testASTParserLoadingTestDecimalLiterals_1387() { expectParserSuccess("from Animal where bodyWeight > 100e-10"); } @Test public void testASTParserLoadingTestDecimalLiterals_1388() { expectParserSuccess("from Animal where bodyWeight > .01E-10"); } @Test public void testASTParserLoadingTestDecimalLiterals_1389() { expectParserSuccess("from Animal where bodyWeight > 1e-38"); } @Test public void testASTParserLoadingTestNakedPropertyRef_1391() { expectParserSuccess("from Animal where bodyWeight = bodyWeight"); } @Test public void testASTParserLoadingTestNakedPropertyRef_1392() { expectParserSuccess("select bodyWeight from Animal"); } @Test public void testASTParserLoadingTestNakedPropertyRef_1393() { expectParserSuccess("select max(bodyWeight) from Animal"); } @Test public void testASTParserLoadingTestNakedComponentPropertyRef_1395() { expectParserSuccess("select name from Human"); } @Test public void testASTParserLoadingTestNakedImplicitJoins_1399() { expectParserSuccess("from Animal where mother.father.id = 1"); } @Test public void testASTParserLoadingTestNakedEntityAssociationReference_1401() { expectParserSuccess("from Animal where mother = :mother"); } @Test public void testASTParserLoadingTestNakedMapIndex_1403() { expectParserSuccess("from Zoo where mammals['dog'].description like '%black%'"); } @Test public void testASTParserLoadingTestInvalidFetchSemantics_1405() { expectParserSuccess("select mother from Human a left join fetch a.mother mother"); } @Test public void testASTParserLoadingTestArithmetic_1407() { expectParserSuccess("select 2 from Zoo"); } @Test public void testASTParserLoadingTestNestedCollectionFetch_1417() { expectParserSuccess("from Animal a left join fetch a.offspring o left join fetch o.offspring where a.mother.id = 1 order by a.description"); } @Test public void testASTParserLoadingTestNestedCollectionFetch_1418() { expectParserSuccess("from Zoo z left join fetch z.animals a left join fetch a.offspring where z.name ='MZ' order by a.description"); } @Test public void testASTParserLoadingTestNestedCollectionFetch_1419() { expectParserSuccess("from Human h left join fetch h.pets a left join fetch a.offspring where h.name.first ='Gavin' order by a.description"); } @Test public void testASTParserLoadingTestInitProxy_1424() { expectParserSuccess("from Animal a"); } @Test public void testASTParserLoadingTestSelectClauseImplicitJoin_1426() { expectParserSuccess("select distinct a.zoo from Animal a where a.zoo is not null"); } @Test public void testASTParserLoadingTestComponentOrderBy_1428() { expectParserSuccess("from Human as h order by h.name"); } @Test public void testASTParserLoadingTestAliases_1433() { expectParserSuccess("select a.bodyWeight as abw, a.description from Animal a"); } @Test public void testASTParserLoadingTestAliases_1434() { expectParserSuccess("select count(*), avg(a.bodyWeight) as avg from Animal a"); } @Test public void testASTParserLoadingTestParameterMixing_1436() { expectParserSuccess("from Animal a where a.description = ? and a.bodyWeight = ? or a.bodyWeight = :bw"); } @Test public void testASTParserLoadingTestOrdinalParameters_1438() { expectParserSuccess("from Animal a where a.description = :description and a.bodyWeight = :weight"); } @Test public void testASTParserLoadingTestOrdinalParameters_1439() { expectParserSuccess("from Animal a where a.bodyWeight in (?, ?)"); } @Test public void testASTParserLoadingTestIndexParams_1441() { expectParserSuccess("from Zoo zoo where zoo.mammals[:name] = :id"); } @Test public void testASTParserLoadingTestIndexParams_1442() { expectParserSuccess("from Zoo zoo where zoo.mammals[:name].bodyWeight > :w"); } @Test public void testASTParserLoadingTestIndexParams_1443() { expectParserSuccess("from Zoo zoo where zoo.animals[:sn].mother.bodyWeight < :mw"); } @Test public void testASTParserLoadingTestIndexParams_1444() { expectParserSuccess("from Zoo zoo where zoo.animals[:sn].description like :desc and zoo.animals[:sn].bodyWeight > :wmin and zoo.animals[:sn].bodyWeight < :wmax"); } @Test public void testASTParserLoadingTestIndexParams_1445() { expectParserSuccess("from Human where addresses[:type].city = :city and addresses[:type].country = :country"); } @Test public void testASTParserLoadingTestAggregation_1447() { expectParserSuccess("select sum(h.bodyWeight) from Human h"); } @Test public void testASTParserLoadingTestAggregation_1448() { expectParserSuccess("select avg(h.height) from Human h"); } @Test public void testASTParserLoadingTestAggregation_1449() { expectParserSuccess("select max(a.id) from Animal a"); } @Test public void testASTParserLoadingTestImplicitPolymorphism_1454() { expectParserSuccess("from java.lang.Comparable"); } @Test public void testASTParserLoadingTestImplicitPolymorphism_1455() { expectParserSuccess("from java.lang.Object"); } @Test public void testASTParserLoadingTestCoalesce_1457() { expectParserSuccess("from Human h where coalesce(h.nickName, h.name.first, h.name.last) = 'max'"); } @Test public void testASTParserLoadingTestCoalesce_1458() { expectParserSuccess("select nullif(nickName, '1e1') from Human"); } @Test public void testASTParserLoadingTestStr_1460() { expectParserSuccess("select str(an.bodyWeight) from Animal an where str(an.bodyWeight) like '%1%'"); } @Test public void testASTParserLoadingTestStr_1461() { expectParserSuccess("select str(an.bodyWeight, 8, 3) from Animal an where str(an.bodyWeight, 8, 3) like '%1%'"); } @Test public void testASTParserLoadingTestCast_1465() { expectParserSuccess("from Human h where h.nickName like 'G%'"); } @Test public void testASTParserLoadingTestSelectExpressions_1477() { expectParserSuccess("select a.bodyWeight from Animal a join a.mother m"); } @Test public void testASTParserLoadingTestSelectExpressions_1479() { expectParserSuccess("select sum(a.bodyWeight) from Animal a join a.mother m"); } @Test public void testASTParserLoadingTestSelectExpressions_1481() { expectParserSuccess("select concat(h.name.first, ' ', h.name.initial, ' ', h.name.last) from Human h"); } @Test public void testASTParserLoadingTestSelectExpressions_1483() { expectParserSuccess("select nickName from Human"); } @Test public void testASTParserLoadingTestSelectExpressions_1485() { expectParserSuccess("select abs(bodyWeight) from Human"); } @Test public void testASTParserLoadingTestSelectExpressions_1491() { expectParserSuccess("select sum(abs(bodyWeight)) from Animal"); } @Test public void testASTParserLoadingTestImplicitJoin_1493() { expectParserSuccess("from Animal a where a.mother.bodyWeight < 2.0 or a.mother.bodyWeight > 9.0"); } @Test public void testASTParserLoadingTestImplicitJoin_1494() { expectParserSuccess("from Animal a where a.mother.bodyWeight > 2.0 and a.mother.bodyWeight > 9.0"); } @Test public void testASTParserLoadingTestSimpleSelect_1496() { expectParserSuccess("select a.mother from Animal as a"); } @Test public void testASTParserLoadingTestWhere_1498() { expectParserSuccess("from Animal an where an.bodyWeight > 10"); } @Test public void testASTParserLoadingTestWhere_1499() { expectParserSuccess("from Animal an where not an.bodyWeight > 10"); } @Test public void testASTParserLoadingTestWhere_1500() { expectParserSuccess("from Animal an where an.bodyWeight between 0 and 10"); } @Test public void testASTParserLoadingTestWhere_1501() { expectParserSuccess("from Animal an where an.bodyWeight not between 0 and 10"); } @Test public void testASTParserLoadingTestWhere_1503() { expectParserSuccess("from Animal an where (an.bodyWeight > 10 and an.bodyWeight < 100) or an.bodyWeight is null", "(QUERY (QUERY_SPEC (SELECT_FROM (from (PERSISTER_SPACE (ENTITY_PERSISTER_REF Animal an))) (SELECT (SELECT_LIST (SELECT_ITEM an)))) (where (or (and (> (PATH (. an bodyWeight)) 10) (< (PATH (. an bodyWeight)) 100)) (is null (PATH (. an bodyWeight)))))))"); } @Test public void testASTParserLoadingTestEntityFetching_1505() { expectParserSuccess("from Animal an join fetch an.mother"); } @Test public void testASTParserLoadingTestEntityFetching_1506() { expectParserSuccess("select an from Animal an join fetch an.mother"); } @Test public void testASTParserLoadingTestCollectionFetching_1508() { expectParserSuccess("from Animal an join fetch an.offspring"); } @Test public void testASTParserLoadingTestCollectionFetching_1509() { expectParserSuccess("select an from Animal an join fetch an.offspring"); } @Test public void testASTParserLoadingTestProjectionQueries_1511() { expectParserSuccess("select an.mother.id, max(an.bodyWeight) from Animal an group by an.mother.id"); } @Test public void testASTParserLoadingTestResultTransformerScalarQueries_1519() { expectParserSuccess("select an.description as description, an.bodyWeight as bodyWeight from Animal an order by bodyWeight desc"); } @Test public void testASTParserLoadingTestResultTransformerScalarQueries_1520() { expectParserSuccess("select a from Animal a, Animal b order by a.id"); } @Test public void testASTParserLoadingTestResultTransformerEntityQueries_1522() { expectParserSuccess("select an as an from Animal an order by bodyWeight desc"); } @Test public void testASTParserLoadingTestEJBQLFunctions_1524() { expectParserSuccess("from Animal a where a.description = concat('1', concat('2','3'), '45')"); } @Test public void testASTParserLoadingTestEJBQLFunctions_1525() { expectParserSuccess("from Animal a where substring(a.description, 1, 3) = 'cat'"); } @Test public void testASTParserLoadingTestEJBQLFunctions_1529() { expectParserSuccess("from Animal a where length(a.description) = 5"); } @Test public void testASTParserLoadingTestEJBQLFunctions_1530() { expectParserSuccess("from Animal a where locate('abc', a.description, 2) = 2"); } @Test public void testASTParserLoadingTestEJBQLFunctions_1531() { expectParserSuccess("from Animal a where locate('abc', a.description) = 2"); } @Test public void testASTParserLoadingTestEJBQLFunctions_1532() { expectParserSuccess("select locate('cat', a.description, 2) from Animal a"); } @Test public void testASTParserLoadingTestEJBQLFunctions_1541() { expectParserSuccess("from Animal a where a.description like '%a%'"); } @Test public void testASTParserLoadingTestEJBQLFunctions_1542() { expectParserSuccess("from Animal a where a.description not like '%a%'"); } @Test public void testASTParserLoadingTestEJBQLFunctions_1543() { expectParserSuccess("from Animal a where a.description like 'x%ax%' escape 'x'"); } @Test public void testASTParserLoadingTestSubselectBetween_1546() { expectParserSuccess("from Animal x where (x.name, x.bodyWeight) = ('cat', 20)"); } @Test public void testHQLPARSER_71_1548() { expectParserSuccess("select p from pppoe_test p where p.sourceIP=:source_ip and p.login>:logentrytime and (p.logout>:logentrytime OR p.logout IS NULL)"); } @Test public void testHQLPARSER_71_1549() { expectParserSuccess("select a from Animal a where TrUE"); } @Test public void testHQLPARSER_71_1550() { expectParserSuccess("select a from eg.Animal a where FALSE"); } }
133,549
31.018701
328
java
null
infinispan-main/object-filter/src/test/java/org/infinispan/objectfilter/impl/ql/test/LexerTest.java
/* * Copyright 2016, Red Hat Inc. and/or its affiliates. * * 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 org.infinispan.objectfilter.impl.ql.test; import org.junit.Test; /** * @author anistor@redhat.com * @since 9.0 */ public class LexerTest extends TestBase { @Test public void testGreaterEqual() { // todo [anistor] it's also possible to invoke method mGREATER_EQUAL() of lexer directly instead of nextToken() expectLexerSuccess(">=", "GREATER_EQUAL"); } @Test public void testIdentifier() { expectLexerSuccess("acme", "IDENTIFIER"); expectLexerFailure("1cme"); } @Test public void testFloatingPointLiteral() { expectLexerSuccess(".12e+10", "FLOATING_POINT_LITERAL"); expectLexerFailure(".12e+-10"); } @Test public void testNull() { expectLexerSuccess("null", "NULL"); expectLexerSuccess("NULL", "NULL"); expectLexerSuccess("NuLl", "NULL"); } @Test public void testFalse() { expectLexerSuccess("false", "FALSE"); expectLexerSuccess("FALSE", "FALSE"); expectLexerSuccess("FaLse", "FALSE"); } @Test public void testTrue() { expectLexerSuccess("true", "TRUE"); expectLexerSuccess("TRUE", "TRUE"); expectLexerSuccess("TrUe", "TRUE"); } }
1,814
26.923077
117
java
null
infinispan-main/object-filter/src/test/java/org/infinispan/objectfilter/impl/ql/test/ParserTest.java
/* * Copyright 2016, Red Hat Inc. and/or its affiliates. * * 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 org.infinispan.objectfilter.impl.ql.test; import org.junit.Test; public class ParserTest extends TestBase { @Test public void testFromNote1() { expectParserSuccess("from Note n where ! n.text = 'foo'", "(QUERY (QUERY_SPEC (SELECT_FROM (from (PERSISTER_SPACE (ENTITY_PERSISTER_REF Note n))) (SELECT (SELECT_LIST (SELECT_ITEM n)))) " + "(where (! (= (PATH (. n text)) (CONST_STRING_VALUE foo))))))"); expectParserSuccess("from Note n where ! (n.text = 'foo')", "(QUERY (QUERY_SPEC (SELECT_FROM (from (PERSISTER_SPACE (ENTITY_PERSISTER_REF Note n))) (SELECT (SELECT_LIST (SELECT_ITEM n)))) " + "(where (! (= (PATH (. n text)) (CONST_STRING_VALUE foo))))))"); expectParserSuccess("from Note n where not n.text = 'foo'", "(QUERY (QUERY_SPEC (SELECT_FROM (from (PERSISTER_SPACE (ENTITY_PERSISTER_REF Note n))) (SELECT (SELECT_LIST (SELECT_ITEM n)))) " + "(where (not (= (PATH (. n text)) (CONST_STRING_VALUE foo))))))"); expectParserSuccess("from Note n where not (n.text = 'foo')", "(QUERY (QUERY_SPEC (SELECT_FROM (from (PERSISTER_SPACE (ENTITY_PERSISTER_REF Note n))) (SELECT (SELECT_LIST (SELECT_ITEM n)))) " + "(where (not (= (PATH (. n text)) (CONST_STRING_VALUE foo))))))"); } @Test public void testFromNote2() { expectParserSuccess("from Note where text : 'bar'", "(QUERY (QUERY_SPEC (SELECT_FROM (from (PERSISTER_SPACE (ENTITY_PERSISTER_REF Note <gen:0>))) (SELECT (SELECT_LIST (SELECT_ITEM <gen:0>)))) " + "(where (: (PATH text) (FT_TERM (CONST_STRING_VALUE bar))))))"); expectParserSuccess("from Note where #text : 'bar'", "(QUERY (QUERY_SPEC (SELECT_FROM (from (PERSISTER_SPACE (ENTITY_PERSISTER_REF Note <gen:0>))) (SELECT (SELECT_LIST (SELECT_ITEM <gen:0>)))) " + "(where (: (PATH text) (# (FT_TERM (CONST_STRING_VALUE bar)))))))"); expectParserSuccess("from Note where text : ('bar')", "(QUERY (QUERY_SPEC (SELECT_FROM (from (PERSISTER_SPACE (ENTITY_PERSISTER_REF Note <gen:0>))) (SELECT (SELECT_LIST (SELECT_ITEM <gen:0>)))) " + "(where (: (PATH text) (FT_TERM (CONST_STRING_VALUE bar))))))"); expectParserSuccess("from Note n where - n.text : (-'foo' +'bar')", "(QUERY (QUERY_SPEC (SELECT_FROM (from (PERSISTER_SPACE (ENTITY_PERSISTER_REF Note n))) (SELECT (SELECT_LIST (SELECT_ITEM n)))) " + "(where (: (PATH (. n text)) (- (OR (- (FT_TERM (CONST_STRING_VALUE foo))) (+ (FT_TERM (CONST_STRING_VALUE bar)))))))))"); expectParserSuccess("from Note n where not n.text : (-'foo' +'bar')", "(QUERY (QUERY_SPEC (SELECT_FROM (from (PERSISTER_SPACE (ENTITY_PERSISTER_REF Note n))) (SELECT (SELECT_LIST (SELECT_ITEM n)))) " + "(where (not (: (PATH (. n text)) (OR (- (FT_TERM (CONST_STRING_VALUE foo))) (+ (FT_TERM (CONST_STRING_VALUE bar)))))))))"); } @Test public void testFromNote3() { expectParserSuccess("from Note n where ! n.text : (-'foo' +'bar')", "(QUERY (QUERY_SPEC (SELECT_FROM (from (PERSISTER_SPACE (ENTITY_PERSISTER_REF Note n))) (SELECT (SELECT_LIST (SELECT_ITEM n)))) " + "(where (! (: (PATH (. n text)) (OR (- (FT_TERM (CONST_STRING_VALUE foo))) (+ (FT_TERM (CONST_STRING_VALUE bar)))))))))"); } @Test public void testFromNote4() { expectParserSuccess("from Note n where + n.text : 'foo'", "(QUERY (QUERY_SPEC (SELECT_FROM (from (PERSISTER_SPACE (ENTITY_PERSISTER_REF Note n))) (SELECT (SELECT_LIST (SELECT_ITEM n)))) " + "(where (: (PATH (. n text)) (+ (FT_TERM (CONST_STRING_VALUE foo)))))))"); } @Test public void testFromAnimal() { //generated alias: expectParserSuccess("from Animal", "(QUERY (QUERY_SPEC (SELECT_FROM (from (PERSISTER_SPACE (ENTITY_PERSISTER_REF Animal <gen:0>))) (SELECT (SELECT_LIST (SELECT_ITEM <gen:0>))))))"); } @Test public void testSuperSimpleQuery() { //generated alias: expectParserSuccess("from EntityName", "(QUERY (QUERY_SPEC (SELECT_FROM (from (PERSISTER_SPACE (ENTITY_PERSISTER_REF EntityName <gen:0>))) (SELECT (SELECT_LIST (SELECT_ITEM <gen:0>))))))"); } @Test public void testSimpleQuery() { //full selection with specified alias: expectParserSuccess("select e from com. acme . EntityName e", "(QUERY (QUERY_SPEC (SELECT_FROM (from (PERSISTER_SPACE (ENTITY_PERSISTER_REF com.acme.EntityName e))) (select (SELECT_LIST (SELECT_ITEM (PATH e)))))))"); } @Test public void testSimpleFromQuery() { //abbreviated form: expectParserSuccess("from com.acme.EntityName e", "(QUERY (QUERY_SPEC (SELECT_FROM (from (PERSISTER_SPACE (ENTITY_PERSISTER_REF com.acme.EntityName e))) (SELECT (SELECT_LIST (SELECT_ITEM e))))))"); } @Test public void testSimpleQueryDefaultContext() { //generated alias: expectParserSuccess("from com.acme.EntityName e", "(QUERY (QUERY_SPEC (SELECT_FROM (from (PERSISTER_SPACE (ENTITY_PERSISTER_REF com.acme.EntityName e))) (SELECT (SELECT_LIST (SELECT_ITEM e))))))"); } @Test public void testOneCriteriaQuery() { //generated alias: expectParserSuccess("from com.acme.EntityName e where e.name = 'same'", "(QUERY (QUERY_SPEC (SELECT_FROM (from (PERSISTER_SPACE (ENTITY_PERSISTER_REF com.acme.EntityName e))) (SELECT (SELECT_LIST (SELECT_ITEM e)))) (where (= (PATH (. e name)) (CONST_STRING_VALUE same)))))"); } @Test public void testOrderByAsc() { //generated alias: expectParserSuccess("from com.acme.EntityName e order by e.name asc", "(QUERY (QUERY_SPEC (SELECT_FROM (from (PERSISTER_SPACE (ENTITY_PERSISTER_REF com.acme.EntityName e))) (SELECT (SELECT_LIST (SELECT_ITEM e))))) (order (SORT_SPEC (PATH (. e name)) asc)))"); } @Test public void testOrderByDefault() { //generated alias: expectParserSuccess("from com.acme.EntityName e order by e.name", "(QUERY (QUERY_SPEC (SELECT_FROM (from (PERSISTER_SPACE (ENTITY_PERSISTER_REF com.acme.EntityName e))) (SELECT (SELECT_LIST (SELECT_ITEM e))))) (order (SORT_SPEC (PATH (. e name)) asc)))"); } @Test public void testOrderByDesc() { //generated alias: expectParserSuccess("from com.acme.EntityName e order by e.name DESC", "(QUERY (QUERY_SPEC (SELECT_FROM (from (PERSISTER_SPACE (ENTITY_PERSISTER_REF com.acme.EntityName e))) (SELECT (SELECT_LIST (SELECT_ITEM e))))) (order (SORT_SPEC (PATH (. e name)) desc)))"); } @Test public void testStringLiteralSingleQuoteEscape() { //generated alias: expectParserSuccess("from com.acme.EntityName e where e.name = 'Jack Daniel''s Old No. 7'", "(QUERY (QUERY_SPEC (SELECT_FROM (from (PERSISTER_SPACE (ENTITY_PERSISTER_REF com.acme.EntityName e))) (SELECT (SELECT_LIST (SELECT_ITEM e)))) (where (= (PATH (. e name)) (CONST_STRING_VALUE Jack Daniel's Old No. 7)))))"); } @Test public void testJoinOnEmbedded() { //generated alias: expectParserSuccess("SELECT e.author.name FROM IndexedEntity e JOIN e.contactDetails d JOIN e.alternativeContactDetails a WHERE d.address.postCode='EA123' AND a.email='mail@mail.af'", "(QUERY (QUERY_SPEC (SELECT_FROM (FROM (PERSISTER_SPACE (ENTITY_PERSISTER_REF IndexedEntity e) (property-join INNER d (PATH (. e contactDetails))) (property-join INNER a (PATH (. e alternativeContactDetails))))) (SELECT (SELECT_LIST (SELECT_ITEM (PATH (. (. e author) name)))))) (WHERE (AND (= (PATH (. (. d address) postCode)) (CONST_STRING_VALUE EA123)) (= (PATH (. a email)) (CONST_STRING_VALUE mail@mail.af))))))"); } @Test public void testProjectionOnEmbeddedAndUnqualifiedProperties() { //generated alias: expectParserSuccess("SELECT name, text, e.author.name FROM IndexedEntity e JOIN e.contactDetails d", "(QUERY (QUERY_SPEC (SELECT_FROM (FROM (PERSISTER_SPACE (ENTITY_PERSISTER_REF IndexedEntity e) (property-join INNER d (PATH (. e contactDetails))))) (SELECT (SELECT_LIST (SELECT_ITEM (PATH name)) (SELECT_ITEM (PATH text)) (SELECT_ITEM (PATH (. (. e author) name))))))))"); } @Test public void testNamedParam() { expectParserSuccess("FROM IndexedEntity e where e.name = :nameParam", "(QUERY (QUERY_SPEC (SELECT_FROM (FROM (PERSISTER_SPACE (ENTITY_PERSISTER_REF IndexedEntity e))) (SELECT (SELECT_LIST (SELECT_ITEM e)))) (where (= (PATH (. e name)) nameParam))))"); } }
9,272
54.196429
431
java
null
infinispan-main/object-filter/src/test/java/org/infinispan/objectfilter/impl/ql/test/TestBase.java
/* * Copyright 2016, Red Hat Inc. and/or its affiliates. * * 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 org.infinispan.objectfilter.impl.ql.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.lang.reflect.Field; import java.util.List; import org.antlr.runtime.ANTLRStringStream; import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.Token; import org.antlr.runtime.tree.CommonTree; import org.infinispan.objectfilter.impl.ql.parse.IckleLexer; import org.infinispan.objectfilter.impl.ql.parse.IckleParser; /** * Common utilities for testing the parser and lexer. * * @author anistor@redhat.com * @since 9.0 */ abstract class TestBase { protected void expectParserSuccess(String inputText) { parse(inputText, false, null, false); } protected void expectParserSuccess(String inputText, String expectedOut) { parse(inputText, false, expectedOut, false); } protected void expectParserFailure(String inputText) { parse(inputText, true, null, false); } protected void expectLexerSuccess(String inputText) { parse(inputText, false, null, true); } protected void expectLexerSuccess(String inputText, String expectedOut) { parse(inputText, false, expectedOut, true); } protected void expectLexerFailure(String inputText) { parse(inputText, true, null, true); } private void parse(String inputText, boolean expectFailure, String expectedTreeOut, boolean lexerOnly) { if (expectFailure && expectedTreeOut != null) { throw new IllegalArgumentException("If failure is expected then expectedTreeOut must be null"); } IckleLexer lexer = new IckleLexer(new ANTLRStringStream(inputText)); CommonTokenStream tokens = new CommonTokenStream(lexer); try { ByteArrayOutputStream errorStream = new ByteArrayOutputStream(); Token token = null; CommonTree tree = null; if (lexerOnly) { lexer.setErrStream(new PrintStream(errorStream)); token = lexer.nextToken(); } else { IckleParser parser = new IckleParser(tokens); parser.setErrStream(new PrintStream(errorStream)); IckleParser.statement_return statement = parser.statement(); tree = (CommonTree) statement.getTree(); } String errMsg = errorStream.size() > 0 ? errorStream.toString() : null; if (errMsg != null) { // we have an error message if (expectFailure) { return; } else { fail(errMsg); } } if (expectedTreeOut != null) { if (lexerOnly) { int expectedTokenType; try { // expectedTreeOut is assumed to be a token name Field tokenTypeConstant = lexer.getClass().getDeclaredField(expectedTreeOut); expectedTokenType = (Integer) tokenTypeConstant.get(null); } catch (IllegalAccessException | NoSuchFieldException e) { throw new RuntimeException("Could not determine the type of token: " + expectedTreeOut, e); } assertEquals("Token type", expectedTokenType, token.getType()); } else { assertEquals(expectedTreeOut, tree.toStringTree()); } } String unconsumedTokens = getUnconsumedTokens(tokens); if (unconsumedTokens != null) { if (expectFailure) { return; } else { fail("Found unconsumed tokens: \"" + unconsumedTokens + "\"."); } } } catch (Exception e) { if (expectFailure) { return; } else { fail(e.getMessage()); } } if (expectFailure) { fail("Parsing was expected to fail but it actually succeeded."); } } private String getUnconsumedTokens(CommonTokenStream tokens) { // ensure we've buffered all tokens from the underlying TokenSource tokens.fill(); if (tokens.index() == tokens.size() - 1) { return null; } StringBuilder sb = new StringBuilder(); @SuppressWarnings("unchecked") List<Token> unconsumed = (List<Token>) tokens.getTokens(tokens.index(), tokens.size() - 1); for (Token t : unconsumed) { if (t.getType() != Token.EOF) { sb.append(t.getText()); } } return sb.length() > 0 ? sb.toString() : null; } }
5,175
32.393548
109
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/package-info.java
/** * Querying on plain Java objects. * * @author anistor@redhat.com * @since 7.0 * * @api.public */ package org.infinispan.objectfilter;
145
13.6
36
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/ParsingException.java
package org.infinispan.objectfilter; /** * Thrown in case of syntax errors during parsing or during the processing of the parse tree. * * @author anistor@redhat.com * @since 9.0 */ public class ParsingException extends RuntimeException { public ParsingException(String message) { super(message); } public ParsingException(Throwable cause) { super(cause); } public ParsingException(String message, Throwable cause) { super(message, cause); } }
488
20.26087
93
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/SortField.java
package org.infinispan.objectfilter; import org.infinispan.objectfilter.impl.ql.PropertyPath; /** * Sort specification for a field. * * @author anistor@redhat.com * @since 7.0 */ public interface SortField { /** * The field path. */ PropertyPath<?> getPath(); /** * Indicates if sorting is ascending or descending. */ boolean isAscending(); }
380
15.565217
56
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/FilterCallback.java
package org.infinispan.objectfilter; /** * A single-method callback that is specified when registering a filter with a Matcher. The {@link #onFilterResult} * method is notified of all instances that were presented to {@link Matcher#match} and successfully matched the filter * associated with this callback. The callback will receive the instance being matched, the projected fields (optional, * if specified) and the 'order by' projections (optional, if specified). The 'order by' projection is an array of * {@link java.lang.Comparable} that can be compared using the {@link java.util.Comparator} provided by {@link * FilterSubscription#getComparator()}. * <p/> * Implementations of this interface are provided by the subscriber and must written is such a way that they can be * invoked from multiple threads simultaneously. * * @author anistor@redhat.com * @since 7.0 */ @FunctionalInterface public interface FilterCallback { /** * Receives notification that an instance matches the filter. * * @param userContext the optional user context object passed to {@link Matcher#match} * @param eventType the optional event type discriminator object passed to {@link Matcher#match} * @param instance the object being matched * @param projection the projection, if a projection was requested or {@code null} otherwise * @param sortProjection the projection of fields used for sorting, if sorting was requested or {@code null} * otherwise */ void onFilterResult(Object userContext, Object eventType, Object instance, Object[] projection, Comparable[] sortProjection); }
1,661
50.9375
128
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/ObjectFilter.java
package org.infinispan.objectfilter; import java.util.Comparator; import java.util.Map; import java.util.Set; /** * A filter that tests if an object matches a pre-defined condition and returns either the original instance or the * projection, depending on how the filter was created. The projection is represented as an Object[]. If the given * instance does not match the filter will just return null. * * @author anistor@redhat.com * @since 7.0 */ public interface ObjectFilter { /** * The fully qualified entity type name accepted by this filter. */ String getEntityTypeName(); /** * The array of '.' separated path names of the projected fields if any, or {@code null} otherwise. */ String[] getProjection(); /** * The types of the projects paths (see {@link #getProjection()} or {@code null} if there are no projections. */ Class<?>[] getProjectionTypes(); /** * Returns the filter parameter names or an empty {@link Set} if there are no parameters. */ Set<String> getParameterNames(); /** * The parameter values. Please do not mutate this map. Obtain a new filter instance with new parameter values using * {@link #withParameters(Map)} if you have to. */ Map<String, Object> getParameters(); /** * Creates a new ObjectFilter instance based on the current one and the given parameter values. */ ObjectFilter withParameters(Map<String, Object> namedParameters); /** * The array of sort specifications if defined, or {@code null} otherwise. */ SortField[] getSortFields(); /** * The comparator corresponding to the 'order by' clause, if any. * * @return the Comparator or {@code null} if no 'order by' was specified ({@link #getSortFields()} also returns * {@code null}) */ Comparator<Comparable<?>[]> getComparator(); /** * Tests if an object matches the filter. A shorthand for {@code filter(null, value)}. * * @param value the instance to test; this is never {@code null} * @return a {@link FilterResult} if there is a match or {@code null} otherwise */ default FilterResult filter(Object value) { return filter(null, value); } /** * Tests if an object matches the filter. The given key is optional (can be null) and will be returned to * the user in the {@link FilterResult}. * * @param key the (optional) key; this can be {@code null} if it is of no interest * @param value the instance to test; this is never {@code null} * @return a {@link FilterResult} if there is a match or {@code null} otherwise */ FilterResult filter(Object key, Object value); /** * The output of the {@link ObjectFilter#filter} method. */ interface FilterResult { /** * Returns the key of the matched object. This is optional. */ Object getKey(); /** * Returns the matched object. This is non-null unless projections are present. */ Object getInstance(); /** * Returns the projection, if a projection was requested or {@code null} otherwise. */ Object[] getProjection(); /** * Returns the projection of fields used for sorting, if sorting was requested or {@code null} otherwise. */ Comparable<?>[] getSortProjection(); } }
3,352
30.336449
119
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/Matcher.java
package org.infinispan.objectfilter; import java.util.List; import java.util.Map; import org.infinispan.objectfilter.impl.aggregation.FieldAccumulator; import org.infinispan.query.dsl.Query; /** * An object matcher able to test a given object against multiple registered filters specified either as Ickle queries * (a JP-QL subset with full-text support) or using the query DSL (see {@link org.infinispan.query.dsl}). The matching * filters are notified via a callback supplied when registering the filter. The filter will have to specify the fully * qualified type name of the matching entity type because simple names cannot be easily resolved as it would happen * in the case of an {@code javax.persistence.EntityManager} which has knowledge of all types in advance and is able to * translate simple names to fully qualified names unambiguously. * <p> * Full-text predicates are not supported at the moment. * <p> * This is a low-level interface which should not be directly used by Infinispan users. * * @author anistor@redhat.com * @since 7.0 */ public interface Matcher { FilterSubscription registerFilter(Query<?> query, FilterCallback callback, Object... eventType); FilterSubscription registerFilter(String queryString, Map<String, Object> namedParameters, FilterCallback callback, Object... eventType); FilterSubscription registerFilter(String queryString, FilterCallback callback, Object... eventType); FilterSubscription registerFilter(Query<?> query, FilterCallback callback, boolean isDeltaFilter, Object... eventType); FilterSubscription registerFilter(String queryString, Map<String, Object> namedParameters, FilterCallback callback, boolean isDeltaFilter, Object... eventType); FilterSubscription registerFilter(String queryString, FilterCallback callback, boolean isDeltaFilter, Object... eventType); void unregisterFilter(FilterSubscription filterSubscription); /** * Test the given instance against all the subscribed filters and notify all callbacks registered for instances of * the same instance type. The {@code isDelta} parameter of the callback will be {@code false}. * * @param userContext an optional user provided object to be passed to matching subscribers along with the matching * instance; can be {@code null} * @param eventType on optional event type discriminator that is matched against the event type specified when the * filter was registered; can be {@code null} * @param instance the object to test against the registered filters; never {@code null} */ void match(Object userContext, Object eventType, Object instance); /** * Test two instances (which are actually before/after snapshots of the same instance) against all the subscribed * filters and notify all callbacks registered for instances of the same instance type. The {@code isDelta} parameter * of the callback will be {@code true}. * * @param userContext an optional user provided object to be passed to matching subscribers along with the matching * instance; can be {@code null} * @param eventType on optional event type discriminator that is matched against the event type specified when the * filter was registered; can be {@code null} * @param instanceOld the 'before' object to test against the registered filters; never {@code null} * @param instanceNew the 'after' object to test against the registered filters; never {@code null} * @param joinEvent the event to generate if the instance joins the matching set * @param updateEvent the event to generate if a matching instance is updated and continues to the match * @param leaveEvent the event to generate if the instance leaves the matching set */ void matchDelta(Object userContext, Object eventType, Object instanceOld, Object instanceNew, Object joinEvent, Object updateEvent, Object leaveEvent); /** * Obtains an ObjectFilter instance that is capable of testing a single filter condition. * * @param filterSubscription a filter subscription previously registered with this Matcher; the newly created * ObjectFilter will be based on the same filter condition * @return the single-filter */ ObjectFilter getObjectFilter(FilterSubscription filterSubscription); ObjectFilter getObjectFilter(Query<?> query); ObjectFilter getObjectFilter(String queryString); ObjectFilter getObjectFilter(String queryString, List<FieldAccumulator> acc); }
4,606
53.845238
163
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/FilterSubscription.java
package org.infinispan.objectfilter; import java.util.Comparator; /** * A subscription for match notifications. * * @author anistor@redhat.com * @since 7.0 */ public interface FilterSubscription { /** * The fully qualified entity type name accepted by this filter. */ String getEntityTypeName(); /** * The associated callback that is being notified of successful matches. */ FilterCallback getCallback(); boolean isDeltaFilter(); /** * The array of '.' separated path names of the projected fields if any, or {@code null} otherwise. */ String[] getProjection(); /** * The array of sort specifications if defined, or {@code null} otherwise. */ SortField[] getSortFields(); /** * The comparator corresponding to the 'order by' clause, if any. * * @return the Comparator or {@code null} if no 'order by' was specified */ Comparator<Comparable<?>[]> getComparator(); /** * The event types. * * @return the array of event types or null */ Object[] getEventTypes(); }
1,079
21.040816
102
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/package-info.java
/** * Internal implementation package of org.infinispan.objectfilter functionality. * * @author anistor@redhat.com * @since 7.0 * * @api.private */ package org.infinispan.objectfilter.impl;
197
18.8
80
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/FilterRegistry.java
package org.infinispan.objectfilter.impl; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.infinispan.objectfilter.FilterCallback; import org.infinispan.objectfilter.FilterSubscription; import org.infinispan.objectfilter.SortField; import org.infinispan.objectfilter.impl.predicateindex.PredicateIndex; import org.infinispan.objectfilter.impl.predicateindex.be.BETree; import org.infinispan.objectfilter.impl.predicateindex.be.BETreeMaker; import org.infinispan.objectfilter.impl.syntax.BooleanExpr; import org.infinispan.objectfilter.impl.syntax.BooleanFilterNormalizer; import org.infinispan.objectfilter.impl.util.StringHelper; /** * A registry for filters on the same type of entity. * * @author anistor@redhat.com * @since 7.0 */ public final class FilterRegistry<TypeMetadata, AttributeMetadata, AttributeId extends Comparable<AttributeId>> { private final PredicateIndex<AttributeMetadata, AttributeId> predicateIndex; private final List<FilterSubscriptionImpl> filterSubscriptions = new ArrayList<>(); private final BooleanFilterNormalizer booleanFilterNormalizer = new BooleanFilterNormalizer(); private final BETreeMaker<AttributeId> treeMaker; private final MetadataAdapter<TypeMetadata, AttributeMetadata, AttributeId> metadataAdapter; private final boolean useIntervals; public FilterRegistry(MetadataAdapter<TypeMetadata, AttributeMetadata, AttributeId> metadataAdapter, boolean useIntervals) { this.metadataAdapter = metadataAdapter; this.useIntervals = useIntervals; treeMaker = new BETreeMaker<>(metadataAdapter, useIntervals); predicateIndex = new PredicateIndex<>(metadataAdapter); } public MetadataAdapter<TypeMetadata, AttributeMetadata, AttributeId> getMetadataAdapter() { return metadataAdapter; } public PredicateIndex<AttributeMetadata, AttributeId> getPredicateIndex() { return predicateIndex; } public List<FilterSubscriptionImpl> getFilterSubscriptions() { return filterSubscriptions; } public FilterSubscriptionImpl<TypeMetadata, AttributeMetadata, AttributeId> addFilter(String queryString, Map<String, Object> namedParameters, BooleanExpr query, String[] projection, Class<?>[] projectionTypes, SortField[] sortFields, FilterCallback callback, boolean isDeltaFilter, Object[] eventTypes) { if (eventTypes != null) { if (eventTypes.length == 0) { eventTypes = null; } else { for (Object et : eventTypes) { if (et == null) { eventTypes = null; break; } } } } List<List<AttributeId>> translatedProjections = null; if (projection != null && projection.length != 0) { translatedProjections = new ArrayList<>(projection.length); for (String projectionPath : projection) { translatedProjections.add(metadataAdapter.mapPropertyNamePathToFieldIdPath(StringHelper.split(projectionPath))); } } List<List<AttributeId>> translatedSortFields = null; if (sortFields != null) { // deduplicate sort fields LinkedHashMap<String, SortField> sortFieldMap = new LinkedHashMap<>(); for (SortField sf : sortFields) { String path = sf.getPath().asStringPath(); if (!sortFieldMap.containsKey(path)) { sortFieldMap.put(path, sf); } } sortFields = sortFieldMap.values().toArray(new SortField[sortFieldMap.size()]); // translate sort field paths translatedSortFields = new ArrayList<>(sortFields.length); for (SortField sortField : sortFields) { translatedSortFields.add(metadataAdapter.mapPropertyNamePathToFieldIdPath(sortField.getPath().asArrayPath())); } } BooleanExpr normalizedQuery = booleanFilterNormalizer.normalize(query); BETree beTree = treeMaker.make(normalizedQuery, namedParameters); FilterSubscriptionImpl<TypeMetadata, AttributeMetadata, AttributeId> filterSubscription = new FilterSubscriptionImpl<>(queryString, namedParameters, useIntervals, metadataAdapter, beTree, callback, isDeltaFilter, projection, projectionTypes, translatedProjections, sortFields, translatedSortFields, eventTypes); filterSubscription.registerProjection(predicateIndex); filterSubscription.subscribe(predicateIndex); filterSubscription.index = filterSubscriptions.size(); filterSubscriptions.add(filterSubscription); return filterSubscription; } public void removeFilter(FilterSubscription filterSubscription) { FilterSubscriptionImpl<TypeMetadata, AttributeMetadata, AttributeId> filterSubscriptionImpl = (FilterSubscriptionImpl<TypeMetadata, AttributeMetadata, AttributeId>) filterSubscription; filterSubscriptionImpl.unregisterProjection(predicateIndex); filterSubscriptionImpl.unsubscribe(predicateIndex); filterSubscriptions.remove(filterSubscriptionImpl); for (int i = filterSubscriptionImpl.index; i < filterSubscriptions.size(); i++) { filterSubscriptions.get(i).index--; } filterSubscriptionImpl.index = -1; } }
5,265
43.252101
317
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/RejectObjectFilter.java
package org.infinispan.objectfilter.impl; import java.util.Map; import org.infinispan.objectfilter.ObjectFilter; import org.infinispan.objectfilter.impl.syntax.parser.IckleParsingResult; /** * A filter that rejects all input. Ignores sorting and projection. * * @author anistor@redhat.com * @since 9.0 */ final class RejectObjectFilter<TypeMetadata> extends ObjectFilterBase<TypeMetadata> implements ObjectFilter { RejectObjectFilter(Map<String, Object> namedParameters, IckleParsingResult<TypeMetadata> parsingResult) { super(parsingResult, namedParameters); } @Override public ObjectFilter withParameters(Map<String, Object> namedParameters) { validateParameters(namedParameters); return new RejectObjectFilter<>(namedParameters, parsingResult); } @Override public FilterResult filter(Object key, Object value) { if (value == null) { throw new IllegalArgumentException("instance cannot be null"); } return null; } }
998
28.382353
109
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/RowMatcher.java
package org.infinispan.objectfilter.impl; import java.util.Collections; import java.util.List; import org.infinispan.objectfilter.impl.predicateindex.RowMatcherEvalContext; import org.infinispan.objectfilter.impl.syntax.parser.RowPropertyHelper; /** * A matcher for projection rows (Object[]). This matcher is not stateless so it cannot be reused. * * @author anistor@redhat.com * @since 8.0 */ public final class RowMatcher extends BaseMatcher<RowPropertyHelper.RowMetadata, RowPropertyHelper.ColumnMetadata, Integer> { private final RowPropertyHelper.RowMetadata rowMetadata; public RowMatcher(RowPropertyHelper.ColumnMetadata[] columns) { super(new RowPropertyHelper(columns)); rowMetadata = ((RowPropertyHelper) propertyHelper).getRowMetadata(); } @Override protected RowMatcherEvalContext startMultiTypeContext(boolean isDeltaFilter, Object userContext, Object eventType, Object instance) { FilterRegistry<RowPropertyHelper.RowMetadata, RowPropertyHelper.ColumnMetadata, Integer> filterRegistry = getFilterRegistryForType(isDeltaFilter, rowMetadata); if (filterRegistry != null) { RowMatcherEvalContext context = new RowMatcherEvalContext(userContext, eventType, null, instance, rowMetadata); context.initMultiFilterContext(filterRegistry); return context; } return null; } @Override protected RowMatcherEvalContext startSingleTypeContext(Object userContext, Object eventType, Object key, Object instance, MetadataAdapter<RowPropertyHelper.RowMetadata, RowPropertyHelper.ColumnMetadata, Integer> metadataAdapter) { if (Object[].class == instance.getClass()) { return new RowMatcherEvalContext(userContext, eventType, key, instance, rowMetadata); } else { return null; } } @Override protected MetadataAdapter<RowPropertyHelper.RowMetadata, RowPropertyHelper.ColumnMetadata, Integer> createMetadataAdapter(RowPropertyHelper.RowMetadata rowMetadata) { return new MetadataAdapterImpl(rowMetadata); } private static class MetadataAdapterImpl implements MetadataAdapter<RowPropertyHelper.RowMetadata, RowPropertyHelper.ColumnMetadata, Integer> { private final RowPropertyHelper.RowMetadata rowMetadata; MetadataAdapterImpl(RowPropertyHelper.RowMetadata rowMetadata) { this.rowMetadata = rowMetadata; } /** * Implementation is just for completeness. The name does not matter. */ @Override public String getTypeName() { return "Row"; } @Override public RowPropertyHelper.RowMetadata getTypeMetadata() { return rowMetadata; } @Override public List<Integer> mapPropertyNamePathToFieldIdPath(String[] path) { if (path.length > 1) { throw new IllegalStateException("Rows do not support nested attributes"); } String columnName = path[0]; for (RowPropertyHelper.ColumnMetadata c : rowMetadata.getColumns()) { if (c.getColumnName().equals(columnName)) { return Collections.singletonList(c.getColumnIndex()); } } throw new IllegalArgumentException("Column not found : " + columnName); } @Override public RowPropertyHelper.ColumnMetadata makeChildAttributeMetadata(RowPropertyHelper.ColumnMetadata parentAttributeMetadata, Integer attribute) { if (parentAttributeMetadata != null) { throw new IllegalStateException("Rows do not support nested attributes"); } return rowMetadata.getColumns()[attribute]; } @Override public boolean isComparableProperty(RowPropertyHelper.ColumnMetadata attributeMetadata) { Class<?> propertyType = attributeMetadata.getPropertyType(); return propertyType.isPrimitive() || Comparable.class.isAssignableFrom(propertyType); } } }
3,992
38.147059
183
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/MetadataAdapter.java
package org.infinispan.objectfilter.impl; import java.util.List; /** * A generic representation of some of the aspects of type metadata. This is meant to ensure decoupling from the * underlying metadata representation (Class, Protobuf descriptor, etc). * * @author anistor@redhat.com * @since 7.0 */ public interface MetadataAdapter<TypeMetadata, AttributeMetadata, AttributeId extends Comparable<AttributeId>> { String getTypeName(); TypeMetadata getTypeMetadata(); /** * Transforms a String property name path into an internal representation of the path which might not be String based * (AttributeId is an Integer in the Protobuf case). */ List<AttributeId> mapPropertyNamePathToFieldIdPath(String[] path); AttributeMetadata makeChildAttributeMetadata(AttributeMetadata parentAttributeMetadata, AttributeId attribute); boolean isComparableProperty(AttributeMetadata attributeMetadata); }
934
32.392857
120
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/ObjectFilterImpl.java
package org.infinispan.objectfilter.impl; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.infinispan.objectfilter.FilterCallback; import org.infinispan.objectfilter.ObjectFilter; import org.infinispan.objectfilter.SortField; import org.infinispan.objectfilter.impl.aggregation.FieldAccumulator; import org.infinispan.objectfilter.impl.logging.Log; import org.infinispan.objectfilter.impl.predicateindex.AttributeNode; import org.infinispan.objectfilter.impl.predicateindex.FilterEvalContext; import org.infinispan.objectfilter.impl.predicateindex.MatcherEvalContext; import org.infinispan.objectfilter.impl.predicateindex.PredicateIndex; import org.infinispan.objectfilter.impl.predicateindex.be.BETree; import org.infinispan.objectfilter.impl.predicateindex.be.BETreeMaker; import org.infinispan.objectfilter.impl.syntax.BooleanExpr; import org.infinispan.objectfilter.impl.syntax.BooleanFilterNormalizer; import org.infinispan.objectfilter.impl.syntax.parser.IckleParsingResult; import org.infinispan.objectfilter.impl.util.StringHelper; import org.jboss.logging.Logger; /** * @author anistor@redhat.com * @since 7.0 */ final class ObjectFilterImpl<TypeMetadata, AttributeMetadata, AttributeId extends Comparable<AttributeId>> extends ObjectFilterBase<TypeMetadata> implements ObjectFilter { private static final Log log = Logger.getMessageLogger(Log.class, ObjectFilterImpl.class.getName()); private static final FilterCallback emptyCallback = (userContext, eventType, instance, projection, sortProjection) -> { // do nothing }; private final BaseMatcher<TypeMetadata, AttributeMetadata, AttributeId> matcher; private final MetadataAdapter<TypeMetadata, AttributeMetadata, AttributeId> metadataAdapter; private final FieldAccumulator[] acc; private final String[] projection; private final Class<?>[] projectionTypes; private final List<List<AttributeId>> translatedProjections; private final SortField[] sortFields; private final List<List<AttributeId>> translatedSortFields; private final BooleanExpr normalizedQuery; private FilterSubscriptionImpl<TypeMetadata, AttributeMetadata, AttributeId> filterSubscription; private AttributeNode<AttributeMetadata, AttributeId> root; ObjectFilterImpl(BaseMatcher<TypeMetadata, AttributeMetadata, AttributeId> matcher, MetadataAdapter<TypeMetadata, AttributeMetadata, AttributeId> metadataAdapter, IckleParsingResult<TypeMetadata> parsingResult, FieldAccumulator[] acc) { super(parsingResult, null); this.projection = parsingResult.getProjections(); this.projectionTypes = parsingResult.getProjectedTypes(); this.sortFields = parsingResult.getSortFields(); if (acc != null) { if (projectionTypes == null) { throw new IllegalArgumentException("Accumulators can only be used with projections"); } if (sortFields != null) { throw new IllegalArgumentException("Accumulators cannot be used with sorting"); } } this.matcher = matcher; this.metadataAdapter = metadataAdapter; this.acc = acc; if (projection != null && projection.length != 0) { translatedProjections = new ArrayList<>(projection.length); for (String projectionPath : projection) { translatedProjections.add(metadataAdapter.mapPropertyNamePathToFieldIdPath(StringHelper.split(projectionPath))); } } else { translatedProjections = null; } if (sortFields != null) { // deduplicate sort fields LinkedHashMap<String, SortField> sortFieldMap = new LinkedHashMap<>(); for (SortField sf : sortFields) { String path = sf.getPath().asStringPath(); if (!sortFieldMap.containsKey(path)) { sortFieldMap.put(path, sf); } } SortField[] sortFields = sortFieldMap.values().toArray(new SortField[sortFieldMap.size()]); // translate sort field paths translatedSortFields = new ArrayList<>(sortFields.length); for (SortField sortField : sortFields) { translatedSortFields.add(metadataAdapter.mapPropertyNamePathToFieldIdPath(sortField.getPath().asArrayPath())); } } else { translatedSortFields = null; } BooleanFilterNormalizer booleanFilterNormalizer = new BooleanFilterNormalizer(); normalizedQuery = booleanFilterNormalizer.normalize(parsingResult.getWhereClause()); if (getParameterNames().isEmpty()) { subscribe(); } } private ObjectFilterImpl(ObjectFilterImpl<TypeMetadata, AttributeMetadata, AttributeId> other, Map<String, Object> namedParameters) { super(other.parsingResult, Collections.unmodifiableMap(namedParameters)); this.matcher = other.matcher; this.metadataAdapter = other.metadataAdapter; this.acc = other.acc; this.projection = other.projection; this.projectionTypes = other.projectionTypes; this.sortFields = other.sortFields; this.translatedProjections = other.translatedProjections; this.translatedSortFields = other.translatedSortFields; this.normalizedQuery = other.normalizedQuery; subscribe(); } private void subscribe() { BETreeMaker<AttributeId> treeMaker = new BETreeMaker<>(metadataAdapter, false); BETree beTree = treeMaker.make(normalizedQuery, namedParameters); PredicateIndex<AttributeMetadata, AttributeId> predicateIndex = new PredicateIndex<>(metadataAdapter); root = predicateIndex.getRoot(); filterSubscription = new FilterSubscriptionImpl<>(parsingResult.getQueryString(), namedParameters, false, metadataAdapter, beTree, emptyCallback, false, projection, projectionTypes, translatedProjections, sortFields, translatedSortFields, null); filterSubscription.registerProjection(predicateIndex); filterSubscription.subscribe(predicateIndex); filterSubscription.index = 0; } @Override public String getEntityTypeName() { return metadataAdapter.getTypeName(); } @Override public String[] getProjection() { return projection; } @Override public Class<?>[] getProjectionTypes() { return projectionTypes; } @Override public ObjectFilter withParameters(Map<String, Object> namedParameters) { if (namedParameters == null) { throw log.getNamedParametersCannotBeNull(); } for (String paramName : getParameterNames()) { if (namedParameters.get(paramName) == null) { throw new IllegalArgumentException("Query parameter '" + paramName + "' was not set"); } } return new ObjectFilterImpl<>(this, namedParameters); } @Override public SortField[] getSortFields() { return sortFields; } @Override public Comparator<Comparable<?>[]> getComparator() { if (filterSubscription == null) { throw new IllegalStateException("Parameter values were not bound yet."); } return filterSubscription.getComparator(); } @Override public FilterResult filter(Object key, Object instance) { if (filterSubscription == null) { throw new IllegalStateException("Parameter values were not bound yet."); } if (instance == null) { throw new IllegalArgumentException("instance cannot be null"); } MatcherEvalContext<TypeMetadata, AttributeMetadata, AttributeId> matcherEvalContext = matcher.startSingleTypeContext(null, null, key, instance, filterSubscription.getMetadataAdapter()); if (matcherEvalContext != null) { FilterEvalContext filterEvalContext = matcherEvalContext.initSingleFilterContext(filterSubscription); if (acc != null) { filterEvalContext.acc = acc; for (FieldAccumulator a : acc) { if (a != null) { a.init(filterEvalContext.getProjection()); } } } matcherEvalContext.process(root); if (filterEvalContext.isMatching()) { Object o = filterEvalContext.getProjection() == null ? matcher.convert(instance) : null; return new FilterResultImpl(key, o, filterEvalContext.getProjection(), filterEvalContext.getSortProjection()); } } return null; } }
8,561
37.223214
191
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/ObjectFilterBase.java
package org.infinispan.objectfilter.impl; import java.util.Collections; import java.util.Comparator; import java.util.Map; import java.util.Set; import org.infinispan.objectfilter.ObjectFilter; import org.infinispan.objectfilter.SortField; import org.infinispan.objectfilter.impl.logging.Log; import org.infinispan.objectfilter.impl.syntax.parser.IckleParsingResult; import org.jboss.logging.Logger; /** * @author anistor@redhat.com * @since 9.0 */ abstract class ObjectFilterBase<TypeMetadata> implements ObjectFilter { private static final Log log = Logger.getMessageLogger(Log.class, ObjectFilterBase.class.getName()); protected final IckleParsingResult<TypeMetadata> parsingResult; protected final Map<String, Object> namedParameters; protected ObjectFilterBase(IckleParsingResult<TypeMetadata> parsingResult, Map<String, Object> namedParameters) { this.parsingResult = parsingResult; this.namedParameters = namedParameters != null ? Collections.unmodifiableMap(namedParameters) : null; } protected void validateParameters(Map<String, Object> namedParameters) { if (namedParameters == null) { throw log.getNamedParametersCannotBeNull(); } for (String paramName : getParameterNames()) { if (namedParameters.get(paramName) == null) { throw new IllegalArgumentException("Query parameter '" + paramName + "' was not set"); } } } @Override public String getEntityTypeName() { return parsingResult.getTargetEntityName(); } @Override public String[] getProjection() { return null; } @Override public Class<?>[] getProjectionTypes() { return null; } @Override public SortField[] getSortFields() { return null; } @Override public Comparator<Comparable<?>[]> getComparator() { return null; } @Override public Set<String> getParameterNames() { return parsingResult.getParameterNames(); } @Override public Map<String, Object> getParameters() { return namedParameters; } }
2,083
26.064935
116
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/BaseMatcher.java
package org.infinispan.objectfilter.impl; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.infinispan.objectfilter.FilterCallback; import org.infinispan.objectfilter.FilterSubscription; import org.infinispan.objectfilter.Matcher; import org.infinispan.objectfilter.ObjectFilter; import org.infinispan.objectfilter.impl.aggregation.FieldAccumulator; import org.infinispan.objectfilter.impl.logging.Log; import org.infinispan.objectfilter.impl.predicateindex.MatcherEvalContext; import org.infinispan.objectfilter.impl.syntax.ConstantBooleanExpr; import org.infinispan.objectfilter.impl.syntax.FullTextVisitor; import org.infinispan.objectfilter.impl.syntax.parser.IckleParser; import org.infinispan.objectfilter.impl.syntax.parser.IckleParsingResult; import org.infinispan.objectfilter.impl.syntax.parser.ObjectPropertyHelper; import org.infinispan.query.dsl.Query; import org.jboss.logging.Logger; /** * @author anistor@redhat.com * @since 7.0 */ //todo [anistor] make package local public abstract class BaseMatcher<TypeMetadata, AttributeMetadata, AttributeId extends Comparable<AttributeId>> implements Matcher { private static final Log log = Logger.getMessageLogger(Log.class, BaseMatcher.class.getName()); private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); private final Lock read = readWriteLock.readLock(); private final Lock write = readWriteLock.writeLock(); private final Map<TypeMetadata, FilterRegistry<TypeMetadata, AttributeMetadata, AttributeId>> filtersByType = new HashMap<>(); private final Map<TypeMetadata, FilterRegistry<TypeMetadata, AttributeMetadata, AttributeId>> deltaFiltersByType = new HashMap<>(); protected final ObjectPropertyHelper<TypeMetadata> propertyHelper; protected BaseMatcher(ObjectPropertyHelper<TypeMetadata> propertyHelper) { this.propertyHelper = propertyHelper; } public ObjectPropertyHelper<TypeMetadata> getPropertyHelper() { return propertyHelper; } /** * Executes the registered filters and notifies each one of them whether it was satisfied or not by the given * instance. * * @param userContext an optional user provided object to be passed to matching subscribers along with the matching * instance; can be {@code null} * @param eventType on optional event type discriminator that is matched against the even type specified when the * filter was registered; can be {@code null} * @param instance the object to test against the registered filters; never {@code null} */ @Override public void match(Object userContext, Object eventType, Object instance) { if (instance == null) { throw new IllegalArgumentException("instance cannot be null"); } read.lock(); try { MatcherEvalContext<TypeMetadata, AttributeMetadata, AttributeId> ctx = startMultiTypeContext(false, userContext, eventType, instance); if (ctx != null) { // try to match ctx.process(ctx.getRootNode()); // notify ctx.notifySubscribers(); } } finally { read.unlock(); } } @Override public void matchDelta(Object userContext, Object eventType, Object instanceOld, Object instanceNew, Object joiningEvent, Object updatedEvent, Object leavingEvent) { if (instanceOld == null && instanceNew == null) { throw new IllegalArgumentException("instances cannot be both null"); } read.lock(); try { MatcherEvalContext<TypeMetadata, AttributeMetadata, AttributeId> ctx1 = null; MatcherEvalContext<TypeMetadata, AttributeMetadata, AttributeId> ctx2 = null; if (instanceOld != null) { ctx1 = startMultiTypeContext(true, userContext, eventType, instanceOld); if (ctx1 != null) { // try to match ctx1.process(ctx1.getRootNode()); } } if (instanceNew != null) { ctx2 = startMultiTypeContext(true, userContext, eventType, instanceNew); if (ctx2 != null) { // try to match ctx2.process(ctx2.getRootNode()); } } if (ctx1 != null) { // notify ctx1.notifyDeltaSubscribers(ctx2, joiningEvent, updatedEvent, leavingEvent); } else if (ctx2 != null) { // notify ctx2.notifyDeltaSubscribers(null, leavingEvent, updatedEvent, joiningEvent); } } finally { read.unlock(); } } @Override public ObjectFilter getObjectFilter(Query<?> query) { return getObjectFilter(query.getQueryString(), null); } @Override public ObjectFilter getObjectFilter(String queryString) { return getObjectFilter(queryString, null); } @Override public ObjectFilter getObjectFilter(String queryString, List<FieldAccumulator> acc) { final IckleParsingResult<TypeMetadata> parsingResult = IckleParser.parse(queryString, propertyHelper); disallowGroupingAndAggregations(parsingResult); // if the query is a contradiction just return an ObjectFilter that rejects everything if (parsingResult.getWhereClause() == ConstantBooleanExpr.FALSE) { return new RejectObjectFilter<>(null, parsingResult); } final MetadataAdapter<TypeMetadata, AttributeMetadata, AttributeId> metadataAdapter = createMetadataAdapter(parsingResult.getTargetEntityMetadata()); // if the query is a tautology or there is no query at all and there is no sorting or projections just return a special instance that accepts anything // in case we have sorting and projections we cannot take this shortcut because the computation of projections or sort projections is a bit more involved if ((parsingResult.getWhereClause() == null || parsingResult.getWhereClause() == ConstantBooleanExpr.TRUE) && parsingResult.getSortFields() == null && parsingResult.getProjectedPaths() == null) { return new AcceptObjectFilter<>(null, this, metadataAdapter, parsingResult); } FieldAccumulator[] accumulators = acc != null ? acc.toArray(new FieldAccumulator[acc.size()]) : null; return new ObjectFilterImpl<>(this, metadataAdapter, parsingResult, accumulators); } @Override public ObjectFilter getObjectFilter(FilterSubscription filterSubscription) { FilterSubscriptionImpl<TypeMetadata, AttributeMetadata, AttributeId> filterSubscriptionImpl = (FilterSubscriptionImpl<TypeMetadata, AttributeMetadata, AttributeId>) filterSubscription; ObjectFilter objectFilter = getObjectFilter(filterSubscriptionImpl.getQueryString()); return filterSubscriptionImpl.getNamedParameters() != null ? objectFilter.withParameters(filterSubscriptionImpl.getNamedParameters()) : objectFilter; } @Override public FilterSubscription registerFilter(Query<?> query, FilterCallback callback, Object... eventType) { return registerFilter(query, callback, false, eventType); } @Override public FilterSubscription registerFilter(Query<?> query, FilterCallback callback, boolean isDeltaFilter, Object... eventType) { return registerFilter(query.getQueryString(), query.getParameters(), callback, isDeltaFilter, eventType); } @Override public FilterSubscription registerFilter(String queryString, FilterCallback callback, Object... eventType) { return registerFilter(queryString, callback, false, eventType); } @Override public FilterSubscription registerFilter(String queryString, FilterCallback callback, boolean isDeltaFilter, Object... eventType) { return registerFilter(queryString, null, callback, isDeltaFilter, eventType); } @Override public FilterSubscription registerFilter(String queryString, Map<String, Object> namedParameters, FilterCallback callback, Object... eventType) { return registerFilter(queryString, namedParameters, callback, false, eventType); } @Override public FilterSubscription registerFilter(String queryString, Map<String, Object> namedParameters, FilterCallback callback, boolean isDeltaFilter, Object... eventType) { IckleParsingResult<TypeMetadata> parsingResult = IckleParser.parse(queryString, propertyHelper); disallowGroupingAndAggregations(parsingResult); disallowFullText(parsingResult); Map<TypeMetadata, FilterRegistry<TypeMetadata, AttributeMetadata, AttributeId>> filterMap = isDeltaFilter ? deltaFiltersByType : filtersByType; write.lock(); try { FilterRegistry<TypeMetadata, AttributeMetadata, AttributeId> filterRegistry = filterMap.get(parsingResult.getTargetEntityMetadata()); if (filterRegistry == null) { filterRegistry = new FilterRegistry<>(createMetadataAdapter(parsingResult.getTargetEntityMetadata()), true); filterMap.put(filterRegistry.getMetadataAdapter().getTypeMetadata(), filterRegistry); } return filterRegistry.addFilter(queryString, namedParameters, parsingResult.getWhereClause(), parsingResult.getProjections(), parsingResult.getProjectedTypes(), parsingResult.getSortFields(), callback, isDeltaFilter, eventType); } finally { write.unlock(); } } private void disallowFullText(IckleParsingResult<TypeMetadata> parsingResult) { if (parsingResult.getWhereClause() != null) { if (parsingResult.getWhereClause().acceptVisitor(FullTextVisitor.INSTANCE)) { throw log.getFiltersCannotUseFullTextSearchException(); } } } private void disallowGroupingAndAggregations(IckleParsingResult<TypeMetadata> parsingResult) { if (parsingResult.hasGroupingOrAggregations()) { throw log.getFiltersCannotUseGroupingOrAggregationException(); } } @Override public void unregisterFilter(FilterSubscription filterSubscription) { FilterSubscriptionImpl<TypeMetadata, AttributeMetadata, AttributeId> filterSubscriptionImpl = (FilterSubscriptionImpl<TypeMetadata, AttributeMetadata, AttributeId>) filterSubscription; Map<TypeMetadata, FilterRegistry<TypeMetadata, AttributeMetadata, AttributeId>> filterMap = filterSubscription.isDeltaFilter() ? deltaFiltersByType : filtersByType; write.lock(); try { FilterRegistry<TypeMetadata, AttributeMetadata, AttributeId> filterRegistry = filterMap.get(filterSubscriptionImpl.getMetadataAdapter().getTypeMetadata()); if (filterRegistry != null) { filterRegistry.removeFilter(filterSubscription); } else { throw new IllegalStateException("No filter was found for type " + filterSubscriptionImpl.getMetadataAdapter().getTypeMetadata()); } if (filterRegistry.getFilterSubscriptions().isEmpty()) { filterMap.remove(filterRegistry.getMetadataAdapter().getTypeMetadata()); } } finally { write.unlock(); } } /** * Creates a new {@link MatcherEvalContext} capable of dealing with multiple filters. The context is created only if * the given instance is recognized to be of a type that has some filters registered. If there are no filters, {@code * null} is returned to signal this condition and make the evaluation faster. This method must be called while * holding the internal write lock. * * @param isDelta indicates if this is a delta match of not * @param userContext an opaque value, possibly null, the is received from the caller and is to be handed to the * {@link FilterCallback} in case a match is detected * @param eventType on optional event type discriminator * @param instance the instance to filter; never {@code null} * @return the MatcherEvalContext or {@code null} if no filter was registered for the instance */ protected abstract MatcherEvalContext<TypeMetadata, AttributeMetadata, AttributeId> startMultiTypeContext(boolean isDelta, Object userContext, Object eventType, Object instance); /** * Creates a new {@link MatcherEvalContext} capable of dealing with a single filter for a single type. The context is * created only if the given instance is recognized to be of a type that has some filters registered. If there are no * filters, {@code null} is returned to signal this condition and make the evaluation faster. This method must be * called while holding the internal write lock. * * @param userContext an opaque value, possibly null, the is received from the caller and is to be handed to the * {@link FilterCallback} in case a match is detected * @param instance the instance to filter; never {@code null} * @param metadataAdapter the metadata adapter of expected instance type * @return the MatcherEvalContext or {@code null} if no filter was registered for the instance */ protected abstract MatcherEvalContext<TypeMetadata, AttributeMetadata, AttributeId> startSingleTypeContext( Object userContext, Object eventType, Object key, Object instance, MetadataAdapter<TypeMetadata, AttributeMetadata, AttributeId> metadataAdapter); protected abstract MetadataAdapter<TypeMetadata, AttributeMetadata, AttributeId> createMetadataAdapter(TypeMetadata entityType); protected final FilterRegistry<TypeMetadata, AttributeMetadata, AttributeId> getFilterRegistryForType(boolean isDeltaFilter, TypeMetadata entityType) { return isDeltaFilter ? deltaFiltersByType.get(entityType) : filtersByType.get(entityType); } /** * Decorates a matching instance before it is presented to the caller of the {@link ObjectFilter#filter(Object)}. * * @param instance never null * @return the converted/decorated instance */ protected Object convert(Object instance) { return instance; } }
14,146
47.61512
237
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/AcceptObjectFilter.java
package org.infinispan.objectfilter.impl; import java.util.Map; import org.infinispan.objectfilter.ObjectFilter; import org.infinispan.objectfilter.impl.predicateindex.MatcherEvalContext; import org.infinispan.objectfilter.impl.syntax.parser.IckleParsingResult; /** * A filter that accepts all inputs of a given type. Does not support sorting and projections. * * @author anistor@redhat.com * @since 9.0 */ final class AcceptObjectFilter<TypeMetadata, AttributeMetadata, AttributeId extends Comparable<AttributeId>> extends ObjectFilterBase<TypeMetadata> implements ObjectFilter { private final BaseMatcher<TypeMetadata, AttributeMetadata, AttributeId> matcher; private final MetadataAdapter<TypeMetadata, AttributeMetadata, AttributeId> metadataAdapter; AcceptObjectFilter(Map<String, Object> namedParameters, BaseMatcher<TypeMetadata, AttributeMetadata, AttributeId> matcher, MetadataAdapter<TypeMetadata, AttributeMetadata, AttributeId> metadataAdapter, IckleParsingResult<TypeMetadata> parsingResult) { super(parsingResult, namedParameters); this.matcher = matcher; this.metadataAdapter = metadataAdapter; } @Override public ObjectFilter withParameters(Map<String, Object> namedParameters) { validateParameters(namedParameters); return new AcceptObjectFilter<>(namedParameters, matcher, metadataAdapter, parsingResult); } @Override public FilterResult filter(Object key, Object instance) { if (instance == null) { throw new IllegalArgumentException("instance cannot be null"); } MatcherEvalContext<TypeMetadata, AttributeMetadata, AttributeId> matcherEvalContext = matcher.startSingleTypeContext(null, null, key, instance, metadataAdapter); if (matcherEvalContext != null) { // once we have a successfully created context we already have a match as there are no filter conditions except for entity type return new FilterResultImpl(key, matcher.convert(instance), null, null); } return null; } }
2,107
41.16
167
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/FilterSubscriptionImpl.java
package org.infinispan.objectfilter.impl; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Map; import org.infinispan.objectfilter.FilterCallback; import org.infinispan.objectfilter.FilterSubscription; import org.infinispan.objectfilter.SortField; import org.infinispan.objectfilter.impl.predicateindex.PredicateIndex; import org.infinispan.objectfilter.impl.predicateindex.Predicates; import org.infinispan.objectfilter.impl.predicateindex.be.BENode; import org.infinispan.objectfilter.impl.predicateindex.be.BETree; import org.infinispan.objectfilter.impl.predicateindex.be.PredicateNode; import org.infinispan.objectfilter.impl.util.ComparableArrayComparator; /** * @author anistor@redhat.com * @since 7.0 */ public final class FilterSubscriptionImpl<TypeMetadata, AttributeMetadata, AttributeId extends Comparable<AttributeId>> implements FilterSubscription { private final String queryString; private final Map<String, Object> namedParameters; private final boolean useIntervals; public int index = -1; // todo [anistor] hide this private final MetadataAdapter<TypeMetadata, AttributeMetadata, AttributeId> metadataAdapter; private final BETree beTree; private final List<Predicates.Subscription<AttributeId>> predicateSubscriptions = new ArrayList<>(); private final FilterCallback callback; private final boolean isDeltaFilter; private final String[] projection; private final Class<?>[] projectionTypes; private final List<List<AttributeId>> translatedProjection; private final SortField[] sortFields; private final List<List<AttributeId>> translatedSortProjection; private final Object[] eventTypes; private Comparator<Comparable<?>[]> comparator; protected FilterSubscriptionImpl(String queryString, Map<String, Object> namedParameters, boolean useIntervals, MetadataAdapter<TypeMetadata, AttributeMetadata, AttributeId> metadataAdapter, BETree beTree, FilterCallback callback, boolean isDeltaFilter, String[] projection, Class<?>[] projectionTypes, List<List<AttributeId>> translatedProjection, SortField[] sortFields, List<List<AttributeId>> translatedSortProjection, Object[] eventTypes) { this.queryString = queryString; this.namedParameters = namedParameters; this.useIntervals = useIntervals; this.metadataAdapter = metadataAdapter; this.beTree = beTree; this.callback = callback; this.isDeltaFilter = isDeltaFilter; this.projection = projection; this.projectionTypes = projectionTypes; this.sortFields = sortFields; this.translatedProjection = translatedProjection; this.translatedSortProjection = translatedSortProjection; this.eventTypes = eventTypes; } public String getQueryString() { return queryString; } public Map<String, Object> getNamedParameters() { return namedParameters; } public boolean useIntervals() { return useIntervals; } public BETree getBETree() { return beTree; } @Override public String getEntityTypeName() { return metadataAdapter.getTypeName(); } public MetadataAdapter<TypeMetadata, AttributeMetadata, AttributeId> getMetadataAdapter() { return metadataAdapter; } @Override public FilterCallback getCallback() { return callback; } @Override public boolean isDeltaFilter() { return isDeltaFilter; } @Override public String[] getProjection() { return projection; } public Class<?>[] getProjectionTypes() { return projectionTypes; } @Override public SortField[] getSortFields() { return sortFields; } @Override public Comparator<Comparable<?>[]> getComparator() { if (sortFields != null && comparator == null) { boolean[] direction = new boolean[sortFields.length]; for (int i = 0; i < sortFields.length; i++) { direction[i] = sortFields[i].isAscending(); } comparator = new ComparableArrayComparator(direction); } return comparator; } @Override public Object[] getEventTypes() { return eventTypes; } public void registerProjection(PredicateIndex<AttributeMetadata, AttributeId> predicateIndex) { int i = 0; if (translatedProjection != null) { i = predicateIndex.addProjections(this, translatedProjection, i); } if (translatedSortProjection != null) { predicateIndex.addProjections(this, translatedSortProjection, i); } } public void unregisterProjection(PredicateIndex<AttributeMetadata, AttributeId> predicateIndex) { if (translatedProjection != null) { predicateIndex.removeProjections(this, translatedProjection); } if (translatedSortProjection != null) { predicateIndex.removeProjections(this, translatedSortProjection); } } public void subscribe(PredicateIndex<AttributeMetadata, AttributeId> predicateIndex) { for (BENode node : beTree.getNodes()) { if (node instanceof PredicateNode) { PredicateNode<AttributeId> predicateNode = (PredicateNode<AttributeId>) node; predicateSubscriptions.add(predicateIndex.addSubscriptionForPredicate(predicateNode, this)); } } } public void unsubscribe(PredicateIndex<AttributeMetadata, AttributeId> predicateIndex) { for (Predicates.Subscription<AttributeId> subscription : predicateSubscriptions) { predicateIndex.removeSubscriptionForPredicate(subscription); } } }
5,777
31.644068
151
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/ProtobufMatcher.java
package org.infinispan.objectfilter.impl; import java.util.List; import org.infinispan.objectfilter.impl.predicateindex.ProtobufMatcherEvalContext; import org.infinispan.objectfilter.impl.syntax.IndexedFieldProvider; import org.infinispan.objectfilter.impl.syntax.parser.ObjectPropertyHelper; import org.infinispan.objectfilter.impl.syntax.parser.ProtobufPropertyHelper; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.WrappedMessage; import org.infinispan.protostream.descriptors.Descriptor; import org.infinispan.protostream.descriptors.FieldDescriptor; /** * @author anistor@redhat.com * @since 7.0 */ public class ProtobufMatcher extends BaseMatcher<Descriptor, FieldDescriptor, Integer> { private final SerializationContext serializationContext; private final Descriptor wrappedMessageDescriptor; public ProtobufMatcher(SerializationContext serializationContext, IndexedFieldProvider<Descriptor> indexedFieldProvider) { super(new ProtobufPropertyHelper(serializationContext, indexedFieldProvider)); this.serializationContext = serializationContext; this.wrappedMessageDescriptor = serializationContext.getMessageDescriptor(WrappedMessage.PROTOBUF_TYPE_NAME); } @Override protected ProtobufMatcherEvalContext startMultiTypeContext(boolean isDeltaFilter, Object userContext, Object eventType, Object instance) { ProtobufMatcherEvalContext context = new ProtobufMatcherEvalContext(userContext, eventType, null, instance, wrappedMessageDescriptor, serializationContext); if (context.getEntityType() != null) { FilterRegistry<Descriptor, FieldDescriptor, Integer> filterRegistry = getFilterRegistryForType(isDeltaFilter, context.getEntityType()); if (filterRegistry != null) { context.initMultiFilterContext(filterRegistry); return context; } } return null; } @Override protected ProtobufMatcherEvalContext startSingleTypeContext(Object userContext, Object eventType, Object key, Object instance, MetadataAdapter<Descriptor, FieldDescriptor, Integer> metadataAdapter) { ProtobufMatcherEvalContext ctx = new ProtobufMatcherEvalContext(userContext, eventType, key, instance, wrappedMessageDescriptor, serializationContext); return ctx.getEntityType() != null && ctx.getEntityType().getFullName().equals(metadataAdapter.getTypeName()) ? ctx : null; } @Override protected MetadataAdapter<Descriptor, FieldDescriptor, Integer> createMetadataAdapter(Descriptor messageDescriptor) { return new MetadataAdapterImpl(messageDescriptor, propertyHelper); } private static class MetadataAdapterImpl implements MetadataAdapter<Descriptor, FieldDescriptor, Integer> { private final Descriptor messageDescriptor; private final ObjectPropertyHelper<Descriptor> propertyHelper; MetadataAdapterImpl(Descriptor messageDescriptor, ObjectPropertyHelper<Descriptor> propertyHelper) { this.messageDescriptor = messageDescriptor; this.propertyHelper = propertyHelper; } @Override public String getTypeName() { return messageDescriptor.getFullName(); } @Override public Descriptor getTypeMetadata() { return messageDescriptor; } @Override public List<Integer> mapPropertyNamePathToFieldIdPath(String[] path) { return (List<Integer>) propertyHelper.mapPropertyNamePathToFieldIdPath(messageDescriptor, path); } @Override public FieldDescriptor makeChildAttributeMetadata(FieldDescriptor parentAttributeMetadata, Integer attribute) { return parentAttributeMetadata == null ? messageDescriptor.findFieldByNumber(attribute) : parentAttributeMetadata.getMessageType().findFieldByNumber(attribute); } @Override public boolean isComparableProperty(FieldDescriptor attributeMetadata) { switch (attributeMetadata.getJavaType()) { case INT: case LONG: case FLOAT: case DOUBLE: case BOOLEAN: case STRING: case BYTE_STRING: case ENUM: return true; } return false; } } }
4,333
41.07767
162
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/FilterResultImpl.java
package org.infinispan.objectfilter.impl; import java.util.Arrays; import org.infinispan.objectfilter.ObjectFilter; /** * @author anistor@redhat.com * @since 7.0 */ public final class FilterResultImpl implements ObjectFilter.FilterResult { private final Object key; private final Object instance; private final Object[] projection; private final Comparable[] sortProjection; public FilterResultImpl(Object key, Object instance, Object[] projection, Comparable[] sortProjection) { if (instance != null && projection != null) { throw new IllegalArgumentException("instance and projection cannot be both non-null"); } if (instance == null && projection == null) { throw new IllegalArgumentException("instance and projection cannot be both null"); } this.key = key; this.instance = instance; this.projection = projection; this.sortProjection = sortProjection; } @Override public Object getKey() { return key; } @Override public Object getInstance() { return instance; } @Override public Object[] getProjection() { return projection; } @Override public Comparable<?>[] getSortProjection() { return sortProjection; } @Override public String toString() { return "FilterResultImpl{" + "instance=" + instance + ", projection=" + Arrays.toString(projection) + ", sortProjection=" + Arrays.toString(sortProjection) + '}'; } }
1,538
23.428571
107
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/ReflectionMatcher.java
package org.infinispan.objectfilter.impl; import java.util.List; import org.infinispan.objectfilter.impl.predicateindex.ReflectionMatcherEvalContext; import org.infinispan.objectfilter.impl.syntax.parser.EntityNameResolver; import org.infinispan.objectfilter.impl.syntax.parser.ObjectPropertyHelper; import org.infinispan.objectfilter.impl.syntax.parser.ReflectionEntityNamesResolver; import org.infinispan.objectfilter.impl.syntax.parser.ReflectionPropertyHelper; import org.infinispan.objectfilter.impl.util.ReflectionHelper; /** * @author anistor@redhat.com * @since 7.0 */ public class ReflectionMatcher extends BaseMatcher<Class<?>, ReflectionHelper.PropertyAccessor, String> { public ReflectionMatcher(ObjectPropertyHelper<Class<?>> propertyHelper) { super(propertyHelper); } public ReflectionMatcher(ClassLoader classLoader) { this(new ReflectionEntityNamesResolver(classLoader)); } public ReflectionMatcher(EntityNameResolver<Class<?>> entityNameResolver) { super(new ReflectionPropertyHelper(entityNameResolver)); } @Override protected ReflectionMatcherEvalContext startMultiTypeContext(boolean isDeltaFilter, Object userContext, Object eventType, Object instance) { FilterRegistry<Class<?>, ReflectionHelper.PropertyAccessor, String> filterRegistry = getFilterRegistryForType(isDeltaFilter, instance.getClass()); if (filterRegistry != null) { ReflectionMatcherEvalContext context = new ReflectionMatcherEvalContext(userContext, eventType, null, instance); context.initMultiFilterContext(filterRegistry); return context; } return null; } @Override protected ReflectionMatcherEvalContext startSingleTypeContext(Object userContext, Object eventType, Object key, Object instance, MetadataAdapter<Class<?>, ReflectionHelper.PropertyAccessor, String> metadataAdapter) { if (metadataAdapter.getTypeMetadata() == instance.getClass()) { return new ReflectionMatcherEvalContext(userContext, eventType, key, instance); } else { return null; } } @Override protected MetadataAdapter<Class<?>, ReflectionHelper.PropertyAccessor, String> createMetadataAdapter(Class<?> clazz) { return new MetadataAdapterImpl(clazz, propertyHelper); } private static class MetadataAdapterImpl implements MetadataAdapter<Class<?>, ReflectionHelper.PropertyAccessor, String> { private final Class<?> clazz; private final ObjectPropertyHelper<Class<?>> propertyHelper; MetadataAdapterImpl(Class<?> clazz, ObjectPropertyHelper<Class<?>> propertyHelper) { this.clazz = clazz; this.propertyHelper = propertyHelper; } @Override public String getTypeName() { return clazz.getName(); } @Override public Class<?> getTypeMetadata() { return clazz; } @Override public List<String> mapPropertyNamePathToFieldIdPath(String[] path) { return (List<String>) propertyHelper.mapPropertyNamePathToFieldIdPath(clazz, path); } @Override public ReflectionHelper.PropertyAccessor makeChildAttributeMetadata(ReflectionHelper.PropertyAccessor parentAttributeMetadata, String attribute) { try { return parentAttributeMetadata == null ? ReflectionHelper.getAccessor(clazz, attribute) : parentAttributeMetadata.getAccessor(attribute); } catch (ReflectiveOperationException e) { return null; } } @Override public boolean isComparableProperty(ReflectionHelper.PropertyAccessor attributeMetadata) { Class<?> propertyType = attributeMetadata.getPropertyType(); return propertyType != null && (propertyType.isPrimitive() || Comparable.class.isAssignableFrom(propertyType)); } } }
3,918
38.585859
169
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/ComparisonExpr.java
package org.infinispan.objectfilter.impl.syntax; /** * An expression that represents a comparison of Comparable values. * * @author anistor@redhat.com * @since 7.0 */ public final class ComparisonExpr implements PrimaryPredicateExpr { private final ValueExpr leftChild; private final ValueExpr rightChild; private final Type type; public enum Type { LESS, LESS_OR_EQUAL, EQUAL, NOT_EQUAL, GREATER_OR_EQUAL, GREATER; public Type negate() { switch (this) { case LESS: return GREATER_OR_EQUAL; case LESS_OR_EQUAL: return GREATER; case EQUAL: return NOT_EQUAL; case NOT_EQUAL: return EQUAL; case GREATER_OR_EQUAL: return LESS; case GREATER: return LESS_OR_EQUAL; default: return this; } } public Type reverse() { switch (this) { case LESS: return GREATER; case GREATER: return LESS; case LESS_OR_EQUAL: return GREATER_OR_EQUAL; case GREATER_OR_EQUAL: return LESS_OR_EQUAL; default: return this; } } } public ComparisonExpr(ValueExpr leftChild, ValueExpr rightChild, Type type) { this.leftChild = leftChild; this.rightChild = rightChild; this.type = type; } public ValueExpr getLeftChild() { return leftChild; } public ValueExpr getRightChild() { return rightChild; } public Type getComparisonType() { return type; } @Override public ValueExpr getChild() { return leftChild; } @Override public <T> T acceptVisitor(Visitor<?, ?> visitor) { return (T) visitor.visit(this); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ComparisonExpr other = (ComparisonExpr) o; return type == other.type && leftChild.equals(other.leftChild) && rightChild.equals(other.rightChild); } @Override public int hashCode() { int result = 31 * leftChild.hashCode() + rightChild.hashCode(); return 31 * result + type.hashCode(); } @Override public String toString() { return type + "(" + leftChild + ", " + rightChild + ')'; } @Override public String toQueryString() { StringBuilder sb = new StringBuilder(); sb.append(leftChild.toQueryString()).append(' '); switch (type) { case LESS: sb.append('<'); break; case LESS_OR_EQUAL: sb.append("<="); break; case EQUAL: sb.append('='); break; case NOT_EQUAL: sb.append("!="); break; case GREATER_OR_EQUAL: sb.append(">="); break; case GREATER: sb.append('>'); break; } sb.append(' ').append(rightChild.toQueryString()); return sb.toString(); } }
3,202
23.082707
108
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/Visitor.java
package org.infinispan.objectfilter.impl.syntax; /** * Visitor interface for expressions. * * @param <BE> is the return type when visiting a boolean expression (an expression that produces a {@link Boolean}) * @param <VE> is the return type when visiting a value expression (an expression that produces an arbitrary {@link * Object}) * @author anistor@redhat.com * @since 7.0 */ public interface Visitor<BE, VE> { BE visit(FullTextOccurExpr fullTextOccurExpr); BE visit(FullTextBoostExpr fullTextBoostExpr); BE visit(FullTextTermExpr fullTextTermExpr); BE visit(FullTextRegexpExpr fullTextRegexpExpr); BE visit(FullTextRangeExpr fullTextRangeExpr); BE visit(NotExpr notExpr); BE visit(OrExpr orExpr); BE visit(AndExpr andExpr); BE visit(ConstantBooleanExpr constantBooleanExpr); BE visit(IsNullExpr isNullExpr); BE visit(ComparisonExpr comparisonExpr); BE visit(BetweenExpr betweenExpr); BE visit(LikeExpr likeExpr); VE visit(ConstantValueExpr constantValueExpr); VE visit(PropertyValueExpr propertyValueExpr); VE visit(AggregationExpr aggregationExpr); }
1,141
23.826087
116
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/IndexedFieldProvider.java
package org.infinispan.objectfilter.impl.syntax; /** * @author anistor@redhat.com * @since 9.0 */ @FunctionalInterface public interface IndexedFieldProvider<TypeMetadata> { FieldIndexingMetadata get(TypeMetadata typeMetadata); interface FieldIndexingMetadata { /** * Checks if the property of the indexed entity is indexed. * * @param propertyPath the path of the property * @return {@code true} if the property is indexed, {@code false} otherwise. */ boolean isIndexed(String[] propertyPath); /** * Checks if the property of the indexed entity is analyzed. * * @param propertyPath the path of the property * @return {@code true} if the property is analyzed, {@code false} otherwise. */ boolean isAnalyzed(String[] propertyPath); /** * Checks if the property of the indexed entity is projectable. * * @param propertyPath the path of the property * @return {@code true} if the property is projectable, {@code false} otherwise. */ boolean isProjectable(String[] propertyPath); /** * Checks if the property of the indexed entity is sortable. * * @param propertyPath the path of the property * @return {@code true} if the property is sortable, {@code false} otherwise. */ boolean isSortable(String[] propertyPath); Object getNullMarker(String[] propertyPath); } FieldIndexingMetadata NO_INDEXING = new FieldIndexingMetadata() { @Override public boolean isIndexed(String[] propertyPath) { return false; } @Override public boolean isAnalyzed(String[] propertyPath) { return false; } @Override public boolean isProjectable(String[] propertyPath) { return false; } @Override public boolean isSortable(String[] propertyPath) { return false; } @Override public Object getNullMarker(String[] propertyPath) { return null; } }; }
2,077
26.342105
86
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/package-info.java
/** * The syntactic representation of an Ickle query (the output of the parser). This representation needs further * semantic processing before it can become 'executable'. All structures are meant to be immutable after construction. * * @author anistor@redhat.com * @since 7.0 * * @api.private */ package org.infinispan.objectfilter.impl.syntax;
354
31.272727
118
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/FullTextOccurExpr.java
package org.infinispan.objectfilter.impl.syntax; import org.infinispan.objectfilter.impl.ql.QueryRendererDelegate; /** * @author anistor@redhat.com * @since 9.0 */ public final class FullTextOccurExpr implements BooleanExpr { private final BooleanExpr child; private final QueryRendererDelegate.Occur occur; public FullTextOccurExpr(BooleanExpr child, QueryRendererDelegate.Occur occur) { this.child = child; this.occur = occur; } public QueryRendererDelegate.Occur getOccur() { return occur; } public BooleanExpr getChild() { return child; } @Override public <T> T acceptVisitor(Visitor<?, ?> visitor) { return (T) visitor.visit(this); } @Override public String toString() { return occur + "(" + child + ")"; } @Override public String toQueryString() { return occur.getOperator() + child.toQueryString(); } }
916
20.325581
83
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/PrimaryPredicateExpr.java
package org.infinispan.objectfilter.impl.syntax; /** * @author anistor@redhat.com * @since 7.0 */ public interface PrimaryPredicateExpr extends BooleanExpr { /** * Returns the left child value expression to which the predicate is attached. The {@link ValueExpr} should always be * a {@link PropertyValueExpr} after the tree was normalized and constant expressions were removed. */ ValueExpr getChild(); }
428
27.6
120
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/PredicateOptimisations.java
package org.infinispan.objectfilter.impl.syntax; import java.util.List; /** * @author anistor@redhat.com * @since 8.0 */ final class PredicateOptimisations { private PredicateOptimisations() { } /** * Checks if two predicates are identical or opposite. * * @param isFirstNegated is first predicate negated? * @param first the first predicate expression * @param isSecondNegated is second predicate negated? * @param second the second predicate expression * @return -1 if unrelated predicates, 0 if identical predicates, 1 if opposite predicates */ public static int comparePrimaryPredicates(boolean isFirstNegated, PrimaryPredicateExpr first, boolean isSecondNegated, PrimaryPredicateExpr second) { if (first.getClass() == second.getClass()) { if (first instanceof ComparisonExpr) { ComparisonExpr comparison1 = (ComparisonExpr) first; ComparisonExpr comparison2 = (ComparisonExpr) second; assert comparison1.getLeftChild() instanceof PropertyValueExpr; assert comparison1.getRightChild() instanceof ConstantValueExpr; assert comparison2.getLeftChild() instanceof PropertyValueExpr; assert comparison2.getRightChild() instanceof ConstantValueExpr; if (comparison1.getLeftChild().equals(comparison2.getLeftChild()) && comparison1.getRightChild().equals(comparison2.getRightChild())) { ComparisonExpr.Type cmpType1 = comparison1.getComparisonType(); if (isFirstNegated) { cmpType1 = cmpType1.negate(); } ComparisonExpr.Type cmpType2 = comparison2.getComparisonType(); if (isSecondNegated) { cmpType2 = cmpType2.negate(); } return cmpType1 == cmpType2 ? 0 : (cmpType1 == cmpType2.negate() ? 1 : -1); } } else if (first.equals(second)) { return isFirstNegated == isSecondNegated ? 0 : 1; } } return -1; } public static void optimizePredicates(List<BooleanExpr> children, boolean isConjunction) { removeRedundantPredicates(children, isConjunction); optimizeOverlappingIntervalPredicates(children, isConjunction); } /** * Removes duplicate occurrences of same predicate in a conjunction or disjunction. Also detects and removes * tautology and contradiction. The following translation rules are applied: * <ul> * <li>X || X => X</li> * <li>X && X => X</li> * <li>!X || !X => !X</li> * <li>!X && !X => !X</li> * <li>X || !X => TRUE (tautology)</li> * <li>X && !X => FALSE (contradiction)</li> * </ul> * * @param children the list of children expressions * @param isConjunction is the parent boolean expression a conjunction or a disjunction? */ private static void removeRedundantPredicates(List<BooleanExpr> children, boolean isConjunction) { for (int i = 0; i < children.size(); i++) { BooleanExpr ci = children.get(i); if (ci instanceof BooleanOperatorExpr || ci instanceof FullTextBoostExpr || ci instanceof FullTextOccurExpr) { // we may encounter non-predicate expressions, just ignore them continue; } boolean isCiNegated = ci instanceof NotExpr; if (isCiNegated) { ci = ((NotExpr) ci).getChild(); } assert ci instanceof PrimaryPredicateExpr; PrimaryPredicateExpr ci1 = (PrimaryPredicateExpr) ci; assert ci1.getChild() instanceof PropertyValueExpr; PropertyValueExpr pve = (PropertyValueExpr) ci1.getChild(); if (pve.isRepeated()) { // do not optimize repeated predicates continue; } int j = i + 1; while (j < children.size()) { BooleanExpr cj = children.get(j); // we may encounter non-predicate expressions, just ignore them if (!(cj instanceof BooleanOperatorExpr || cj instanceof FullTextBoostExpr || cj instanceof FullTextOccurExpr)) { boolean isCjNegated = cj instanceof NotExpr; if (isCjNegated) { cj = ((NotExpr) cj).getChild(); } PrimaryPredicateExpr cj1 = (PrimaryPredicateExpr) cj; assert cj1.getChild() instanceof PropertyValueExpr; PropertyValueExpr pve2 = (PropertyValueExpr) cj1.getChild(); // do not optimize repeated predicates if (!pve2.isRepeated()) { int res = comparePrimaryPredicates(isCiNegated, ci1, isCjNegated, cj1); if (res == 0) { // found duplication children.remove(j); continue; } else if (res == 1) { // found tautology or contradiction children.clear(); children.add(ConstantBooleanExpr.forBoolean(!isConjunction)); return; } } } j++; } } } private static void optimizeOverlappingIntervalPredicates(List<BooleanExpr> children, boolean isConjunction) { for (int i = 0; i < children.size(); i++) { BooleanExpr ci = children.get(i); if (ci instanceof ComparisonExpr) { ComparisonExpr first = (ComparisonExpr) ci; assert first.getLeftChild() instanceof PropertyValueExpr; assert first.getRightChild() instanceof ConstantValueExpr; PropertyValueExpr pve = (PropertyValueExpr) first.getLeftChild(); if (pve.isRepeated()) { // do not optimize repeated predicates continue; } int j = i + 1; while (j < children.size()) { BooleanExpr cj = children.get(j); if (cj instanceof ComparisonExpr) { ComparisonExpr second = (ComparisonExpr) cj; assert second.getLeftChild() instanceof PropertyValueExpr; assert second.getRightChild() instanceof ConstantValueExpr; PropertyValueExpr pve2 = (PropertyValueExpr) second.getLeftChild(); // do not optimize repeated predicates if (!pve2.isRepeated()) { if (first.getLeftChild().equals(second.getLeftChild())) { BooleanExpr res = optimizeOverlappingIntervalPredicates(first, second, isConjunction); if (res != null) { if (res instanceof ConstantBooleanExpr) { children.clear(); children.add(res); return; } children.remove(j); if (res != first) { first = (ComparisonExpr) res; children.set(i, first); } continue; } } } } j++; } } } } /** * @param first * @param second * @param isConjunction * @return null or a replacement BooleanExpr */ private static BooleanExpr optimizeOverlappingIntervalPredicates(ComparisonExpr first, ComparisonExpr second, boolean isConjunction) { final ConstantValueExpr firstConstant = (ConstantValueExpr) first.getRightChild(); final ConstantValueExpr secondConstant = (ConstantValueExpr) second.getRightChild(); if (firstConstant.isParameter() || secondConstant.isParameter()) { // if an interval end is a parameter then it is too early to do optimisations return null; } final Comparable firstValue = firstConstant.getConstantValue(); final Comparable secondValue = secondConstant.getConstantValue(); final int cmp = firstValue.compareTo(secondValue); if (first.getComparisonType() == ComparisonExpr.Type.EQUAL) { return optimizeEqAndInterval(first, second, isConjunction, cmp); } else if (second.getComparisonType() == ComparisonExpr.Type.EQUAL) { return optimizeEqAndInterval(second, first, isConjunction, -cmp); } else if (first.getComparisonType() == ComparisonExpr.Type.NOT_EQUAL) { return optimizeNotEqAndInterval(first, second, isConjunction, cmp); } else if (second.getComparisonType() == ComparisonExpr.Type.NOT_EQUAL) { return optimizeNotEqAndInterval(second, first, isConjunction, -cmp); } if (cmp == 0) { if (first.getComparisonType() == second.getComparisonType()) { // identical intervals return first; } if (first.getComparisonType() == second.getComparisonType().negate()) { // opposite directions, disjoint, union is full coverage return isConjunction ? ConstantBooleanExpr.FALSE : ConstantBooleanExpr.TRUE; } if (first.getComparisonType() == ComparisonExpr.Type.LESS_OR_EQUAL || first.getComparisonType() == ComparisonExpr.Type.GREATER_OR_EQUAL) { // opposite directions, overlapping in one point, union is full coverage return isConjunction ? new ComparisonExpr(first.getLeftChild(), first.getRightChild(), ComparisonExpr.Type.EQUAL) : ConstantBooleanExpr.TRUE; } else { // opposite directions, disjoint in one point, union is not full coverage return isConjunction ? ConstantBooleanExpr.FALSE : new ComparisonExpr(first.getLeftChild(), first.getRightChild(), ComparisonExpr.Type.NOT_EQUAL); } } // opposite direction intervals if (first.getComparisonType() == second.getComparisonType().negate() || first.getComparisonType() == second.getComparisonType().reverse()) { if (cmp < 0) { if (first.getComparisonType() == ComparisonExpr.Type.LESS || first.getComparisonType() == ComparisonExpr.Type.LESS_OR_EQUAL) { if (isConjunction) { return ConstantBooleanExpr.FALSE; } } else if (!isConjunction) { return ConstantBooleanExpr.TRUE; } } else { if (first.getComparisonType() == ComparisonExpr.Type.GREATER || first.getComparisonType() == ComparisonExpr.Type.GREATER_OR_EQUAL) { if (isConjunction) { return ConstantBooleanExpr.FALSE; } } else if (!isConjunction) { return ConstantBooleanExpr.TRUE; } } return null; } // same direction intervals if (first.getComparisonType() == ComparisonExpr.Type.LESS || first.getComparisonType() == ComparisonExpr.Type.LESS_OR_EQUAL) { // less than if (isConjunction) { return cmp < 0 ? first : second; } else { return cmp < 0 ? second : first; } } else { // greater than if (isConjunction) { return cmp < 0 ? second : first; } else { return cmp < 0 ? first : second; } } } private static BooleanExpr optimizeEqAndInterval(ComparisonExpr first, ComparisonExpr second, boolean isConjunction, int cmp) { assert first.getComparisonType() == ComparisonExpr.Type.EQUAL; switch (second.getComparisonType()) { case EQUAL: if (cmp == 0) { return first; } return isConjunction ? ConstantBooleanExpr.FALSE : null; case NOT_EQUAL: if (cmp == 0) { return ConstantBooleanExpr.forBoolean(!isConjunction); } return isConjunction ? first : null; case LESS: if (cmp == 0) { return isConjunction ? ConstantBooleanExpr.FALSE : new ComparisonExpr(first.getLeftChild(), first.getRightChild(), ComparisonExpr.Type.LESS_OR_EQUAL); } if (cmp < 0) { return isConjunction ? first : second; } return isConjunction ? ConstantBooleanExpr.FALSE : null; case LESS_OR_EQUAL: if (cmp <= 0) { return isConjunction ? first : second; } return isConjunction ? ConstantBooleanExpr.FALSE : null; case GREATER: if (cmp == 0) { return isConjunction ? ConstantBooleanExpr.FALSE : new ComparisonExpr(first.getLeftChild(), first.getRightChild(), ComparisonExpr.Type.GREATER_OR_EQUAL); } if (cmp > 0) { return isConjunction ? first : second; } return isConjunction ? ConstantBooleanExpr.FALSE : null; case GREATER_OR_EQUAL: if (cmp >= 0) { return isConjunction ? first : second; } return isConjunction ? ConstantBooleanExpr.FALSE : null; default: return null; } } private static BooleanExpr optimizeNotEqAndInterval(ComparisonExpr first, ComparisonExpr second, boolean isConjunction, int cmp) { assert first.getComparisonType() == ComparisonExpr.Type.NOT_EQUAL; switch (second.getComparisonType()) { case EQUAL: if (cmp == 0) { return ConstantBooleanExpr.FALSE; } return isConjunction ? second : first; case NOT_EQUAL: if (cmp == 0) { return first; } return isConjunction ? null : ConstantBooleanExpr.TRUE; case LESS: if (cmp >= 0) { return isConjunction ? second : first; } return isConjunction ? null : ConstantBooleanExpr.TRUE; case LESS_OR_EQUAL: if (cmp < 0) { return isConjunction ? null : ConstantBooleanExpr.TRUE; } if (cmp > 0) { return isConjunction ? second : first; } return isConjunction ? new ComparisonExpr(first.getLeftChild(), first.getRightChild(), ComparisonExpr.Type.LESS) : ConstantBooleanExpr.TRUE; case GREATER: if (cmp > 0) { return isConjunction ? null : ConstantBooleanExpr.TRUE; } return isConjunction ? second : first; case GREATER_OR_EQUAL: if (cmp < 0) { return isConjunction ? second : first; } if (cmp > 0) { return isConjunction ? new ComparisonExpr(first.getLeftChild(), first.getRightChild(), ComparisonExpr.Type.GREATER) : ConstantBooleanExpr.TRUE; } return isConjunction ? ConstantBooleanExpr.FALSE : null; default: return null; } } }
14,960
42.365217
168
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/ToQueryString.java
package org.infinispan.objectfilter.impl.syntax; /** * @author anistor@redhat.com * @since 9.0 */ interface ToQueryString { String toQueryString(); }
158
13.454545
48
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/ExprVisitor.java
package org.infinispan.objectfilter.impl.syntax; /** * A pass-through, zero transformation {@link Visitor} implementation. Comes handy when you want to implement a {@link * Visitor} but do not want to cover all the cases. * * @author anistor@redhat.com * @since 7.0 */ public class ExprVisitor implements Visitor<BooleanExpr, ValueExpr> { @Override public BooleanExpr visit(FullTextOccurExpr fullTextOccurExpr) { return fullTextOccurExpr; } @Override public BooleanExpr visit(FullTextBoostExpr fullTextBoostExpr) { return fullTextBoostExpr; } @Override public BooleanExpr visit(FullTextTermExpr fullTextTermExpr) { return fullTextTermExpr; } @Override public BooleanExpr visit(FullTextRegexpExpr fullTextRegexpExpr) { return fullTextRegexpExpr; } @Override public BooleanExpr visit(FullTextRangeExpr fullTextRangeExpr) { return fullTextRangeExpr; } @Override public BooleanExpr visit(NotExpr notExpr) { return notExpr; } @Override public BooleanExpr visit(OrExpr orExpr) { return orExpr; } @Override public BooleanExpr visit(AndExpr andExpr) { return andExpr; } @Override public BooleanExpr visit(ConstantBooleanExpr constantBooleanExpr) { return constantBooleanExpr; } @Override public BooleanExpr visit(IsNullExpr isNullExpr) { return isNullExpr; } @Override public BooleanExpr visit(ComparisonExpr comparisonExpr) { return comparisonExpr; } @Override public BooleanExpr visit(BetweenExpr betweenExpr) { return betweenExpr; } @Override public BooleanExpr visit(LikeExpr likeExpr) { return likeExpr; } @Override public ValueExpr visit(ConstantValueExpr constantValueExpr) { return constantValueExpr; } @Override public ValueExpr visit(PropertyValueExpr propertyValueExpr) { return propertyValueExpr; } @Override public ValueExpr visit(AggregationExpr aggregationExpr) { return aggregationExpr; } }
2,062
21.423913
118
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/ConstantBooleanExpr.java
package org.infinispan.objectfilter.impl.syntax; /** * A constant boolean expression (tautology or contradiction). * * @author anistor@redhat.com * @since 7.0 */ public final class ConstantBooleanExpr implements PrimaryPredicateExpr { public static final ConstantBooleanExpr TRUE = new ConstantBooleanExpr(true); public static final ConstantBooleanExpr FALSE = new ConstantBooleanExpr(false); private final boolean constantValue; public static ConstantBooleanExpr forBoolean(boolean value) { return value ? TRUE : FALSE; } private ConstantBooleanExpr(boolean constantValue) { this.constantValue = constantValue; } @Override public ValueExpr getChild() { return null; } public boolean getValue() { return constantValue; } public ConstantBooleanExpr negate() { return constantValue ? FALSE : TRUE; } @Override public <T> T acceptVisitor(Visitor<?, ?> visitor) { return (T) visitor.visit(this); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ConstantBooleanExpr other = (ConstantBooleanExpr) o; return constantValue == other.constantValue; } @Override public int hashCode() { return constantValue ? 1 : 0; } @Override public String toString() { return constantValue ? "CONST_TRUE" : "CONST_FALSE"; } @Override public String toQueryString() { return constantValue ? "TRUE" : "FALSE"; } }
1,554
22.560606
82
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/IsNullExpr.java
package org.infinispan.objectfilter.impl.syntax; /** * @author anistor@redhat.com * @since 7.0 */ public class IsNullExpr implements PrimaryPredicateExpr { private final ValueExpr child; public IsNullExpr(ValueExpr child) { this.child = child; } @Override public ValueExpr getChild() { return child; } @Override public <T> T acceptVisitor(Visitor<?, ?> visitor) { return (T) visitor.visit(this); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; IsNullExpr other = (IsNullExpr) o; return child.equals(other.child); } @Override public int hashCode() { return child.hashCode(); } @Override public String toString() { return "IS_NULL(" + child + ')'; } @Override public String toQueryString() { return child.toQueryString() + " IS NULL"; } }
957
18.958333
64
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/FullTextRegexpExpr.java
package org.infinispan.objectfilter.impl.syntax; /** * @author anistor@redhat.com * @since 9.0 */ public final class FullTextRegexpExpr implements PrimaryPredicateExpr { private final ValueExpr leftChild; private final String regexp; public FullTextRegexpExpr(ValueExpr leftChild, String regexp) { this.leftChild = leftChild; this.regexp = regexp; } public String getRegexp() { return regexp; } @Override public <T> T acceptVisitor(Visitor<?, ?> visitor) { return (T) visitor.visit(this); } @Override public ValueExpr getChild() { return leftChild; } @Override public String toString() { return leftChild.toString() + ":/" + regexp + "/"; } @Override public String toQueryString() { return leftChild.toQueryString() + ":/" + regexp + "/"; } }
851
19.285714
71
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/NotExpr.java
package org.infinispan.objectfilter.impl.syntax; /** * @author anistor@redhat.com * @since 7.0 */ public final class NotExpr implements BooleanExpr { private final BooleanExpr child; public NotExpr(BooleanExpr child) { this.child = child; } public BooleanExpr getChild() { return child; } @Override public <T> T acceptVisitor(Visitor<?, ?> visitor) { return (T) visitor.visit(this); } @Override public String toString() { return "NOT(" + child + ')'; } @Override public String toQueryString() { return "NOT(" + child.toQueryString() + ")"; } }
626
17.441176
54
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/FullTextTermExpr.java
package org.infinispan.objectfilter.impl.syntax; import java.util.Map; /** * @author anistor@redhat.com * @since 9.0 */ public final class FullTextTermExpr implements PrimaryPredicateExpr { private final ValueExpr leftChild; private final String term; private final Integer fuzzySlop; private final ConstantValueExpr.ParamPlaceholder paramPlaceholder; public FullTextTermExpr(ValueExpr leftChild, Object comparisonObject, Integer fuzzySlop) { this.leftChild = leftChild; this.term = comparisonObject.toString(); this.fuzzySlop = fuzzySlop; this.paramPlaceholder = (comparisonObject instanceof ConstantValueExpr.ParamPlaceholder) ? (ConstantValueExpr.ParamPlaceholder) comparisonObject : null; } public Integer getFuzzySlop() { return fuzzySlop; } @Override public <T> T acceptVisitor(Visitor<?, ?> visitor) { return (T) visitor.visit(this); } @Override public ValueExpr getChild() { return leftChild; } @Override public String toString() { return leftChild.toString() + ":'" + term + "'" + (fuzzySlop != null ? "~" + fuzzySlop : ""); } @Override public String toQueryString() { return leftChild.toQueryString() + ":'" + term + "'" + (fuzzySlop != null ? "~" + fuzzySlop : ""); } public String getTerm(Map<String, Object> namedParameters) { if (paramPlaceholder == null) { return term; } String paramName = paramPlaceholder.getName(); if (namedParameters == null) { throw new IllegalStateException("Missing value for parameter " + paramName); } Comparable value = (Comparable) namedParameters.get(paramName); if (value == null) { throw new IllegalStateException("Missing value for parameter " + paramName); } if (value instanceof String) { return (String) value; } throw new IllegalStateException("Parameter must be a string " + paramName); } }
1,994
27.913043
104
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/Visitable.java
package org.infinispan.objectfilter.impl.syntax; /** * @author anistor@redhat.com * @since 7.0 */ public interface Visitable { <T> T acceptVisitor(Visitor<?, ?> visitor); }
181
15.545455
48
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/BetweenExpr.java
package org.infinispan.objectfilter.impl.syntax; /** * An expression that represents a range of Comparable values corresponding to the BETWEEN predicate. The lower and * upper bound are included. * * @author anistor@redhat.com * @since 9.0 */ public final class BetweenExpr implements PrimaryPredicateExpr { private final ValueExpr leftChild; private final ValueExpr fromChild; private final ValueExpr toChild; public BetweenExpr(ValueExpr leftChild, ValueExpr fromChild, ValueExpr toChild) { this.leftChild = leftChild; this.fromChild = fromChild; this.toChild = toChild; } @Override public ValueExpr getChild() { return leftChild; } public ValueExpr getLeftChild() { return leftChild; } public ValueExpr getFromChild() { return fromChild; } public ValueExpr getToChild() { return toChild; } @Override public <T> T acceptVisitor(Visitor<?, ?> visitor) { return (T) visitor.visit(this); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; BetweenExpr other = (BetweenExpr) o; return leftChild.equals(other.leftChild) && fromChild.equals(other.fromChild) && toChild.equals(other.toChild); } @Override public int hashCode() { return 31 * (31 * leftChild.hashCode() + fromChild.hashCode()) + toChild.hashCode(); } @Override public String toString() { return "BETWEEN(" + leftChild + ", " + fromChild + ", " + toChild + ")"; } @Override public String toQueryString() { return leftChild.toQueryString() + " BETWEEN " + fromChild.toQueryString() + " AND " + toChild.toQueryString(); } }
1,784
23.791667
117
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/AggregationExpr.java
package org.infinispan.objectfilter.impl.syntax; import org.infinispan.objectfilter.impl.ql.AggregationFunction; import org.infinispan.objectfilter.impl.syntax.parser.AggregationPropertyPath; /** * @author anistor@redhat.com * @since 8.0 */ public final class AggregationExpr extends PropertyValueExpr { private final AggregationPropertyPath<?> propertyPath; public AggregationExpr(AggregationPropertyPath<?> propertyPath, boolean isRepeated, Class<?> primitiveType) { super(propertyPath, isRepeated, primitiveType); this.propertyPath = propertyPath; } public AggregationFunction getAggregationType() { return propertyPath.getAggregationFunction(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AggregationExpr other = (AggregationExpr) o; return propertyPath.equals(other.propertyPath); } @Override public int hashCode() { return propertyPath.hashCode(); } @Override public String toString() { return propertyPath.getAggregationFunction().name() + "(" + super.toString() + ")"; } @Override public String toQueryString() { return propertyPath.getAggregationFunction().name() + "(" + super.toQueryString() + ")"; } @Override public <T> T acceptVisitor(Visitor<?, ?> visitor) { return (T) visitor.visit(this); } }
1,438
27.215686
112
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/BooleanOperatorExpr.java
package org.infinispan.objectfilter.impl.syntax; import java.util.ArrayList; import java.util.List; /** * An expression that applies a boolean operator (OR, AND) to a list of boolean sub-expressions. * * @author anistor@redhat.com * @since 7.0 */ public abstract class BooleanOperatorExpr implements BooleanExpr { protected final List<BooleanExpr> children = new ArrayList<>(); protected BooleanOperatorExpr(BooleanExpr... children) { for (BooleanExpr child : children) { this.children.add(child); } } protected BooleanOperatorExpr(List<BooleanExpr> children) { for (BooleanExpr child : children) { this.children.add(child); } } public List<BooleanExpr> getChildren() { return children; } }
771
23.125
96
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/FullTextBoostExpr.java
package org.infinispan.objectfilter.impl.syntax; /** * @author anistor@redhat.com * @since 9.0 */ public final class FullTextBoostExpr implements BooleanExpr { private final BooleanExpr child; private final float boost; public FullTextBoostExpr(BooleanExpr child, float boost) { this.child = child; this.boost = boost; } public float getBoost() { return boost; } public BooleanExpr getChild() { return child; } @Override public <T> T acceptVisitor(Visitor<?, ?> visitor) { return (T) visitor.visit(this); } @Override public String toString() { return "(" + child + ")^" + boost; } @Override public String toQueryString() { return "(" + child.toQueryString() + ")^" + boost; } }
783
18.121951
61
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/BooleanExpr.java
package org.infinispan.objectfilter.impl.syntax; /** * @author anistor@redhat.com * @since 7.0 */ public interface BooleanExpr extends Visitable, ToQueryString { }
168
17.777778
63
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/BooleShannonExpansion.java
package org.infinispan.objectfilter.impl.syntax; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; /** * Expands an input filter expression composed of indexed and unindexed fields into a superset of it * (matching the set of the input filter plus some more false positives), using only indexed fields. * The expanded expression is computed by applying <a href="http://en.wikipedia.org/wiki/Boole%27s_expansion_theorem">Boole's expansion theorem</a> * to all non-indexed fields and then ignoring the non-indexed fields from the resulting product. The resulting product * is a more complex expression but it can be executed fully indexed. In some exterme cases it can become a tautology * (TRUE), indicating that the filter should be executed fully non-indexed by doing a full scan. * * @author anistor@redhat.com * @since 8.0 */ public final class BooleShannonExpansion { /** * The maximum number of cofactors we allow in the product before giving up. */ private final int maxExpansionCofactors; // todo [anistor] besides indexed vs non-indexed we need to detect occurrences of cross-relationship spurious matches and apply a second in-memory filtering phase private final IndexedFieldProvider.FieldIndexingMetadata fieldIndexingMetadata; public BooleShannonExpansion(int maxExpansionCofactors, IndexedFieldProvider.FieldIndexingMetadata fieldIndexingMetadata) { this.maxExpansionCofactors = maxExpansionCofactors; this.fieldIndexingMetadata = fieldIndexingMetadata; } private class Collector extends ExprVisitor { private boolean foundIndexed = false; private final Set<PrimaryPredicateExpr> predicatesToRemove = new LinkedHashSet<>(); @Override public BooleanExpr visit(FullTextBoostExpr fullTextBoostExpr) { fullTextBoostExpr.getChild().acceptVisitor(this); return fullTextBoostExpr; } @Override public BooleanExpr visit(FullTextOccurExpr fullTextOccurExpr) { fullTextOccurExpr.getChild().acceptVisitor(this); return fullTextOccurExpr; } @Override public BooleanExpr visit(FullTextTermExpr fullTextTermExpr) { PropertyValueExpr propertyValueExpr = (PropertyValueExpr) fullTextTermExpr.getChild(); if (fieldIndexingMetadata.isIndexed(propertyValueExpr.getPropertyPath().asArrayPath())) { foundIndexed = true; } else { predicatesToRemove.add(fullTextTermExpr); } return fullTextTermExpr; } @Override public BooleanExpr visit(FullTextRegexpExpr fullTextRegexpExpr) { PropertyValueExpr propertyValueExpr = (PropertyValueExpr) fullTextRegexpExpr.getChild(); if (fieldIndexingMetadata.isIndexed(propertyValueExpr.getPropertyPath().asArrayPath())) { foundIndexed = true; } else { predicatesToRemove.add(fullTextRegexpExpr); } return fullTextRegexpExpr; } @Override public BooleanExpr visit(FullTextRangeExpr fullTextRangeExpr) { PropertyValueExpr propertyValueExpr = (PropertyValueExpr) fullTextRangeExpr.getChild(); if (fieldIndexingMetadata.isIndexed(propertyValueExpr.getPropertyPath().asArrayPath())) { foundIndexed = true; } else { predicatesToRemove.add(fullTextRangeExpr); } return fullTextRangeExpr; } @Override public BooleanExpr visit(NotExpr notExpr) { notExpr.getChild().acceptVisitor(this); return notExpr; } @Override public BooleanExpr visit(OrExpr orExpr) { for (BooleanExpr c : orExpr.getChildren()) { c.acceptVisitor(this); } return orExpr; } @Override public BooleanExpr visit(AndExpr andExpr) { for (BooleanExpr c : andExpr.getChildren()) { c.acceptVisitor(this); } return andExpr; } @Override public BooleanExpr visit(ConstantBooleanExpr constantBooleanExpr) { return constantBooleanExpr; } @Override public BooleanExpr visit(IsNullExpr isNullExpr) { PropertyValueExpr propertyValueExpr = (PropertyValueExpr) isNullExpr.getChild(); if (fieldIndexingMetadata.isIndexed(propertyValueExpr.getPropertyPath().asArrayPath())) { foundIndexed = true; } else { predicatesToRemove.add(isNullExpr); } return isNullExpr; } @Override public BooleanExpr visit(ComparisonExpr comparisonExpr) { PropertyValueExpr propertyValueExpr = (PropertyValueExpr) comparisonExpr.getLeftChild(); if (fieldIndexingMetadata.isIndexed(propertyValueExpr.getPropertyPath().asArrayPath())) { foundIndexed = true; } else { predicatesToRemove.add(comparisonExpr); } return comparisonExpr; } @Override public BooleanExpr visit(LikeExpr likeExpr) { PropertyValueExpr propertyValueExpr = (PropertyValueExpr) likeExpr.getChild(); if (fieldIndexingMetadata.isIndexed(propertyValueExpr.getPropertyPath().asArrayPath())) { foundIndexed = true; } else { predicatesToRemove.add(likeExpr); } return likeExpr; } @Override public ValueExpr visit(ConstantValueExpr constantValueExpr) { return constantValueExpr; } @Override public ValueExpr visit(PropertyValueExpr propertyValueExpr) { return propertyValueExpr; } @Override public ValueExpr visit(AggregationExpr aggregationExpr) { return aggregationExpr; } } private static class Replacer extends ExprVisitor { private final PrimaryPredicateExpr toReplace; private final ConstantBooleanExpr with; private boolean found = false; private Replacer(PrimaryPredicateExpr toReplace, ConstantBooleanExpr with) { this.toReplace = toReplace; this.with = with; } @Override public BooleanExpr visit(NotExpr notExpr) { BooleanExpr transformedChild = notExpr.getChild().acceptVisitor(this); if (transformedChild instanceof ConstantBooleanExpr) { return ((ConstantBooleanExpr) transformedChild).negate(); } return new NotExpr(transformedChild); } @Override public BooleanExpr visit(OrExpr orExpr) { List<BooleanExpr> newChildren = new ArrayList<>(orExpr.getChildren().size()); for (BooleanExpr c : orExpr.getChildren()) { BooleanExpr e = c.acceptVisitor(this); if (e instanceof ConstantBooleanExpr) { if (((ConstantBooleanExpr) e).getValue()) { return ConstantBooleanExpr.TRUE; } } else { if (e instanceof OrExpr) { newChildren.addAll(((OrExpr) e).getChildren()); } else { newChildren.add(e); } } } PredicateOptimisations.optimizePredicates(newChildren, false); if (newChildren.size() == 1) { return newChildren.get(0); } return new OrExpr(newChildren); } @Override public BooleanExpr visit(AndExpr andExpr) { List<BooleanExpr> newChildren = new ArrayList<>(andExpr.getChildren().size()); for (BooleanExpr c : andExpr.getChildren()) { BooleanExpr e = c.acceptVisitor(this); if (e instanceof ConstantBooleanExpr) { if (!((ConstantBooleanExpr) e).getValue()) { return ConstantBooleanExpr.FALSE; } } else { if (e instanceof AndExpr) { newChildren.addAll(((AndExpr) e).getChildren()); } else { newChildren.add(e); } } } PredicateOptimisations.optimizePredicates(newChildren, true); if (newChildren.size() == 1) { return newChildren.get(0); } return new AndExpr(newChildren); } @Override public BooleanExpr visit(ConstantBooleanExpr constantBooleanExpr) { return constantBooleanExpr; } @Override public BooleanExpr visit(IsNullExpr isNullExpr) { return replacePredicate(isNullExpr); } @Override public BooleanExpr visit(ComparisonExpr comparisonExpr) { return replacePredicate(comparisonExpr); } @Override public BooleanExpr visit(LikeExpr likeExpr) { return replacePredicate(likeExpr); } @Override public ValueExpr visit(ConstantValueExpr constantValueExpr) { return constantValueExpr; } @Override public ValueExpr visit(PropertyValueExpr propertyValueExpr) { return propertyValueExpr; } @Override public ValueExpr visit(AggregationExpr aggregationExpr) { return aggregationExpr; } private BooleanExpr replacePredicate(PrimaryPredicateExpr primaryPredicateExpr) { switch (PredicateOptimisations.comparePrimaryPredicates(false, primaryPredicateExpr, false, toReplace)) { case 0: found = true; return with; case 1: found = true; return with.negate(); default: return primaryPredicateExpr; } } } /** * Creates a less restrictive (expanded) query that matches the same objects as the input query plus potentially some * more (false positives). This query can be executed fully indexed and the result can be filtered in a second pass * to remove the false positives. This method can eventually return TRUE and in that case the expansion is useless * and it is better to just run the entire query unindexed (full scan). * <p> * If all fields used by the input query are indexed then the expansion is identical to the input query. * * @param booleanExpr the expression to expand * @return the expanded query if some of the fields are non-indexed or the input query if all fields are indexed */ public BooleanExpr expand(BooleanExpr booleanExpr) { if (booleanExpr == null || booleanExpr instanceof ConstantBooleanExpr) { return booleanExpr; } Collector collector = new Collector(); booleanExpr.acceptVisitor(collector); if (!collector.foundIndexed) { return ConstantBooleanExpr.TRUE; } if (!collector.predicatesToRemove.isEmpty()) { int numCofactors = 1; for (PrimaryPredicateExpr e : collector.predicatesToRemove) { Replacer replacer1 = new Replacer(e, ConstantBooleanExpr.TRUE); BooleanExpr e1 = booleanExpr.acceptVisitor(replacer1); if (!replacer1.found) { continue; } if (e1 == ConstantBooleanExpr.TRUE) { return ConstantBooleanExpr.TRUE; } Replacer replacer2 = new Replacer(e, ConstantBooleanExpr.FALSE); BooleanExpr e2 = booleanExpr.acceptVisitor(replacer2); if (e2 == ConstantBooleanExpr.TRUE) { return ConstantBooleanExpr.TRUE; } if (e1 == ConstantBooleanExpr.FALSE) { booleanExpr = e2; } else if (e2 == ConstantBooleanExpr.FALSE) { booleanExpr = e1; } else { numCofactors *= 2; OrExpr disjunction; if (e1 instanceof OrExpr) { disjunction = (OrExpr) e1; if (e2 instanceof OrExpr) { disjunction.getChildren().addAll(((OrExpr) e2).getChildren()); } else { disjunction.getChildren().add(e2); } } else if (e2 instanceof OrExpr) { disjunction = (OrExpr) e2; disjunction.getChildren().add(e1); } else { disjunction = new OrExpr(e1, e2); } PredicateOptimisations.optimizePredicates(disjunction.getChildren(), false); booleanExpr = disjunction; } if (numCofactors > maxExpansionCofactors) { // expansion is too big, it's better to do full scan rather than search the index with a huge and // complex query that is a disjunction of many predicates so will very likely match everything anyway return ConstantBooleanExpr.TRUE; } } } return booleanExpr; } }
12,801
35.369318
165
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/FullTextVisitor.java
package org.infinispan.objectfilter.impl.syntax; /** * Checks if there are any full-text predicates in a query. * * @author anistor@redhat.com * @since 9.0 */ public final class FullTextVisitor implements Visitor<Boolean, Boolean> { public static final FullTextVisitor INSTANCE = new FullTextVisitor(); @Override public Boolean visit(FullTextOccurExpr fullTextOccurExpr) { return Boolean.TRUE; } @Override public Boolean visit(FullTextBoostExpr fullTextBoostExpr) { return Boolean.TRUE; } @Override public Boolean visit(FullTextTermExpr fullTextTermExpr) { return Boolean.TRUE; } @Override public Boolean visit(FullTextRegexpExpr fullTextRegexpExpr) { return Boolean.TRUE; } @Override public Boolean visit(FullTextRangeExpr fullTextRangeExpr) { return Boolean.TRUE; } @Override public Boolean visit(NotExpr notExpr) { return notExpr.getChild().acceptVisitor(this); } @Override public Boolean visit(OrExpr orExpr) { for (BooleanExpr c : orExpr.getChildren()) { if (c.acceptVisitor(this)) { return Boolean.TRUE; } } return Boolean.FALSE; } @Override public Boolean visit(AndExpr andExpr) { for (BooleanExpr c : andExpr.getChildren()) { if (c.acceptVisitor(this)) { return Boolean.TRUE; } } return Boolean.FALSE; } @Override public Boolean visit(ConstantBooleanExpr constantBooleanExpr) { return Boolean.FALSE; } @Override public Boolean visit(IsNullExpr isNullExpr) { return isNullExpr.getChild().acceptVisitor(this); } @Override public Boolean visit(ComparisonExpr comparisonExpr) { return Boolean.FALSE; } @Override public Boolean visit(BetweenExpr betweenExpr) { return Boolean.FALSE; } @Override public Boolean visit(LikeExpr likeExpr) { return Boolean.FALSE; } @Override public Boolean visit(ConstantValueExpr constantValueExpr) { return Boolean.FALSE; } @Override public Boolean visit(PropertyValueExpr propertyValueExpr) { return Boolean.FALSE; } @Override public Boolean visit(AggregationExpr aggregationExpr) { return Boolean.FALSE; } }
2,294
21.281553
73
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/LikeExpr.java
package org.infinispan.objectfilter.impl.syntax; import java.util.Map; /** * @author anistor@redhat.com * @since 7.0 */ public final class LikeExpr implements PrimaryPredicateExpr { public static final char SINGLE_CHARACTER_WILDCARD = '_'; public static final char MULTIPLE_CHARACTERS_WILDCARD = '%'; public static final char DEFAULT_ESCAPE_CHARACTER = '\\'; private final ValueExpr child; private final Object pattern; private final char escapeChar = DEFAULT_ESCAPE_CHARACTER; public LikeExpr(ValueExpr child, Object pattern) { this.child = child; this.pattern = pattern; } @Override public ValueExpr getChild() { return child; } public String getPattern(Map<String, Object> namedParameters) { if (pattern instanceof ConstantValueExpr.ParamPlaceholder) { String paramName = ((ConstantValueExpr.ParamPlaceholder) pattern).getName(); if (namedParameters == null) { throw new IllegalStateException("Missing value for parameter " + paramName); } String p = (String) namedParameters.get(paramName); if (p == null) { throw new IllegalStateException("Missing value for parameter " + paramName); } return p; } else { return (String) pattern; } } public char getEscapeChar() { return escapeChar; } @Override public <T> T acceptVisitor(Visitor<?, ?> visitor) { return (T) visitor.visit(this); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LikeExpr likeExpr = (LikeExpr) o; return pattern.equals(likeExpr.pattern) && child.equals(likeExpr.child); } @Override public int hashCode() { return 31 * child.hashCode() + pattern.hashCode(); } @Override public String toString() { return "LIKE(" + child + ", " + pattern + ')'; } @Override public String toQueryString() { return child.toQueryString() + " LIKE '" + pattern + "'"; } }
2,097
25.556962
88
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/SyntaxTreePrinter.java
package org.infinispan.objectfilter.impl.syntax; import org.infinispan.objectfilter.SortField; import org.infinispan.objectfilter.impl.ql.PropertyPath; /** * Generates an Ickle query from an expression tree. * * @author anistor@redhat.com * @since 8.0 */ public final class SyntaxTreePrinter { private SyntaxTreePrinter() { } public static String printTree(BooleanExpr whereClause) { StringBuilder sb = new StringBuilder(); if (whereClause != null) { if (whereClause == ConstantBooleanExpr.FALSE) { throw new IllegalArgumentException("The WHERE clause must not be a contradiction"); } if (whereClause != ConstantBooleanExpr.TRUE) { sb.append(" WHERE ").append(whereClause.toQueryString()); } } return sb.toString(); } public static String printTree(String fromEntityTypeName, PropertyPath[] projection, BooleanExpr whereClause, SortField[] orderBy) { StringBuilder sb = new StringBuilder(); if (projection != null && projection.length != 0) { sb.append("SELECT "); for (int i = 0; i < projection.length; i++) { if (i != 0) { sb.append(", "); } sb.append(projection[i]); } sb.append(' '); } sb.append("FROM ").append(fromEntityTypeName); sb.append(printTree(whereClause)); if (orderBy != null && orderBy.length != 0) { sb.append(" ORDER BY "); for (int i = 0; i < orderBy.length; i++) { if (i != 0) { sb.append(", "); } SortField sf = orderBy[i]; sb.append(sf.getPath()); if (!sf.isAscending()) { sb.append(" DESC"); } } } return sb.toString(); } }
1,825
28.934426
135
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/FullTextRangeExpr.java
package org.infinispan.objectfilter.impl.syntax; /** * @author anistor@redhat.com * @since 9.0 */ public final class FullTextRangeExpr implements PrimaryPredicateExpr { private final ValueExpr leftChild; private final boolean includeLower; private final Object lower; private final boolean includeUpper; private final Object upper; public FullTextRangeExpr(ValueExpr leftChild, boolean includeLower, Object lower, Object upper, boolean includeUpper) { this.leftChild = leftChild; this.includeLower = includeLower; this.lower = lower; this.upper = upper; this.includeUpper = includeUpper; } public boolean isIncludeLower() { return includeLower; } public boolean isIncludeUpper() { return includeUpper; } public Object getLower() { return lower; } public Object getUpper() { return upper; } @Override public String toString() { return leftChild.toString() + ":" + (includeLower ? '[' : '{') + (lower == null ? "*" : lower) + " TO " + (upper == null ? "*" : upper) + (includeUpper ? ']' : '}'); } @Override public String toQueryString() { return leftChild.toQueryString() + ":" + (includeLower ? '[' : '{') + (lower == null ? "*" : lower) + " TO " + (upper == null ? "*" : upper) + (includeUpper ? ']' : '}'); } @Override public <T> T acceptVisitor(Visitor<?, ?> visitor) { return (T) visitor.visit(this); } @Override public ValueExpr getChild() { return leftChild; } }
1,617
22.449275
122
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/AndExpr.java
package org.infinispan.objectfilter.impl.syntax; import java.util.List; /** * @author anistor@redhat.com * @since 7.0 */ public final class AndExpr extends BooleanOperatorExpr { public AndExpr(BooleanExpr... children) { super(children); } public AndExpr(List<BooleanExpr> children) { super(children); } @Override public <T> T acceptVisitor(Visitor<?, ?> visitor) { return (T) visitor.visit(this); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("AND("); boolean isFirst = true; for (BooleanExpr c : children) { if (isFirst) { isFirst = false; } else { sb.append(", "); } sb.append(c); } sb.append(')'); return sb.toString(); } @Override public String toQueryString() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < children.size(); i++) { if (i != 0) { sb.append(" AND "); } sb.append('(').append(children.get(i).toQueryString()).append(')'); } return sb.toString(); } }
1,158
20.867925
76
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/PropertyValueExpr.java
package org.infinispan.objectfilter.impl.syntax; import org.infinispan.objectfilter.impl.ql.PropertyPath; /** * A property reference expression. * * @author anistor@redhat.com * @since 7.0 */ public class PropertyValueExpr implements ValueExpr { protected final PropertyPath<?> propertyPath; protected final boolean isRepeated; protected final Class<?> primitiveType; public PropertyValueExpr(PropertyPath<?> propertyPath, boolean isRepeated, Class<?> primitiveType) { this.propertyPath = propertyPath; this.isRepeated = isRepeated; this.primitiveType = primitiveType; } public PropertyValueExpr(String propertyPath, boolean isRepeated, Class<?> primitiveType) { this(PropertyPath.make(propertyPath), isRepeated, primitiveType); } public PropertyPath<?> getPropertyPath() { return propertyPath; } public boolean isRepeated() { return isRepeated; } public Class<?> getPrimitiveType() { return primitiveType; } @Override public <T> T acceptVisitor(Visitor<?, ?> visitor) { return (T) visitor.visit(this); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PropertyValueExpr other = (PropertyValueExpr) o; return propertyPath.equals(other.propertyPath); } @Override public int hashCode() { return propertyPath.hashCode(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("PROP(").append(propertyPath); if (isRepeated) { sb.append('*'); } sb.append(')'); return sb.toString(); } @Override public String toQueryString() { return propertyPath.toString(); } }
1,808
23.12
103
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/ValueExpr.java
package org.infinispan.objectfilter.impl.syntax; /** * @author anistor@redhat.com * @since 7.0 */ public interface ValueExpr extends Visitable, ToQueryString { }
166
17.555556
61
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/ConstantValueExpr.java
package org.infinispan.objectfilter.impl.syntax; import java.text.ParseException; import java.time.Instant; import java.util.Date; import java.util.Map; import org.infinispan.objectfilter.impl.util.DateHelper; /** * A constant comparable value, to be used as right or left side in a comparison expression. * * @author anistor@redhat.com * @since 7.0 */ public final class ConstantValueExpr implements ValueExpr { public static final class ParamPlaceholder implements Comparable { private final String name; public ParamPlaceholder(String name) { if (name == null) { throw new IllegalArgumentException("name cannot be null"); } this.name = name; } public String getName() { return name; } @Override public String toString() { return ":" + getName(); } @Override public int compareTo(Object o) { return name.compareTo(((ParamPlaceholder) o).getName()); } @Override public int hashCode() { return name.hashCode(); } @Override public boolean equals(Object obj) { return obj == this || obj != null && obj.getClass() == ParamPlaceholder.class && name.equals(((ParamPlaceholder) obj).getName()); } } private final Comparable constantValue; public ConstantValueExpr(Comparable constantValue) { if (constantValue == null) { throw new IllegalArgumentException("constantValue cannot be null"); } this.constantValue = constantValue; } public Comparable getConstantValue() { if (isParameter()) { throw new IllegalStateException("The value is a parameter " + constantValue); } return constantValue; } public boolean isParameter() { return constantValue instanceof ParamPlaceholder; } public Comparable getConstantValueAs(Class<?> targetType, Map<String, Object> namedParameters) { Comparable value; if (constantValue instanceof ParamPlaceholder) { String paramName = ((ParamPlaceholder) constantValue).getName(); if (namedParameters == null) { throw new IllegalStateException("Missing value for parameter " + paramName); } value = (Comparable) namedParameters.get(paramName); if (value == null) { throw new IllegalStateException("Missing value for parameter " + paramName); } } else { value = constantValue; } Class<?> type = value.getClass(); if (type != targetType) { if (targetType == String.class) { return value.toString(); } else if (targetType == Boolean.class) { if (type == String.class) { return Boolean.valueOf((String) value); } } else if (targetType == Double.class) { if (type == String.class) { return Double.valueOf((String) value); } else if (Number.class.isAssignableFrom(type)) { return ((Number) value).doubleValue(); } } else if (targetType == Float.class) { if (type == String.class) { return Float.valueOf((String) value); } else if (Number.class.isAssignableFrom(type)) { return ((Number) value).floatValue(); } } else if (targetType == Long.class) { if (type == String.class) { return Long.valueOf((String) value); } else if (Number.class.isAssignableFrom(type)) { return ((Number) value).longValue(); } } else if (targetType == Integer.class) { if (type == String.class) { return Integer.valueOf((String) value); } else if (Number.class.isAssignableFrom(type)) { return ((Number) value).intValue(); } } else if (targetType == Short.class) { if (type == String.class) { return Short.valueOf((String) value); } else if (Number.class.isAssignableFrom(type)) { return ((Number) value).shortValue(); } } else if (targetType == Byte.class) { if (type == String.class) { return Byte.valueOf((String) value); } else if (Number.class.isAssignableFrom(type)) { return ((Number) value).byteValue(); } } else if (targetType == Date.class) { if (type == String.class) { try { return DateHelper.getJpaDateFormat().parse((String) value); } catch (ParseException e) { throw new RuntimeException(e); } } else if (Number.class.isAssignableFrom(type)) { return new Date(((Number) value).longValue()); } } else if (targetType == Instant.class) { if (type == String.class) { return Instant.parse((String) value); } else if (Number.class.isAssignableFrom(type)) { return Instant.ofEpochMilli(((Number) value).longValue()); } } //todo [anistor] continue with other commonsense conversions //todo [anistor] report illegal conversion } return value; } @Override public <T> T acceptVisitor(Visitor<?, ?> visitor) { return (T) visitor.visit(this); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ConstantValueExpr other = (ConstantValueExpr) o; return constantValue.equals(other.constantValue); } @Override public int hashCode() { return constantValue.hashCode(); } @Override public String toString() { String strVal; if (constantValue instanceof ParamPlaceholder) { strVal = constantValue.toString(); } else if (constantValue instanceof String) { strVal = "\"" + constantValue + "\""; } else if (constantValue instanceof Character) { strVal = "'" + constantValue + "'"; } else if (constantValue instanceof Date) { strVal = DateHelper.getJpaDateFormat().format((Date) constantValue); } else if (constantValue instanceof Instant) { strVal = constantValue.toString(); } else { strVal = String.valueOf(constantValue); } return "CONST(" + strVal + ')'; } @Override public String toQueryString() { if (constantValue instanceof ParamPlaceholder) { return constantValue.toString(); } if (constantValue instanceof String) { return "\"" + constantValue + "\""; } if (constantValue instanceof Character) { return "'" + constantValue + "'"; } if (constantValue instanceof Date) { return "'" + DateHelper.getJpaDateFormat().format((Date) constantValue) + "'"; } if (constantValue instanceof Instant) { return "'" + constantValue.toString() + "'"; } return "" + constantValue; } }
7,142
32.378505
138
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/OrExpr.java
package org.infinispan.objectfilter.impl.syntax; import java.util.List; /** * @author anistor@redhat.com * @since 7.0 */ public final class OrExpr extends BooleanOperatorExpr { public OrExpr(BooleanExpr... children) { super(children); } public OrExpr(List<BooleanExpr> children) { super(children); } @Override public <T> T acceptVisitor(Visitor<?, ?> visitor) { return (T) visitor.visit(this); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("OR("); boolean isFirst = true; for (BooleanExpr c : children) { if (isFirst) { isFirst = false; } else { sb.append(", "); } sb.append(c); } sb.append(')'); return sb.toString(); } @Override public String toQueryString() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < children.size(); i++) { if (i != 0) { sb.append(" OR "); } sb.append('(').append(children.get(i).toQueryString()).append(')'); } return sb.toString(); } }
1,153
20.773585
76
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/BooleanFilterNormalizer.java
package org.infinispan.objectfilter.impl.syntax; import java.util.ArrayList; import java.util.List; /** * Applies some optimisations to a boolean expression. Most notably, it brings it to NNF (Negation normal form, see * http://en.wikipedia.org/wiki/Negation_normal_form). Moves negation directly near the variable by repeatedly applying * the De Morgan's laws (see http://en.wikipedia.org/wiki/De_Morgan%27s_laws). Eliminates double negation. Normalizes * comparison operators by replacing 'greater' with 'less'. Detects sub-expressions that are boolean constants. * Simplifies boolean constants by applying boolean short-circuiting. Eliminates resulting trivial conjunctions or * disjunctions that have only one child. Ensures all paths from root to leafs contain an alternation of conjunction and * disjunction. This is achieved by absorbing the children whenever a boolean sub-expression if of the same kind as the * parent. * * @author anistor@redhat.com * @since 7.0 */ public final class BooleanFilterNormalizer { /** * A visitor that removes constant boolean expressions, absorbs sub-expressions (removes needless parentheses) and * swaps comparison operand sides to ensure the constant is always on the right side. */ private final ExprVisitor simplifierVisitor = new ExprVisitor() { @Override public BooleanExpr visit(NotExpr notExpr) { // push the negation down the tree until it reaches a PrimaryPredicateExpr return notExpr.getChild().acceptVisitor(deMorganVisitor); } @Override public BooleanExpr visit(OrExpr orExpr) { List<BooleanExpr> children = new ArrayList<>(orExpr.getChildren().size()); for (BooleanExpr child : orExpr.getChildren()) { child = child.acceptVisitor(this); if (child instanceof ConstantBooleanExpr) { // remove boolean constants or shortcircuit entirely if (((ConstantBooleanExpr) child).getValue()) { return ConstantBooleanExpr.TRUE; } } else if (child instanceof OrExpr) { // absorb sub-expressions of the same kind children.addAll(((OrExpr) child).getChildren()); } else { children.add(child); } } PredicateOptimisations.optimizePredicates(children, false); // simplify trivial expressions if (children.size() == 1) { return children.get(0); } return new OrExpr(children); } @Override public BooleanExpr visit(AndExpr andExpr) { List<BooleanExpr> children = new ArrayList<>(andExpr.getChildren().size()); for (BooleanExpr child : andExpr.getChildren()) { child = child.acceptVisitor(this); if (child instanceof ConstantBooleanExpr) { // remove boolean constants or shortcircuit entirely if (!((ConstantBooleanExpr) child).getValue()) { return ConstantBooleanExpr.FALSE; } } else if (child instanceof AndExpr) { // absorb sub-expressions of the same kind children.addAll(((AndExpr) child).getChildren()); } else { children.add(child); } } PredicateOptimisations.optimizePredicates(children, true); // simplify trivial expressions if (children.size() == 1) { return children.get(0); } return new AndExpr(children); } @Override public BooleanExpr visit(ComparisonExpr comparisonExpr) { // start moving the constant to the right side of the comparison if it's not already there ValueExpr leftChild = comparisonExpr.getLeftChild(); leftChild = leftChild.acceptVisitor(this); ValueExpr rightChild = comparisonExpr.getRightChild(); rightChild = rightChild.acceptVisitor(this); ComparisonExpr.Type comparisonType = comparisonExpr.getComparisonType(); // handle constant expressions if (leftChild instanceof ConstantValueExpr) { if (rightChild instanceof ConstantValueExpr) { // replace the comparison of the two constants with the actual result ConstantValueExpr leftConstant = (ConstantValueExpr) leftChild; ConstantValueExpr rightConstant = (ConstantValueExpr) rightChild; Comparable leftValue = leftConstant.getConstantValue(); Comparable rightValue = rightConstant.getConstantValue(); int compRes = leftValue.compareTo(rightValue); switch (comparisonType) { case LESS: return ConstantBooleanExpr.forBoolean(compRes < 0); case LESS_OR_EQUAL: return ConstantBooleanExpr.forBoolean(compRes <= 0); case EQUAL: return ConstantBooleanExpr.forBoolean(compRes == 0); case NOT_EQUAL: return ConstantBooleanExpr.forBoolean(compRes != 0); case GREATER_OR_EQUAL: return ConstantBooleanExpr.forBoolean(compRes >= 0); case GREATER: return ConstantBooleanExpr.forBoolean(compRes > 0); default: throw new IllegalStateException("Unexpected comparison type: " + comparisonType); } } // swap operand sides to ensure the constant is always on the right side ValueExpr temp = rightChild; rightChild = leftChild; leftChild = temp; // now reverse the operator too to restore the semantics comparisonType = comparisonType.reverse(); } // comparison operators are never negated using NotExpr return new ComparisonExpr(leftChild, rightChild, comparisonType); } @Override public BooleanExpr visit(BetweenExpr betweenExpr) { return new AndExpr( new ComparisonExpr(betweenExpr.getLeftChild(), betweenExpr.getFromChild(), ComparisonExpr.Type.GREATER_OR_EQUAL), new ComparisonExpr(betweenExpr.getLeftChild(), betweenExpr.getToChild(), ComparisonExpr.Type.LESS_OR_EQUAL) ); } }; /** * Handles negation by applying De Morgan laws. */ private final ExprVisitor deMorganVisitor = new ExprVisitor() { @Override public BooleanExpr visit(ConstantBooleanExpr constantBooleanExpr) { // negated constants are simplified immediately return constantBooleanExpr.negate(); } @Override public BooleanExpr visit(NotExpr notExpr) { // double negation is eliminated, child is simplified return notExpr.getChild().acceptVisitor(simplifierVisitor); } @Override public BooleanExpr visit(OrExpr orExpr) { List<BooleanExpr> children = new ArrayList<>(orExpr.getChildren().size()); for (BooleanExpr child : orExpr.getChildren()) { child = child.acceptVisitor(this); if (child instanceof ConstantBooleanExpr) { // remove boolean constants if (!((ConstantBooleanExpr) child).getValue()) { return ConstantBooleanExpr.FALSE; } } else if (child instanceof AndExpr) { // absorb sub-expressions of the same kind children.addAll(((AndExpr) child).getChildren()); } else { children.add(child); } } // simplify trivial expressions if (children.size() == 1) { return children.get(0); } return new AndExpr(children); } @Override public BooleanExpr visit(AndExpr andExpr) { List<BooleanExpr> children = new ArrayList<>(andExpr.getChildren().size()); for (BooleanExpr child : andExpr.getChildren()) { child = child.acceptVisitor(this); if (child instanceof ConstantBooleanExpr) { // remove boolean constants if (((ConstantBooleanExpr) child).getValue()) { return ConstantBooleanExpr.TRUE; } } else if (child instanceof OrExpr) { // absorb sub-expressions of the same kind children.addAll(((OrExpr) child).getChildren()); } else { children.add(child); } } // simplify trivial expressions if (children.size() == 1) { return children.get(0); } return new OrExpr(children); } @Override public BooleanExpr visit(ComparisonExpr comparisonExpr) { BooleanExpr booleanExpr = comparisonExpr.acceptVisitor(simplifierVisitor); // simplify negated constants immediately if (booleanExpr instanceof ConstantBooleanExpr) { return ((ConstantBooleanExpr) booleanExpr).negate(); } // eliminate double negation if (booleanExpr instanceof NotExpr) { return ((NotExpr) booleanExpr).getChild(); } // interval predicates are never negated, they are converted instead into the opposite interval if (booleanExpr instanceof ComparisonExpr) { ComparisonExpr c = (ComparisonExpr) booleanExpr; return new ComparisonExpr(c.getLeftChild(), c.getRightChild(), c.getComparisonType().negate()); } return new NotExpr(booleanExpr); } @Override public BooleanExpr visit(BetweenExpr betweenExpr) { return new OrExpr( new ComparisonExpr(betweenExpr.getLeftChild(), betweenExpr.getFromChild(), ComparisonExpr.Type.LESS), new ComparisonExpr(betweenExpr.getLeftChild(), betweenExpr.getToChild(), ComparisonExpr.Type.GREATER) ); } @Override public BooleanExpr visit(IsNullExpr isNullExpr) { return new NotExpr(isNullExpr); } @Override public BooleanExpr visit(LikeExpr likeExpr) { return new NotExpr(likeExpr); } }; public BooleanExpr normalize(BooleanExpr booleanExpr) { return booleanExpr == null ? null : booleanExpr.acceptVisitor(simplifierVisitor); } }
10,415
37.294118
128
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/parser/package-info.java
/** * The concrete implementation of the {@link org.infinispan.objectfilter.impl.ql.QueryRendererDelegate} and {@link * org.infinispan.objectfilter.impl.ql.QueryResolverDelegate} and the supporting classes for representing type * metadata and performing semantic analysis for the Ickle language. * * @author anistor@redhat.com * @since 9.0 * * @api.private */ package org.infinispan.objectfilter.impl.syntax.parser;
425
34.5
114
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/parser/ReflectionPropertyHelper.java
package org.infinispan.objectfilter.impl.syntax.parser; import java.util.Arrays; import java.util.List; import org.infinispan.objectfilter.impl.util.ReflectionHelper; /** * @author anistor@redhat.com * @since 7.0 */ public class ReflectionPropertyHelper extends ObjectPropertyHelper<Class<?>> { private final EntityNameResolver<Class<?>> entityNameResolver; public ReflectionPropertyHelper(EntityNameResolver<Class<?>> entityNameResolver) { if (entityNameResolver == null) { throw new IllegalArgumentException("The entityNameResolver argument cannot be null"); } this.entityNameResolver = entityNameResolver; } @Override public Class<?> getEntityMetadata(String typeName) { return entityNameResolver.resolve(typeName); } @Override public List<?> mapPropertyNamePathToFieldIdPath(Class<?> type, String[] propertyPath) { return Arrays.asList(propertyPath); } @Override public Class<?> getPrimitivePropertyType(Class<?> entityType, String[] propertyPath) { try { Class<?> propType = getPropertyAccessor(entityType, propertyPath).getPropertyType(); if (propType.isEnum()) { return propType; } return primitives.get(propType); } catch (ReflectiveOperationException e) { // ignored } return null; } @Override public boolean hasEmbeddedProperty(Class<?> entityType, String[] propertyPath) { try { Class<?> propType = getPropertyAccessor(entityType, propertyPath).getPropertyType(); return propType != null && !propType.isEnum() && !primitives.containsKey(propType); } catch (ReflectiveOperationException e) { return false; } } @Override public boolean isRepeatedProperty(Class<?> entityType, String[] propertyPath) { try { ReflectionHelper.PropertyAccessor a = ReflectionHelper.getAccessor(entityType, propertyPath[0]); if (a.isMultiple()) { return true; } for (int i = 1; i < propertyPath.length; i++) { a = a.getAccessor(propertyPath[i]); if (a.isMultiple()) { return true; } } } catch (ReflectiveOperationException e) { // ignored } return false; } @Override public boolean hasProperty(Class<?> entityType, String[] propertyPath) { try { Class<?> propType = getPropertyAccessor(entityType, propertyPath).getPropertyType(); return propType != null; } catch (ReflectiveOperationException e) { return false; } } private ReflectionHelper.PropertyAccessor getPropertyAccessor(Class<?> entityClass, String[] propertyPath) throws ReflectiveOperationException { if (propertyPath == null || propertyPath.length == 0) { throw new IllegalArgumentException("propertyPath name cannot be null or empty"); } ReflectionHelper.PropertyAccessor accessor = ReflectionHelper.getAccessor(entityClass, propertyPath[0]); for (int i = 1; i < propertyPath.length; i++) { accessor = accessor.getAccessor(propertyPath[i]); } return accessor; } }
3,204
32.041237
147
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/parser/ExpressionBuilder.java
package org.infinispan.objectfilter.impl.syntax.parser; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.List; import org.infinispan.objectfilter.impl.logging.Log; import org.infinispan.objectfilter.impl.ql.PropertyPath; import org.infinispan.objectfilter.impl.ql.QueryRendererDelegate; import org.infinispan.objectfilter.impl.syntax.AggregationExpr; import org.infinispan.objectfilter.impl.syntax.AndExpr; import org.infinispan.objectfilter.impl.syntax.BetweenExpr; import org.infinispan.objectfilter.impl.syntax.BooleanExpr; import org.infinispan.objectfilter.impl.syntax.ComparisonExpr; import org.infinispan.objectfilter.impl.syntax.ConstantBooleanExpr; import org.infinispan.objectfilter.impl.syntax.ConstantValueExpr; import org.infinispan.objectfilter.impl.syntax.FullTextBoostExpr; import org.infinispan.objectfilter.impl.syntax.FullTextOccurExpr; import org.infinispan.objectfilter.impl.syntax.FullTextRangeExpr; import org.infinispan.objectfilter.impl.syntax.FullTextRegexpExpr; import org.infinispan.objectfilter.impl.syntax.FullTextTermExpr; import org.infinispan.objectfilter.impl.syntax.IsNullExpr; import org.infinispan.objectfilter.impl.syntax.LikeExpr; import org.infinispan.objectfilter.impl.syntax.NotExpr; import org.infinispan.objectfilter.impl.syntax.OrExpr; import org.infinispan.objectfilter.impl.syntax.PropertyValueExpr; import org.jboss.logging.Logger; /** * Builder for the creation of WHERE/HAVING clause filters targeting a single entity. * <p/> * Implemented as a stack of {@link LazyBooleanExpr}s which allows to add elements to the constructed query in a * uniform manner while traversing through the original query parse tree. * * @author anistor@redhat.com * @since 9.0 */ final class ExpressionBuilder<TypeMetadata> { private static final Log log = Logger.getMessageLogger(Log.class, ExpressionBuilder.class.getName()); private final ObjectPropertyHelper<TypeMetadata> propertyHelper; private TypeMetadata entityType; /** * Keep track of all the parent expressions ({@code AND}, {@code OR}, {@code NOT}) of the WHERE/HAVING clause of the * built query. */ private final Deque<LazyBooleanExpr> stack = new ArrayDeque<>(); ExpressionBuilder(ObjectPropertyHelper<TypeMetadata> propertyHelper) { this.propertyHelper = propertyHelper; } public void setEntityType(TypeMetadata entityType) { this.entityType = entityType; stack.push(new LazyRootBooleanExpr()); } public void addFullTextTerm(PropertyPath<?> propertyPath, Object comparisonObject, Integer fuzzySlop) { push(new FullTextTermExpr(makePropertyValueExpr(propertyPath), comparisonObject, fuzzySlop)); } public void addFullTextRegexp(PropertyPath<?> propertyPath, String regexp) { push(new FullTextRegexpExpr(makePropertyValueExpr(propertyPath), regexp)); } public void addFullTextRange(PropertyPath<?> propertyPath, boolean includeLower, Object lower, Object upper, boolean includeUpper) { push(new FullTextRangeExpr(makePropertyValueExpr(propertyPath), includeLower, lower, upper, includeUpper)); } public void addComparison(PropertyPath<?> propertyPath, ComparisonExpr.Type comparisonType, Object value) { Comparable typedValue = (Comparable) propertyHelper.convertToBackendType(entityType, propertyPath.asArrayPath(), value); push(new ComparisonExpr(makePropertyValueExpr(propertyPath), new ConstantValueExpr(typedValue), comparisonType)); } public void addRange(PropertyPath<?> propertyPath, Object lower, Object upper) { Comparable lowerValue = (Comparable) propertyHelper.convertToBackendType(entityType, propertyPath.asArrayPath(), lower); Comparable upperValue = (Comparable) propertyHelper.convertToBackendType(entityType, propertyPath.asArrayPath(), upper); push(new BetweenExpr(makePropertyValueExpr(propertyPath), new ConstantValueExpr(lowerValue), new ConstantValueExpr(upperValue))); } public void addIn(PropertyPath<?> propertyPath, List<Object> values) { PropertyValueExpr valueExpr = makePropertyValueExpr(propertyPath); List<BooleanExpr> children = new ArrayList<>(values.size()); for (Object element : values) { //todo [anistor] need more efficient implementation Comparable typedValue = (Comparable) propertyHelper.convertToBackendType(entityType, propertyPath.asArrayPath(), element); ComparisonExpr booleanExpr = new ComparisonExpr(valueExpr, new ConstantValueExpr(typedValue), ComparisonExpr.Type.EQUAL); children.add(booleanExpr); } if (children.size() == 1) { // simplify INs with just one clause by removing the wrapper boolean expression push(children.get(0)); } else { push(new OrExpr(children)); } } public void addLike(PropertyPath<?> propertyPath, Object patternValue, Character escapeCharacter) { // TODO [anistor] escapeCharacter is ignored for now push(new LikeExpr(makePropertyValueExpr(propertyPath), patternValue)); } public void addIsNull(PropertyPath<?> propertyPath) { push(new IsNullExpr(makePropertyValueExpr(propertyPath))); } public void pushAnd() { push(new LazyAndExpr()); } public void pushOr() { push(new LazyOrExpr()); } public void pushNot() { push(new LazyNegationExpr()); } public void pushFullTextBoost(float boost) { push(new LazyFTBoostExpr(boost)); } public void pushFullTextOccur(QueryRendererDelegate.Occur occur) { push(new LazyFTOccurExpr(occur)); } private void push(BooleanExpr expr) { push(new LazyLeafBooleanExpr(expr)); } private void push(LazyBooleanExpr expr) { // add as sub-expression to the current top expression stack.peek().addChild(expr); // push to expression stack if required if (expr.isParent()) { stack.push(expr); } } public void pop() { stack.pop(); } public BooleanExpr build() { return stack.getFirst().get(); } private PropertyValueExpr makePropertyValueExpr(PropertyPath<?> propertyPath) { //todo [anistor] 2 calls to propertyHelper .. very inefficient boolean isRepeated = propertyHelper.isRepeatedProperty(entityType, propertyPath.asArrayPath()); Class<?> primitiveType = propertyHelper.getPrimitivePropertyType(entityType, propertyPath.asArrayPath()); if (propertyPath instanceof AggregationPropertyPath) { return new AggregationExpr((AggregationPropertyPath) propertyPath, isRepeated, primitiveType); } else { return new PropertyValueExpr(propertyPath, isRepeated, primitiveType); } } public void addConstantBoolean(boolean booleanConstant) { push(ConstantBooleanExpr.forBoolean(booleanConstant)); } /** * Delays construction until {@link #get} is called. */ abstract static class LazyBooleanExpr { /** * Indicates whether this expression can have sub-expressions or not. */ public boolean isParent() { return true; } /** * Adds the given lazy expression to this. * * @param child the child to add */ public abstract void addChild(LazyBooleanExpr child); /** * Returns the query represented by this lazy expression. Contains the all sub-expressions if this is a parent. * * @return the expression represented by this lazy expression */ public abstract BooleanExpr get(); } private static final class LazyLeafBooleanExpr extends LazyBooleanExpr { private final BooleanExpr booleanExpr; LazyLeafBooleanExpr(BooleanExpr booleanExpr) { this.booleanExpr = booleanExpr; } @Override public boolean isParent() { return false; } @Override public void addChild(LazyBooleanExpr child) { throw new UnsupportedOperationException("Adding a sub-expression to a non-parent expression is illegal"); } @Override public BooleanExpr get() { return booleanExpr; } } private static final class LazyAndExpr extends LazyBooleanExpr { private final List<LazyBooleanExpr> children = new ArrayList<>(3); @Override public void addChild(LazyBooleanExpr child) { children.add(child); } @Override public BooleanExpr get() { if (children.isEmpty()) { throw new IllegalStateException("A conjunction must have at least one child"); } BooleanExpr firstChild = children.get(0).get(); if (children.size() == 1) { return firstChild; } AndExpr andExpr = new AndExpr(firstChild); for (int i = 1; i < children.size(); i++) { BooleanExpr child = children.get(i).get(); andExpr.getChildren().add(child); } return andExpr; } } private static final class LazyOrExpr extends LazyBooleanExpr { private final List<LazyBooleanExpr> children = new ArrayList<>(3); @Override public void addChild(LazyBooleanExpr child) { children.add(child); } @Override public BooleanExpr get() { if (children.isEmpty()) { throw new IllegalStateException("A disjunction must have at least one child"); } BooleanExpr firstChild = children.get(0).get(); if (children.size() == 1) { return firstChild; } OrExpr orExpr = new OrExpr(firstChild); for (int i = 1; i < children.size(); i++) { BooleanExpr child = children.get(i).get(); orExpr.getChildren().add(child); } return orExpr; } } private static final class LazyNegationExpr extends LazyBooleanExpr { private LazyBooleanExpr child; @Override public void addChild(LazyBooleanExpr child) { if (this.child != null) { throw log.getNotMoreThanOnePredicateInNegationAllowedException(child); } this.child = child; } public LazyBooleanExpr getChild() { return child; } @Override public BooleanExpr get() { return new NotExpr(getChild().get()); } } private static final class LazyFTBoostExpr extends LazyBooleanExpr { private LazyBooleanExpr child; private final float boost; LazyFTBoostExpr(float boost) { this.boost = boost; } @Override public void addChild(LazyBooleanExpr child) { if (this.child != null) { throw log.getNotMoreThanOnePredicateInNegationAllowedException(child); } this.child = child; } public LazyBooleanExpr getChild() { return child; } @Override public BooleanExpr get() { return new FullTextBoostExpr(getChild().get(), boost); } } private static final class LazyFTOccurExpr extends LazyBooleanExpr { private LazyBooleanExpr child; private final QueryRendererDelegate.Occur occur; LazyFTOccurExpr(QueryRendererDelegate.Occur occur) { this.occur = occur; } @Override public void addChild(LazyBooleanExpr child) { if (this.child != null) { throw log.getNotMoreThanOnePredicateInNegationAllowedException(child); } this.child = child; } public LazyBooleanExpr getChild() { return child; } @Override public BooleanExpr get() { return new FullTextOccurExpr(getChild().get(), occur); } } private static final class LazyRootBooleanExpr extends LazyBooleanExpr { private LazyBooleanExpr child; @Override public void addChild(LazyBooleanExpr child) { if (this.child != null) { throw log.getNotMoreThanOnePredicateInRootOfWhereClauseAllowedException(child); } this.child = child; } @Override public BooleanExpr get() { return child == null ? null : child.get(); } } }
12,171
31.545455
135
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/parser/QueryRendererDelegateImpl.java
package org.infinispan.objectfilter.impl.syntax.parser; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import org.antlr.runtime.tree.Tree; import org.infinispan.objectfilter.SortField; import org.infinispan.objectfilter.impl.logging.Log; import org.infinispan.objectfilter.impl.ql.AggregationFunction; import org.infinispan.objectfilter.impl.ql.JoinType; import org.infinispan.objectfilter.impl.ql.PropertyPath; import org.infinispan.objectfilter.impl.ql.QueryRendererDelegate; import org.infinispan.objectfilter.impl.syntax.ComparisonExpr; import org.infinispan.objectfilter.impl.syntax.ConstantValueExpr; import org.infinispan.objectfilter.impl.syntax.IndexedFieldProvider; import org.infinispan.objectfilter.impl.syntax.parser.projection.CacheValuePropertyPath; import org.infinispan.objectfilter.impl.syntax.parser.projection.VersionPropertyPath; import org.jboss.logging.Logger; /** * Transform the parsed tree into a {@link IckleParsingResult} containing the {@link * org.infinispan.objectfilter.impl.syntax.BooleanExpr}s representing the WHERE and HAVING clauses of the query. * * @author Adrian Nistor * @since 9.0 */ final class QueryRendererDelegateImpl<TypeMetadata> implements QueryRendererDelegate<TypeDescriptor<TypeMetadata>> { private static final Log log = Logger.getMessageLogger(Log.class, QueryRendererDelegateImpl.class.getName()); /** * Initial length for various internal growable arrays. */ private static final int ARRAY_INITIAL_LENGTH = 5; private enum Phase { SELECT, FROM, WHERE, GROUP_BY, HAVING, ORDER_BY } /** * The current parsing phase */ private Phase phase; private IckleParsingResult.StatementType statementType; private String targetTypeName; private TypeMetadata targetEntityMetadata; private IndexedFieldProvider.FieldIndexingMetadata fieldIndexingMetadata; private PropertyPath<TypeDescriptor<TypeMetadata>> propertyPath; private AggregationFunction aggregationFunction; private final ExpressionBuilder<TypeMetadata> whereBuilder; private final ExpressionBuilder<TypeMetadata> havingBuilder; /** * Persister space: keep track of aliases and entity names. */ private final Map<String, String> aliasToEntityType = new HashMap<>(); private final Map<String, PropertyPath<TypeDescriptor<TypeMetadata>>> aliasToPropertyPath = new HashMap<>(); private String alias; private final Map<String, Object> namedParameters = new HashMap<>(ARRAY_INITIAL_LENGTH); private final ObjectPropertyHelper<TypeMetadata> propertyHelper; private List<PropertyPath<TypeDescriptor<TypeMetadata>>> groupBy; private List<SortField> sortFields; private List<PropertyPath<TypeDescriptor<TypeMetadata>>> projections; private List<Class<?>> projectedTypes; private List<Object> projectedNullMarkers; private final String queryString; QueryRendererDelegateImpl(String queryString, ObjectPropertyHelper<TypeMetadata> propertyHelper) { this.queryString = queryString; this.propertyHelper = propertyHelper; this.whereBuilder = new ExpressionBuilder<>(propertyHelper); this.havingBuilder = new ExpressionBuilder<>(propertyHelper); } /** * See rule entityName */ @Override public void registerPersisterSpace(String entityName, Tree aliasTree) { String aliasText = aliasTree.getText(); String previous = aliasToEntityType.put(aliasText, entityName); if (previous != null && !previous.equalsIgnoreCase(entityName)) { throw new UnsupportedOperationException("Alias reuse currently not supported: alias " + aliasText + " already assigned to type " + previous); } if (targetTypeName != null) { throw new IllegalStateException("Can't target multiple types: " + targetTypeName + " already selected before " + entityName); } targetTypeName = entityName; targetEntityMetadata = propertyHelper.getEntityMetadata(targetTypeName); if (targetEntityMetadata == null) { throw log.getUnknownEntity(targetTypeName); } fieldIndexingMetadata = propertyHelper.getIndexedFieldProvider().get(targetEntityMetadata); whereBuilder.setEntityType(targetEntityMetadata); havingBuilder.setEntityType(targetEntityMetadata); } // TODO [anistor] unused ?? public void registerEmbeddedAlias(String aliasText, PropertyPath<TypeDescriptor<TypeMetadata>> propertyPath) { PropertyPath<TypeDescriptor<TypeMetadata>> previous = aliasToPropertyPath.put(aliasText, propertyPath); if (previous != null) { throw new UnsupportedOperationException("Alias reuse currently not supported: alias " + aliasText + " already assigned to type " + previous); } } @Override public boolean isUnqualifiedPropertyReference() { return true; } @Override public boolean isPersisterReferenceAlias() { return aliasToEntityType.containsKey(alias); } @Override public void activateFromStrategy(JoinType joinType, Tree associationFetchTree, Tree propertyFetchTree, Tree alias) { phase = Phase.FROM; this.alias = alias.getText(); } @Override public void activateSelectStrategy() { phase = Phase.SELECT; statementType = IckleParsingResult.StatementType.SELECT; } @Override public void activateDeleteStrategy() { phase = Phase.SELECT; // Not a mistake, DELETE is parsed similarly to a SELECT statementType = IckleParsingResult.StatementType.DELETE; } @Override public void activateWhereStrategy() { phase = Phase.WHERE; } @Override public void activateGroupByStrategy() { phase = Phase.GROUP_BY; } @Override public void activateHavingStrategy() { phase = Phase.HAVING; } @Override public void activateOrderByStrategy() { phase = Phase.ORDER_BY; } @Override public void deactivateStrategy() { phase = null; alias = null; propertyPath = null; aggregationFunction = null; } @Override public void activateOR() { if (phase == Phase.WHERE) { whereBuilder.pushOr(); } else if (phase == Phase.HAVING) { havingBuilder.pushOr(); } else { throw new IllegalStateException(); } } @Override public void activateAND() { if (phase == Phase.WHERE) { whereBuilder.pushAnd(); } else if (phase == Phase.HAVING) { havingBuilder.pushAnd(); } else { throw new IllegalStateException(); } } @Override public void activateNOT() { if (phase == Phase.WHERE) { whereBuilder.pushNot(); } else if (phase == Phase.HAVING) { havingBuilder.pushNot(); } else { throw new IllegalStateException(); } } @Override public void predicateLess(String value) { addComparisonPredicate(value, ComparisonExpr.Type.LESS); } @Override public void predicateLessOrEqual(String value) { addComparisonPredicate(value, ComparisonExpr.Type.LESS_OR_EQUAL); } /** * This implements the equality predicate; the comparison * predicate could be a constant, a subfunction or * some random type parameter. * The tree node has all details but with current tree rendering * it just passes it's text so we have to figure out the options again. */ @Override public void predicateEquals(String value) { addComparisonPredicate(value, ComparisonExpr.Type.EQUAL); } @Override public void predicateNotEquals(String value) { activateNOT(); addComparisonPredicate(value, ComparisonExpr.Type.EQUAL); deactivateBoolean(); } @Override public void predicateGreaterOrEqual(String value) { addComparisonPredicate(value, ComparisonExpr.Type.GREATER_OR_EQUAL); } @Override public void predicateGreater(String value) { addComparisonPredicate(value, ComparisonExpr.Type.GREATER); } private void addComparisonPredicate(String value, ComparisonExpr.Type comparisonType) { ensureLeftSideIsAPropertyPath(); PropertyPath<TypeDescriptor<TypeMetadata>> property = resolveAlias(propertyPath); if (property.isEmpty()) { throw log.getPredicatesOnEntityAliasNotAllowedException(propertyPath.asStringPath()); } Object comparisonValue = parameterValue(value); checkAnalyzed(property, false); if (phase == Phase.WHERE) { whereBuilder.addComparison(property, comparisonType, comparisonValue); } else if (phase == Phase.HAVING) { havingBuilder.addComparison(property, comparisonType, comparisonValue); } else { throw new IllegalStateException(); } } @Override public void predicateIn(List<String> list) { ensureLeftSideIsAPropertyPath(); List<Object> values = new ArrayList<>(list.size()); for (String string : list) { values.add(parameterValue(string)); } PropertyPath<TypeDescriptor<TypeMetadata>> property = resolveAlias(propertyPath); if (property.isEmpty()) { throw log.getPredicatesOnEntityAliasNotAllowedException(propertyPath.asStringPath()); } if (phase == Phase.WHERE) { whereBuilder.addIn(property, values); } else if (phase == Phase.HAVING) { havingBuilder.addIn(property, values); } else { throw new IllegalStateException(); } } @Override public void predicateBetween(String lowerValue, String upperValue) { ensureLeftSideIsAPropertyPath(); Object lowerComparisonValue = parameterValue(lowerValue); Object upperComparisonValue = parameterValue(upperValue); PropertyPath<TypeDescriptor<TypeMetadata>> property = resolveAlias(propertyPath); if (property.isEmpty()) { throw log.getPredicatesOnEntityAliasNotAllowedException(propertyPath.asStringPath()); } checkAnalyzed(property, false); if (phase == Phase.WHERE) { whereBuilder.addRange(property, lowerComparisonValue, upperComparisonValue); } else if (phase == Phase.HAVING) { havingBuilder.addRange(property, lowerComparisonValue, upperComparisonValue); } else { throw new IllegalStateException(); } } @Override public void predicateLike(String patternValue, Character escapeCharacter) { ensureLeftSideIsAPropertyPath(); Object pattern = parameterValue(patternValue); PropertyPath<TypeDescriptor<TypeMetadata>> property = resolveAlias(propertyPath); if (property.isEmpty()) { throw log.getPredicatesOnEntityAliasNotAllowedException(propertyPath.asStringPath()); } checkAnalyzed(property, false); if (phase == Phase.WHERE) { whereBuilder.addLike(property, pattern, escapeCharacter); } else if (phase == Phase.HAVING) { havingBuilder.addLike(property, pattern, escapeCharacter); } else { throw new IllegalStateException(); } } @Override public void predicateIsNull() { ensureLeftSideIsAPropertyPath(); PropertyPath<TypeDescriptor<TypeMetadata>> property = resolveAlias(propertyPath); if (property.isEmpty()) { throw log.getPredicatesOnEntityAliasNotAllowedException(propertyPath.asStringPath()); } checkAnalyzed(property, false); if (phase == Phase.WHERE) { whereBuilder.addIsNull(property); } else if (phase == Phase.HAVING) { havingBuilder.addIsNull(property); } else { throw new IllegalStateException(); } } @Override public void predicateConstantBoolean(boolean booleanConstant) { if (phase == Phase.WHERE) { whereBuilder.addConstantBoolean(booleanConstant); } else if (phase == Phase.HAVING) { havingBuilder.addConstantBoolean(booleanConstant); } else { throw new IllegalStateException(); } } @Override public void predicateFullTextTerm(String term, String fuzzyFlop) { ensureLeftSideIsAPropertyPath(); PropertyPath<TypeDescriptor<TypeMetadata>> property = resolveAlias(propertyPath); if (property.isEmpty()) { throw log.getPredicatesOnEntityAliasNotAllowedException(propertyPath.asStringPath()); } if (phase == Phase.WHERE) { checkAnalyzed(property, true); Object comparisonObject = parameterValue(term); whereBuilder.addFullTextTerm(property, comparisonObject, fuzzyFlop == null ? null : (fuzzyFlop.equals("~") ? 2 : Integer.parseInt(fuzzyFlop))); } else if (phase == Phase.HAVING) { throw log.getFullTextQueriesNotAllowedInHavingClauseException(); } else { throw new IllegalStateException(); } } @Override public void predicateFullTextRegexp(String term) { ensureLeftSideIsAPropertyPath(); PropertyPath<TypeDescriptor<TypeMetadata>> property = resolveAlias(propertyPath); if (property.isEmpty()) { throw log.getPredicatesOnEntityAliasNotAllowedException(propertyPath.asStringPath()); } if (phase == Phase.WHERE) { checkAnalyzed(property, true); whereBuilder.addFullTextRegexp(property, term); } else if (phase == Phase.HAVING) { throw log.getFullTextQueriesNotAllowedInHavingClauseException(); } else { throw new IllegalStateException(); } } @Override public void predicateFullTextRange(boolean includeLower, String lower, String upper, boolean includeUpper) { ensureLeftSideIsAPropertyPath(); if (phase == Phase.WHERE) { PropertyPath<TypeDescriptor<TypeMetadata>> property = resolveAlias(propertyPath); if (property.isEmpty()) { throw log.getPredicatesOnEntityAliasNotAllowedException(propertyPath.asStringPath()); } Object from = lower != null ? parameterValue(lower) : null; Object to = upper != null ? parameterValue(upper) : null; checkIndexed(property); whereBuilder.addFullTextRange(property, includeLower, from, to, includeUpper); } else if (phase == Phase.HAVING) { throw log.getFullTextQueriesNotAllowedInHavingClauseException(); } else { throw new IllegalStateException(); } } private void checkAnalyzed(PropertyPath<?> propertyPath, boolean expectAnalyzed) { if (fieldIndexingMetadata.isAnalyzed(propertyPath.asArrayPath())) { if (!expectAnalyzed) { throw log.getQueryOnAnalyzedPropertyNotSupportedException(targetTypeName, propertyPath.asStringPath()); } } else { if (expectAnalyzed) { throw log.getFullTextQueryOnNotAalyzedPropertyNotSupportedException(targetTypeName, propertyPath.asStringPath()); } } } private void checkIndexed(PropertyPath<?> propertyPath) { if (!fieldIndexingMetadata.isIndexed(propertyPath.asArrayPath())) { throw log.getFullTextQueryOnNotIndexedPropertyNotSupportedException(targetTypeName, propertyPath.asStringPath()); } } @Override public void activateFullTextBoost(float boost) { if (phase == Phase.WHERE) { whereBuilder.pushFullTextBoost(boost); } else if (phase == Phase.HAVING) { throw log.getFullTextQueriesNotAllowedInHavingClauseException(); } else { throw new IllegalStateException(); } } @Override public void deactivateFullTextBoost() { if (phase == Phase.WHERE) { whereBuilder.pop(); } else if (phase == Phase.HAVING) { throw log.getFullTextQueriesNotAllowedInHavingClauseException(); } else { throw new IllegalStateException(); } } @Override public void activateFullTextOccur(Occur occur) { if (phase == Phase.WHERE) { whereBuilder.pushFullTextOccur(occur); } else if (phase == Phase.HAVING) { throw log.getFullTextQueriesNotAllowedInHavingClauseException(); } else { throw new IllegalStateException(); } } @Override public void deactivateFullTextOccur() { if (phase == Phase.WHERE) { whereBuilder.pop(); } else if (phase == Phase.HAVING) { throw log.getFullTextQueriesNotAllowedInHavingClauseException(); } else { throw new IllegalStateException(); } } /** * Sets a property path representing one property in the SELECT, GROUP BY, WHERE or HAVING clause of a given query. * * @param propertyPath the property path to set */ @Override public void setPropertyPath(PropertyPath<TypeDescriptor<TypeMetadata>> propertyPath) { if (aggregationFunction != null) { if (propertyPath == null && aggregationFunction != AggregationFunction.COUNT && aggregationFunction != AggregationFunction.COUNT_DISTINCT) { throw log.getAggregationCanOnlyBeAppliedToPropertyReferencesException(aggregationFunction.name()); } propertyPath = new AggregationPropertyPath<>(aggregationFunction, propertyPath.getNodes()); } if (phase == Phase.SELECT) { if (projections == null) { projections = new ArrayList<>(ARRAY_INITIAL_LENGTH); projectedTypes = new ArrayList<>(ARRAY_INITIAL_LENGTH); projectedNullMarkers = new ArrayList<>(ARRAY_INITIAL_LENGTH); } PropertyPath<TypeDescriptor<TypeMetadata>> projection; Class<?> propertyType; Object nullMarker; if (propertyPath.getLength() == 1 && propertyPath.isAlias()) { projection = new CacheValuePropertyPath<>(); propertyType = null; nullMarker = null; } else { projection = resolveAlias(propertyPath); propertyType = propertyHelper.getPrimitivePropertyType(targetEntityMetadata, projection.asArrayPath()); nullMarker = fieldIndexingMetadata.getNullMarker(projection.asArrayPath()); } projections.add(projection); projectedTypes.add(propertyType); projectedNullMarkers.add(nullMarker); } else { this.propertyPath = propertyPath; } } @Override public void activateAggregation(AggregationFunction aggregationFunction) { if (phase == Phase.WHERE) { throw log.getNoAggregationsInWhereClauseException(aggregationFunction.name()); } if (phase == Phase.GROUP_BY) { throw log.getNoAggregationsInGroupByClauseException(aggregationFunction.name()); } this.aggregationFunction = aggregationFunction; propertyPath = null; } @Override public void deactivateAggregation() { aggregationFunction = null; } @Override public void projectVersion() { if (phase != Phase.SELECT) { return; // do nothing } if (projections == null) { projections = new ArrayList<>(ARRAY_INITIAL_LENGTH); projectedTypes = new ArrayList<>(ARRAY_INITIAL_LENGTH); projectedNullMarkers = new ArrayList<>(ARRAY_INITIAL_LENGTH); } projections.add(new VersionPropertyPath<>()); projectedTypes.add(Object.class); // Usually a core module EntryVersion projectedNullMarkers.add(null); } /** * Add field sort criteria. * * @param collateName optional collation name * @param isAscending sort direction */ @Override public void sortSpecification(String collateName, boolean isAscending) { // collationName is ignored for now PropertyPath<TypeDescriptor<TypeMetadata>> property = resolveAlias(propertyPath); checkAnalyzed(property, false); //todo [anistor] cannot sort on analyzed field? if (sortFields == null) { sortFields = new ArrayList<>(ARRAY_INITIAL_LENGTH); } sortFields.add(new IckleParsingResult.SortFieldImpl<>(property, isAscending)); } /** * Add 'group by' criteria. * * @param collateName optional collation name */ @Override public void groupingValue(String collateName) { // collationName is ignored for now if (groupBy == null) { groupBy = new ArrayList<>(ARRAY_INITIAL_LENGTH); } groupBy.add(resolveAlias(propertyPath)); } private Object parameterValue(String value) { if (value.startsWith(":")) { // it's a named parameter String paramName = value.substring(1).trim(); //todo [anistor] trim should not be required! ConstantValueExpr.ParamPlaceholder namedParam = (ConstantValueExpr.ParamPlaceholder) namedParameters.get(paramName); if (namedParam == null) { namedParam = new ConstantValueExpr.ParamPlaceholder(paramName); namedParameters.put(paramName, namedParam); } return namedParam; } else { // it's a literal value given in the query string List<String> path = propertyPath.getNodeNamesWithoutAlias(); // create the complete path in case it's a join PropertyPath<TypeDescriptor<TypeMetadata>> fullPath = propertyPath; while (fullPath.isAlias()) { PropertyPath<TypeDescriptor<TypeMetadata>> resolved = aliasToPropertyPath.get(fullPath.getFirst().getPropertyName()); if (resolved == null) { break; } path.addAll(0, resolved.getNodeNamesWithoutAlias()); fullPath = resolved; } return propertyHelper.convertToPropertyType(targetEntityMetadata, path.toArray(new String[path.size()]), value); } } @Override public void deactivateBoolean() { if (phase == Phase.WHERE) { whereBuilder.pop(); } else if (phase == Phase.HAVING) { havingBuilder.pop(); } else { throw new IllegalStateException(); } } private PropertyPath<TypeDescriptor<TypeMetadata>> resolveAlias(PropertyPath<TypeDescriptor<TypeMetadata>> path) { List<PropertyPath.PropertyReference<TypeDescriptor<TypeMetadata>>> resolved = resolveAliasPath(path); return path instanceof AggregationPropertyPath ? new AggregationPropertyPath<>(((AggregationPropertyPath) path).getAggregationFunction(), resolved) : new PropertyPath<>(resolved); } private List<PropertyPath.PropertyReference<TypeDescriptor<TypeMetadata>>> resolveAliasPath(PropertyPath<TypeDescriptor<TypeMetadata>> path) { if (path.isAlias()) { String alias = path.getFirst().getPropertyName(); if (aliasToEntityType.containsKey(alias)) { // Alias for entity return path.getNodesWithoutAlias(); } else if (aliasToPropertyPath.containsKey(alias)) { // Alias for embedded PropertyPath<TypeDescriptor<TypeMetadata>> propertyPath = aliasToPropertyPath.get(alias); List<PropertyPath.PropertyReference<TypeDescriptor<TypeMetadata>>> resolvedAlias = resolveAliasPath(propertyPath); resolvedAlias.addAll(path.getNodesWithoutAlias()); return resolvedAlias; } else { // Alias not found throw log.getUnknownAliasException(alias); } } // It does not start with an alias return path.getNodesWithoutAlias(); } @Override public void registerJoinAlias(Tree alias, PropertyPath<TypeDescriptor<TypeMetadata>> path) { if (!aliasToPropertyPath.containsKey(alias.getText())) { aliasToPropertyPath.put(alias.getText(), path); } } private void ensureLeftSideIsAPropertyPath() { if (propertyPath == null) { throw log.getLeftSideMustBeAPropertyPath(); } } public IckleParsingResult<TypeMetadata> getResult() { return new IckleParsingResult<>( queryString, statementType, Collections.unmodifiableSet(new HashSet<>(namedParameters.keySet())), whereBuilder.build(), havingBuilder.build(), targetTypeName, targetEntityMetadata, projections == null ? null : projections.toArray(new PropertyPath[projections.size()]), projectedTypes == null ? null : projectedTypes.toArray(new Class<?>[projectedTypes.size()]), projectedNullMarkers == null ? null : projectedNullMarkers.toArray(new Object[projectedNullMarkers.size()]), groupBy == null ? null : groupBy.toArray(new PropertyPath[groupBy.size()]), sortFields == null ? null : sortFields.toArray(new SortField[sortFields.size()])); } }
24,662
35.269118
152
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/parser/EmbeddedEntityTypeDescriptor.java
package org.infinispan.objectfilter.impl.syntax.parser; import java.util.List; /** * @author anistor@redhat.com * @since 7.0 */ final class EmbeddedEntityTypeDescriptor<TypeMetadata> extends EntityTypeDescriptor<TypeMetadata> { private final List<String> propertyPath; /** * Creates a new {@link EmbeddedEntityTypeDescriptor}. * * @param entityType the entity into which this entity is embedded * @param entityMetadata the actual entity type representation * @param path the property path from the embedding entity to this entity */ EmbeddedEntityTypeDescriptor(String entityType, TypeMetadata entityMetadata, List<String> path) { super(entityType, entityMetadata); this.propertyPath = path; } @Override public String[] makePath(String propName) { String[] newPath = new String[propertyPath.size() + 1]; newPath = propertyPath.toArray(newPath); newPath[newPath.length - 1] = propName; return newPath; } @Override public String toString() { return propertyPath.toString(); } }
1,095
27.842105
100
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/parser/EntityTypeDescriptor.java
package org.infinispan.objectfilter.impl.syntax.parser; import org.infinispan.objectfilter.impl.util.StringHelper; /** * @author anistor@redhat.com * @since 7.0 */ class EntityTypeDescriptor<TypeMetadata> implements TypeDescriptor<TypeMetadata> { private final String typeName; private final TypeMetadata entityMetadata; EntityTypeDescriptor(String typeName, TypeMetadata entityMetadata) { this.typeName = typeName; this.entityMetadata = entityMetadata; } @Override public String getTypeName() { return typeName; } @Override public TypeMetadata getTypeMetadata() { return entityMetadata; } public String[] makePath(String propName) { return StringHelper.split(propName); } @Override public String toString() { return typeName; } }
824
20.153846
82
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/parser/AggregationPropertyPath.java
package org.infinispan.objectfilter.impl.syntax.parser; import java.util.List; import org.infinispan.objectfilter.impl.logging.Log; import org.infinispan.objectfilter.impl.ql.AggregationFunction; import org.infinispan.objectfilter.impl.ql.PropertyPath; import org.jboss.logging.Logger; /** * An aggregated property path (e.g. {@code SUM(foo.bar.baz)}) represented by {@link PropertyReference}s * used with an aggregation function in the SELECT, HAVING or ORDER BY clause. * * @author anistor@redhat.com * @since 9.0 */ public final class AggregationPropertyPath<TypeMetadata> extends PropertyPath<TypeDescriptor<TypeMetadata>> { private static final Log log = Logger.getMessageLogger(Log.class, AggregationPropertyPath.class.getName()); private final AggregationFunction aggregationFunction; AggregationPropertyPath(AggregationFunction aggregationFunction, List<PropertyReference<TypeDescriptor<TypeMetadata>>> path) { super(path); switch (aggregationFunction) { case SUM: case AVG: case MIN: case MAX: case COUNT: break; default: throw log.getAggregationTypeNotSupportedException(aggregationFunction.name()); } this.aggregationFunction = aggregationFunction; } public AggregationFunction getAggregationFunction() { return aggregationFunction; } @Override public boolean equals(Object o) { if (!super.equals(o)) return false; AggregationPropertyPath<?> that = (AggregationPropertyPath<?>) o; return aggregationFunction == that.aggregationFunction; } @Override public int hashCode() { return 31 * super.hashCode() + aggregationFunction.hashCode(); } @Override public String toString() { return aggregationFunction.name() + "(" + asStringPath() + ")"; } }
1,853
30.423729
129
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/parser/RowPropertyHelper.java
package org.infinispan.objectfilter.impl.syntax.parser; import java.util.Collections; import java.util.List; /** * @author anistor@redhat.com * @since 8.0 */ public final class RowPropertyHelper extends ObjectPropertyHelper<RowPropertyHelper.RowMetadata> { public static final class RowMetadata { private final ColumnMetadata[] columns; RowMetadata(ColumnMetadata[] columns) { this.columns = columns; } public ColumnMetadata[] getColumns() { return columns; } } public static final class ColumnMetadata { private final int columnIndex; private final String columnName; private final Class<?> type; public ColumnMetadata(int columnIndex, String columnName, Class<?> type) { this.columnIndex = columnIndex; this.columnName = columnName; this.type = type; } public Object getValue(Object instance) { return ((Object[]) instance)[columnIndex]; } public int getColumnIndex() { return columnIndex; } public String getColumnName() { return columnName; } public Class<?> getPropertyType() { return type; } @Override public String toString() { return "ColumnMetadata{" + "columnIndex=" + columnIndex + ", columnName='" + columnName + '\'' + ", type=" + type + '}'; } } private final RowMetadata rowMetadata; public RowPropertyHelper(RowPropertyHelper.ColumnMetadata[] columns) { this.rowMetadata = new RowPropertyHelper.RowMetadata(columns); } public RowMetadata getRowMetadata() { return rowMetadata; } @Override public RowMetadata getEntityMetadata(String typeName) { // the type name is ignored in this case! return rowMetadata; } @Override public List<?> mapPropertyNamePathToFieldIdPath(RowMetadata type, String[] propertyPath) { if (propertyPath.length > 1) { throw new IllegalStateException("Nested attributes are not supported"); } String columnName = propertyPath[0]; for (RowPropertyHelper.ColumnMetadata c : rowMetadata.getColumns()) { if (c.getColumnName().equals(columnName)) { return Collections.singletonList(c.getColumnIndex()); } } throw new IllegalArgumentException("Column not found : " + columnName); } @Override public Class<?> getPrimitivePropertyType(RowPropertyHelper.RowMetadata entityType, String[] propertyPath) { // entityType is ignored in this case! Class<?> propType = getColumnAccessor(propertyPath).getPropertyType(); if (propType.isEnum() || primitives.containsKey(propType)) { return propType; } return null; } private ColumnMetadata getColumnAccessor(String[] propertyPath) { if (propertyPath.length > 1) { throw new IllegalStateException("Nested attributes are not supported"); } String columnName = propertyPath[0]; for (RowPropertyHelper.ColumnMetadata c : rowMetadata.getColumns()) { if (c.getColumnName().equals(columnName)) { return c; } } throw new IllegalArgumentException("Column not found : " + columnName); } @Override public boolean hasProperty(RowPropertyHelper.RowMetadata entityType, String[] propertyPath) { if (propertyPath.length > 1) { throw new IllegalStateException("Nested attributes are not supported"); } String columnName = propertyPath[0]; for (RowPropertyHelper.ColumnMetadata c : rowMetadata.getColumns()) { if (c.getColumnName().equals(columnName)) { return true; } } return false; } @Override public boolean hasEmbeddedProperty(RowPropertyHelper.RowMetadata entityType, String[] propertyPath) { return false; } @Override public boolean isRepeatedProperty(RowPropertyHelper.RowMetadata entityType, String[] propertyPath) { return false; } }
4,095
26.675676
110
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/parser/ObjectPropertyHelper.java
package org.infinispan.objectfilter.impl.syntax.parser; import java.text.ParseException; import java.time.Instant; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.infinispan.objectfilter.impl.logging.Log; import org.infinispan.objectfilter.impl.syntax.IndexedFieldProvider; import org.infinispan.objectfilter.impl.util.DateHelper; import org.infinispan.objectfilter.impl.util.StringHelper; import org.jboss.logging.Logger; /** * Provides property metadata when dealing with entities. * * @author anistor@redhat.com * @since 7.0 */ public abstract class ObjectPropertyHelper<TypeMetadata> { private static final Log log = Logger.getMessageLogger(Log.class, ObjectPropertyHelper.class.getName()); /** * A map of all types that we consider to be 'primitives'. They are mapped to the equivalent 'boxed' type. */ protected static final Map<Class<?>, Class<?>> primitives = new HashMap<>(); static { primitives.put(java.util.Date.class, java.util.Date.class); primitives.put(java.time.Instant.class, java.time.Instant.class); primitives.put(String.class, String.class); primitives.put(Character.class, Character.class); primitives.put(char.class, Character.class); primitives.put(Double.class, Double.class); primitives.put(double.class, Double.class); primitives.put(Float.class, Float.class); primitives.put(float.class, Float.class); primitives.put(Long.class, Long.class); primitives.put(long.class, Long.class); primitives.put(Integer.class, Integer.class); primitives.put(int.class, Integer.class); primitives.put(Short.class, Short.class); primitives.put(short.class, Short.class); primitives.put(Byte.class, Byte.class); primitives.put(byte.class, Byte.class); primitives.put(Boolean.class, Boolean.class); primitives.put(boolean.class, Boolean.class); } protected ObjectPropertyHelper() { } /** * Lookup a type by name and return the metadata that represents it. * * @param typeName the fully qualified type name * @return the metadata representation */ public abstract TypeMetadata getEntityMetadata(String typeName); /** * Returns the given value converted into the type of the given property as determined via the field bridge of the * property. * * @param value the value to convert * @param entityType the type hosting the property * @param propertyPath the name of the property * @return the given value converted into the type of the given property */ public Object convertToPropertyType(TypeMetadata entityType, String[] propertyPath, String value) { final Class<?> propertyType = getPrimitivePropertyType(entityType, propertyPath); if (propertyType == null) { // not a primitive, then it is an embedded entity, need to signal an invalid query throw log.getPredicatesOnCompleteEmbeddedEntitiesNotAllowedException(StringHelper.join(propertyPath)); } if (Date.class.isAssignableFrom(propertyType)) { try { return DateHelper.getJpaDateFormat().parse(value); } catch (ParseException e) { throw log.getInvalidDateLiteralException(value); } } if (Instant.class.isAssignableFrom(propertyType)) { return Instant.parse(value); } if (Enum.class.isAssignableFrom(propertyType)) { try { return Enum.valueOf((Class<Enum>) propertyType, value); } catch (IllegalArgumentException e) { throw log.getInvalidEnumLiteralException(value, propertyType.getName()); } } if (propertyType == String.class) { return value; } if (propertyType == Character.class || propertyType == char.class) { return value.charAt(0); } try { if (propertyType == Double.class || propertyType == double.class) { return Double.valueOf(value); } if (propertyType == Float.class || propertyType == float.class) { return Float.valueOf(value); } if (propertyType == Long.class || propertyType == long.class) { return Long.valueOf(value); } if (propertyType == Integer.class || propertyType == int.class) { return Integer.valueOf(value); } if (propertyType == Short.class || propertyType == short.class) { return Short.valueOf(value); } if (propertyType == Byte.class || propertyType == byte.class) { return Byte.valueOf(value); } } catch (NumberFormatException ex) { throw log.getInvalidNumericLiteralException(value); } if (propertyType == Boolean.class || propertyType == boolean.class) { if ("true".equalsIgnoreCase(value)) { return true; } else if ("false".equalsIgnoreCase(value)) { return false; } else { throw log.getInvalidBooleanLiteralException(value); } } return value; } /** * Returns the type of the primitive property. * * @param entityType the TypeMetadata of the entity * @param propertyPath the path of the property * @return the {@link Class} or {@code null} if not present or not a primitive property */ public abstract Class<?> getPrimitivePropertyType(TypeMetadata entityType, String[] propertyPath); public abstract boolean hasProperty(TypeMetadata entityType, String[] propertyPath); public abstract boolean hasEmbeddedProperty(TypeMetadata entityType, String[] propertyPath); /** * Tests if the attribute path contains repeated (collection/array) attributes. */ public abstract boolean isRepeatedProperty(TypeMetadata entityType, String[] propertyPath); public IndexedFieldProvider<TypeMetadata> getIndexedFieldProvider() { return typeMetadata -> IndexedFieldProvider.NO_INDEXING; } public abstract List<?> mapPropertyNamePathToFieldIdPath(TypeMetadata type, String[] propertyPath); /** * Converts the given property value (usually a String representation coming right from the user's query string) into * the type expected by the query backend. * * @param entityType the entity type owning the property * @param propertyPath the path from the entity to the property (will only contain more than one element in case the * entity is hosted on an embedded entity). * @param value the value of the property * @return the property value, converted into the type expected by the query backend */ public Object convertToBackendType(TypeMetadata entityType, String[] propertyPath, Object value) { return value; } }
6,868
36.741758
120
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/parser/EntityNameResolver.java
package org.infinispan.objectfilter.impl.syntax.parser; /** * @author anistor@redhat.com * @since 9.0 */ @FunctionalInterface public interface EntityNameResolver<TypeMetadata> { //TODO [anistor] ISPN-11986, now that all types are predeclared for indexed caches we could be able to resolve unqualified type names too TypeMetadata resolve(String typeName); }
368
27.384615
140
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/parser/IckleParsingResult.java
package org.infinispan.objectfilter.impl.syntax.parser; import java.util.Arrays; import java.util.Set; import org.infinispan.objectfilter.SortField; import org.infinispan.objectfilter.impl.ql.PropertyPath; import org.infinispan.objectfilter.impl.syntax.BooleanExpr; /** * @param <TypeMetadata> is either {@link java.lang.Class} or {@link org.infinispan.protostream.descriptors.Descriptor} * @author anistor@redhat.com * @since 7.0 */ public final class IckleParsingResult<TypeMetadata> { public enum StatementType { SELECT, DELETE; private static final StatementType[] CACHED_VALUES = StatementType.values(); public static StatementType valueOf(int index) { return CACHED_VALUES[index]; } } static final class SortFieldImpl<TypeMetadata> implements SortField { public final PropertyPath<TypeDescriptor<TypeMetadata>> path; public final boolean isAscending; SortFieldImpl(PropertyPath<TypeDescriptor<TypeMetadata>> path, boolean isAscending) { this.path = path; this.isAscending = isAscending; } public PropertyPath<TypeDescriptor<TypeMetadata>> getPath() { return path; } public boolean isAscending() { return isAscending; } @Override public String toString() { return "SortField(" + path + ", " + (isAscending ? "ASC" : "DESC") + ')'; } } private final String queryString; private final StatementType statementType; private final Set<String> parameterNames; private final BooleanExpr whereClause; private final BooleanExpr havingClause; private final String targetEntityName; private final TypeMetadata targetEntityMetadata; private final PropertyPath[] projectedPaths; private final Class<?>[] projectedTypes; private final Object[] projectedNullMarkers; private final PropertyPath[] groupBy; private final SortField[] sortFields; //todo [anistor] make package local public IckleParsingResult(String queryString, StatementType statementType, Set<String> parameterNames, BooleanExpr whereClause, BooleanExpr havingClause, String targetEntityName, TypeMetadata targetEntityMetadata, PropertyPath[] projectedPaths, Class<?>[] projectedTypes, Object[] projectedNullMarkers, PropertyPath[] groupBy, SortField[] sortFields) { this.queryString = queryString; this.statementType = statementType; this.parameterNames = parameterNames; this.whereClause = whereClause; this.havingClause = havingClause; this.targetEntityName = targetEntityName; this.targetEntityMetadata = targetEntityMetadata; if (projectedPaths != null && (projectedTypes == null || projectedTypes.length != projectedPaths.length) || projectedPaths == null && projectedTypes != null) { throw new IllegalArgumentException("projectedPaths and projectedTypes sizes must match"); } this.projectedPaths = projectedPaths; this.projectedTypes = projectedTypes; this.projectedNullMarkers = projectedNullMarkers; this.groupBy = groupBy; this.sortFields = sortFields; } public String getQueryString() { return queryString; } public StatementType getStatementType() { return statementType; } public Set<String> getParameterNames() { return parameterNames; } /** * Returns the filter created while walking the parse tree. * * @return the filter created while walking the parse tree */ public BooleanExpr getWhereClause() { return whereClause; } public BooleanExpr getHavingClause() { return havingClause; } /** * Returns the original entity name as given in the query * * @return the entity name of the query */ public String getTargetEntityName() { return targetEntityName; } /** * Returns the entity type of the parsed query. * * @return the entity type of the parsed query */ public TypeMetadata getTargetEntityMetadata() { return targetEntityMetadata; } /** * Returns the projections of the parsed query, represented as dot paths in case of references to fields of embedded * entities, e.g. {@code ["foo", "bar.qaz"]}. * * @return an array with the projections of the parsed query or null if the query has no projections */ public String[] getProjections() { if (projectedPaths == null) { return null; } String[] projections = new String[projectedPaths.length]; for (int i = 0; i < projectedPaths.length; i++) { projections[i] = projectedPaths[i].asStringPath(); } return projections; } public PropertyPath[] getProjectedPaths() { return projectedPaths; } public Class<?>[] getProjectedTypes() { return projectedTypes; } public Object[] getProjectedNullMarkers() { return projectedNullMarkers; } public boolean hasGroupingOrAggregations() { if (groupBy != null || havingClause != null) { return true; } if (projectedPaths != null) { for (PropertyPath<?> p : projectedPaths) { if (p instanceof AggregationPropertyPath) { return true; } } } if (sortFields != null) { for (SortField s : sortFields) { if (s.getPath() instanceof AggregationPropertyPath) { return true; } } } return false; } public PropertyPath[] getGroupBy() { return groupBy; } public SortField[] getSortFields() { return sortFields; } @Override public String toString() { return "FilterParsingResult [" + " queryString=" + queryString + ", statementType=" + statementType + ", targetEntityName=" + targetEntityName + ", parameterNames=" + parameterNames + ", whereClause=" + whereClause + ", havingClause=" + havingClause + ", projectedPaths=" + Arrays.toString(projectedPaths) + ", projectedTypes=" + Arrays.toString(projectedTypes) + ", projectedNullMarkers=" + Arrays.toString(projectedNullMarkers) + ", groupBy=" + Arrays.toString(groupBy) + ", sortFields=" + Arrays.toString(sortFields) + "]"; } }
6,600
30.28436
165
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/parser/TypeDescriptor.java
package org.infinispan.objectfilter.impl.syntax.parser; /** * @author anistor@redhat.com * @since 7.0 */ public interface TypeDescriptor<TypeMetadata> { /** * Returns the type name of the represented entity. * * @return the type name of the represented entity. */ String getTypeName(); /** * Returns the actual internal representation the entity. It might be a Class, or anything else. * * @return the internal representation the entity. */ TypeMetadata getTypeMetadata(); String[] makePath(String propName); }
565
21.64
99
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/parser/IckleParser.java
package org.infinispan.objectfilter.impl.syntax.parser; import org.infinispan.objectfilter.ParsingException; import org.infinispan.objectfilter.impl.ql.QueryParser; /** * @author anistor@redhat.com * @since 9.0 */ public final class IckleParser { private static final QueryParser queryParser = new QueryParser(); private IckleParser() { } public static <TypeMetadata> IckleParsingResult<TypeMetadata> parse(String queryString, ObjectPropertyHelper<TypeMetadata> propertyHelper) { QueryResolverDelegateImpl<TypeMetadata> resolverDelegate = new QueryResolverDelegateImpl<>(propertyHelper); QueryRendererDelegateImpl<TypeMetadata> rendererDelegate = new QueryRendererDelegateImpl<>(queryString, propertyHelper); queryParser.parseQuery(queryString, resolverDelegate, rendererDelegate); IckleParsingResult<TypeMetadata> result = rendererDelegate.getResult(); if (result.getStatementType() == IckleParsingResult.StatementType.DELETE && (result.getProjections() != null || result.getSortFields() != null || result.getGroupBy() != null)) { throw new ParsingException("DELETE statements cannot have projections or use ORDER BY or GROUP BY"); } return result; } }
1,240
41.793103
143
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/parser/QueryResolverDelegateImpl.java
package org.infinispan.objectfilter.impl.syntax.parser; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.antlr.runtime.tree.Tree; import org.infinispan.objectfilter.impl.logging.Log; import org.infinispan.objectfilter.impl.ql.JoinType; import org.infinispan.objectfilter.impl.ql.PropertyPath; import org.infinispan.objectfilter.impl.ql.QueryResolverDelegate; import org.jboss.logging.Logger; /** * @author anistor@redhat.com * @since 7.0 */ final class QueryResolverDelegateImpl<TypeMetadata> implements QueryResolverDelegate<TypeDescriptor<TypeMetadata>> { private static final Log log = Logger.getMessageLogger(Log.class, QueryResolverDelegateImpl.class.getName()); private final Map<String, String> aliasToEntityType = new HashMap<>(); private final Map<String, PropertyPath<TypeDescriptor<TypeMetadata>>> aliasToPropertyPath = new HashMap<>(); private final ObjectPropertyHelper<TypeMetadata> propertyHelper; private String targetType; private TypeMetadata entityMetadata; private String alias; private enum Phase { SELECT, FROM } private Phase phase; QueryResolverDelegateImpl(ObjectPropertyHelper<TypeMetadata> propertyHelper) { this.propertyHelper = propertyHelper; } @Override public void registerPersisterSpace(String entityName, Tree aliasTree) { String aliasText = aliasTree.getText(); String prevAlias = aliasToEntityType.put(aliasText, entityName); if (prevAlias != null && !prevAlias.equalsIgnoreCase(entityName)) { throw new UnsupportedOperationException("Alias reuse currently not supported: alias " + aliasText + " already assigned to type " + prevAlias); } if (targetType != null) { throw new IllegalStateException("Can't target multiple types: " + targetType + " already selected before " + entityName); } targetType = entityName; entityMetadata = propertyHelper.getEntityMetadata(entityName); if (entityMetadata == null) { throw log.getUnknownEntity(entityName); } } @Override public void registerJoinAlias(Tree alias, PropertyPath<TypeDescriptor<TypeMetadata>> path) { if (!path.isEmpty() && !aliasToPropertyPath.containsKey(alias.getText())) { aliasToPropertyPath.put(alias.getText(), path); } } @Override public boolean isUnqualifiedPropertyReference() { return true; } @Override public PropertyPath.PropertyReference<TypeDescriptor<TypeMetadata>> normalizeUnqualifiedPropertyReference(Tree propertyNameTree) { String property = propertyNameTree.getText(); if (aliasToEntityType.containsKey(property)) { return normalizeQualifiedRoot(propertyNameTree); } EntityTypeDescriptor<TypeMetadata> type = new EntityTypeDescriptor<>(targetType, entityMetadata); return normalizeProperty(type, Collections.emptyList(), property); } @Override public boolean isPersisterReferenceAlias() { return aliasToEntityType.containsKey(alias); } @Override public PropertyPath.PropertyReference<TypeDescriptor<TypeMetadata>> normalizeUnqualifiedRoot(Tree aliasTree) { String alias = aliasTree.getText(); if (aliasToEntityType.containsKey(alias)) { return normalizeQualifiedRoot(aliasTree); } PropertyPath<TypeDescriptor<TypeMetadata>> propertyPath = aliasToPropertyPath.get(alias); if (propertyPath == null) { throw log.getUnknownAliasException(alias); } List<String> resolvedAlias = resolveAlias(propertyPath); TypeDescriptor<TypeMetadata> sourceType = propertyPath.getFirst().getTypeDescriptor(); EmbeddedEntityTypeDescriptor<TypeMetadata> type = new EmbeddedEntityTypeDescriptor<>(sourceType.getTypeName(), sourceType.getTypeMetadata(), resolvedAlias); return new PropertyPath.PropertyReference<>(alias, type, true); } @Override public PropertyPath.PropertyReference<TypeDescriptor<TypeMetadata>> normalizeQualifiedRoot(Tree root) { String alias = root.getText(); String entityNameForAlias = aliasToEntityType.get(alias); if (entityNameForAlias == null) { PropertyPath<TypeDescriptor<TypeMetadata>> propertyPath = aliasToPropertyPath.get(alias); if (propertyPath == null) { throw log.getUnknownAliasException(alias); } return new PropertyPath.PropertyReference<>(propertyPath.asStringPathWithoutAlias(), null, false); } TypeMetadata entityMetadata = propertyHelper.getEntityMetadata(entityNameForAlias); if (entityMetadata == null) { throw log.getUnknownEntity(entityNameForAlias); } return new PropertyPath.PropertyReference<>(alias, new EntityTypeDescriptor<>(entityNameForAlias, entityMetadata), true); } @Override public PropertyPath.PropertyReference<TypeDescriptor<TypeMetadata>> normalizePropertyPathIntermediary(PropertyPath<TypeDescriptor<TypeMetadata>> path, Tree propertyNameTree) { String propertyName = propertyNameTree.getText(); TypeDescriptor<TypeMetadata> sourceType = path.getLast().getTypeDescriptor(); if (!propertyHelper.hasProperty(sourceType.getTypeMetadata(), sourceType.makePath(propertyName))) { throw log.getNoSuchPropertyException(sourceType.getTypeName(), propertyName); } List<String> newPath = resolveAlias(path); newPath.add(propertyName); EmbeddedEntityTypeDescriptor<TypeMetadata> type = new EmbeddedEntityTypeDescriptor<>(sourceType.getTypeName(), sourceType.getTypeMetadata(), newPath); return new PropertyPath.PropertyReference<>(propertyName, type, false); } private List<String> resolveAlias(PropertyPath<TypeDescriptor<TypeMetadata>> path) { if (path.isAlias()) { String alias = path.getFirst().getPropertyName(); if (aliasToEntityType.containsKey(alias)) { // Alias for entity return path.getNodeNamesWithoutAlias(); } else if (aliasToPropertyPath.containsKey(alias)) { // Alias for embedded PropertyPath<TypeDescriptor<TypeMetadata>> propertyPath = aliasToPropertyPath.get(alias); List<String> resolvedAlias = resolveAlias(propertyPath); resolvedAlias.addAll(path.getNodeNamesWithoutAlias()); return resolvedAlias; } else { // Alias not found throw log.getUnknownAliasException(alias); } } // It does not start with an alias return path.getNodeNamesWithoutAlias(); } @Override public PropertyPath.PropertyReference<TypeDescriptor<TypeMetadata>> normalizeIntermediateIndexOperation(PropertyPath.PropertyReference<TypeDescriptor<TypeMetadata>> propertyReference, Tree collectionProperty, Tree selector) { throw new UnsupportedOperationException("Not implemented"); } @Override public void normalizeTerminalIndexOperation(PropertyPath.PropertyReference<TypeDescriptor<TypeMetadata>> propertyReference, Tree collectionProperty, Tree selector) { throw new UnsupportedOperationException("Not implemented"); } @Override public PropertyPath.PropertyReference<TypeDescriptor<TypeMetadata>> normalizeUnqualifiedPropertyReferenceSource(Tree identifier) { throw new UnsupportedOperationException("Not implemented"); } @Override public PropertyPath.PropertyReference<TypeDescriptor<TypeMetadata>> normalizePropertyPathTerminus(PropertyPath<TypeDescriptor<TypeMetadata>> path, Tree propertyNameTree) { // receives the property name on a specific entity reference _source_ return normalizeProperty(path.getLast().getTypeDescriptor(), path.getNodeNamesWithoutAlias(), propertyNameTree.getText()); } private PropertyPath.PropertyReference<TypeDescriptor<TypeMetadata>> normalizeProperty(TypeDescriptor<TypeMetadata> type, List<String> path, String propertyName) { String[] propertyPath = type.makePath(propertyName); if (!propertyHelper.hasProperty(type.getTypeMetadata(), propertyPath)) { throw log.getNoSuchPropertyException(type.getTypeName(), propertyName); } TypeDescriptor<TypeMetadata> propType = null; if (propertyHelper.hasEmbeddedProperty(type.getTypeMetadata(), propertyPath)) { List<String> newPath = new LinkedList<>(path); newPath.add(propertyName); propType = new EmbeddedEntityTypeDescriptor<>(type.getTypeName(), type.getTypeMetadata(), newPath); } return new PropertyPath.PropertyReference<>(propertyName, propType, false); } @Override public void activateFromStrategy(JoinType joinType, Tree associationFetchTree, Tree propertyFetchTree, Tree aliasTree) { phase = Phase.FROM; alias = aliasTree.getText(); } @Override public void activateSelectStrategy() { phase = Phase.SELECT; } @Override public void activateDeleteStrategy() { } @Override public void deactivateStrategy() { phase = null; alias = null; } @Override public void propertyPathCompleted(PropertyPath<TypeDescriptor<TypeMetadata>> path) { if (phase == Phase.SELECT) { TypeDescriptor<TypeMetadata> type = path.getLast().getTypeDescriptor(); if (type instanceof EmbeddedEntityTypeDescriptor<?>) { throw log.getProjectionOfCompleteEmbeddedEntitiesNotSupportedException(type.getTypeName(), path.asStringPathWithoutAlias()); } } } }
9,557
39.846154
228
java