/** * Get the query plan for the given collection HQL filter fragment, creating it and caching it if not already cached * * @param filterString The HQL filter fragment * @param collectionRole The collection being filtered * @param shallow Whether the execution will be shallow * @param enabledFilters The filters enabled on the Session * * @return The query plan * * @throws QueryException Indicates a problem translating the query * @throws MappingException Indicates a problem translating the query */ @SuppressWarnings("unchecked") public FilterQueryPlan getFilterQueryPlan( String filterString, String collectionRole, boolean shallow, Map<String,Filter> enabledFilters) throws QueryException, MappingException { final FilterQueryPlanKey key = new FilterQueryPlanKey( filterString, collectionRole, shallow, enabledFilters ); FilterQueryPlan value = (FilterQueryPlan) queryPlanCache.get( key ); if ( value == null ) { LOG.tracev( "Unable to locate collection-filter query plan in cache; generating ({0} : {1} )", collectionRole, filterString ); value = new FilterQueryPlan( filterString, collectionRole, shallow, enabledFilters,factory ); queryPlanCache.putIfAbsent( key, value ); } else { LOG.tracev( "Located collection-filter query plan in cache ({0} : {1})", collectionRole, filterString ); } return value; }
/** * Set the named parameter's value list for this filter. Used * in conjunction with IN-style filter criteria. * * @param name The parameter's name. * @param values The values to be expanded into an SQL IN list. * @return This FilterImpl instance (for method chaining). */ public Filter setParameterList(String name, Collection values) throws HibernateException { // Make sure this is a defined parameter and check the incoming value type if ( values == null ) { throw new IllegalArgumentException( "Collection must be not null!" ); } Type type = definition.getParameterType( name ); if ( type == null ) { throw new HibernateException( "Undefined filter parameter [" + name + "]" ); } if ( !values.isEmpty() ) { Class elementClass = values.iterator().next().getClass(); if ( !type.getReturnedClass().isAssignableFrom( elementClass ) ) { throw new HibernateException( "Incorrect type for parameter [" + name + "]" ); } } parameters.put( name, values ); return this; }
/** * Constructs a number of FilterKey instances, given the currently enabled filters * * @param enabledFilters The currently enabled filters * * @return The filter keys, one per enabled filter */ public static Set<FilterKey> createFilterKeys(Map<String,Filter> enabledFilters) { if ( enabledFilters.size() == 0 ) { return null; } final Set<FilterKey> result = new HashSet<FilterKey>(); for ( Filter filter : enabledFilters.values() ) { final FilterKey key = new FilterKey( filter.getName(), ( (FilterImpl) filter ).getParameters(), filter.getFilterDefinition().getParameterTypes() ); result.add( key ); } return result; }
@Test public void testExecuteWithThreadBoundAndParameterizedFilter() { Filter filter = mock(Filter.class); given(session.isOpen()).willReturn(true); given(session.enableFilter("myFilter")).willReturn(filter); hibernateTemplate.setAllowCreate(false); hibernateTemplate.setFilterName("myFilter"); TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session)); try { final List l = new ArrayList(); l.add("test"); Filter f = hibernateTemplate.enableFilter("myFilter"); assertTrue("Correct filter", f == filter); } finally { TransactionSynchronizationManager.unbindResource(sessionFactory); } InOrder ordered = inOrder(session); ordered.verify(session).getEnabledFilter("myFilter"); ordered.verify(session).enableFilter("myFilter"); }
@Test public void testExecuteWithThreadBoundAndParameterizedExistingFilter() { Filter filter = mock(Filter.class); given(session.isOpen()).willReturn(true); given(session.enableFilter("myFilter")).willReturn(filter); hibernateTemplate.setAllowCreate(false); hibernateTemplate.setFilterName("myFilter"); TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session)); try { final List l = new ArrayList(); l.add("test"); Filter f = hibernateTemplate.enableFilter("myFilter"); assertTrue("Correct filter", f == filter); } finally { TransactionSynchronizationManager.unbindResource(sessionFactory); } verify(session).getEnabledFilter("myFilter"); }
/** * Set the named parameter's value list for this filter. Used * in conjunction with IN-style filter criteria. * * @param name The parameter's name. * @param values The values to be expanded into an SQL IN list. * @return This FilterImpl instance (for method chaining). */ public Filter setParameterList(String name, Collection values) throws HibernateException { // Make sure this is a defined parameter and check the incoming value type if ( values == null ) { throw new IllegalArgumentException( "Collection must be not null!" ); } Type type = definition.getParameterType( name ); if ( type == null ) { throw new HibernateException( "Undefined filter parameter [" + name + "]" ); } if ( values.size() > 0 ) { Class elementClass = values.iterator().next().getClass(); if ( !type.getReturnedClass().isAssignableFrom( elementClass ) ) { throw new HibernateException( "Incorrect type for parameter [" + name + "]" ); } } parameters.put( name, values ); return this; }
private void configureHibernateGlobalFilter(Filter filter) { String filterLanguage = null; if (getLocale() != null) { filterLanguage = getLocale().getLanguage(); } if (filterLanguage == null) { filterLanguage = ""; } String filterLogin = null; if (getApplicationSession().getPrincipal() != null) { filterLogin = getApplicationSession().getUsername(); } if (filterLogin == null) { filterLogin = ""; } filter.setParameter(JSPRESSO_SESSION_GLOBALS_LANGUAGE, filterLanguage); filter.setParameter(JSPRESSO_SESSION_GLOBALS_LOGIN, filterLogin); }
public void doBefore(final JoinPoint joinPoint, final EntityFilter annotation) { Filter f = sessionFactory.getCurrentSession().enableFilter( annotation.filter()); String expression; Integer paramNumber; Expression exp; Object subject; Object[] params = joinPoint.getArgs(); for (FilterAttribute attribute : annotation.params()) { if (ELParser.isMethodParamExpression(attribute.path())) { paramNumber = ELParser.getParamNumber(attribute.path()); expression = ELParser.removeParamNumber(attribute.path()); exp = parser.parseExpression(expression); subject = params[paramNumber]; } else { exp = parser.parseExpression(attribute.path()); subject = joinPoint.getTarget(); } f.setParameter(attribute.name(), exp.getValue(subject)); } }
public void enableFilter(Session session) { Client client = (Client) sessionObjectsService.getSessionObject(ClientContextObjectContributor.CONTEXT_OBJECT_CLIENT_NAME); if (client != null) { LOG.debug("New session created, enabling filter for client selection"); Filter filter = session.enableFilter(CLIENT_FILTER_NAME); filter.setParameter("client", client.getId()); List<String> organizationList = new ArrayList<String>(); for (Organization org : ((Client) session.get(Client.class, client.getId())).getOrganizations()) { organizationList.add(org.getId()); } filter = session.enableFilter(CLIENT_ORGANIZATION_FILTER_NAME); if (organizationList.size() == 0) { organizationList.add("NULL_EXPECT_NEVER_HAS_THIS_KEY_BECAUSE_THE_STRING_HAS_MORE_LEN THAN THE PERMITTED_KEY"); } filter.setParameterList("organizationList", organizationList); } else { LOG.debug("Client filter not enabling because client is not established"); } }
private boolean switchFilter(String filter, CfFlowState flowType, Date startDate, Date endDate, Class clazz, Session session) { log.debug("filter:" + filter); log.debug("clazz:" + clazz); Filter hqlFilter; try { if (filter == null) filter = ""; if (null == flowType) { hqlFilter = session.enableFilter("filter3_" + clazz.getSimpleName()); hqlFilter.setParameter("filter", "%" + filter + "%"); hqlFilter.setParameter("startDate", startDate); hqlFilter.setParameter("endDate", endDate); } else { hqlFilter = session.enableFilter("filter4_" + clazz.getSimpleName()); hqlFilter.setParameter("filter", "%" + filter + "%"); hqlFilter.setParameter("flowState", flowType.ordinal()); hqlFilter.setParameter("startDate", startDate); hqlFilter.setParameter("endDate", endDate); } } catch (Exception e) { e.printStackTrace(); return true; } return false; }
@Override public Filter enableFilter(String filterName) throws IllegalStateException { Session session = getSessionFactory().getCurrentSession(); Filter filter = session.getEnabledFilter(filterName); if (filter == null) { filter = session.enableFilter(filterName); } return filter; }
@Override public Filter enableFilter(String filterName) throws IllegalStateException { Session session = SessionFactoryUtils.getSession(getSessionFactory(), false); Filter filter = session.getEnabledFilter(filterName); if (filter == null) { filter = session.enableFilter(filterName); } return filter; }
/** * Get the query plan for the given HQL query, creating it and caching it if not already cached * * @param queryString The HQL query string * @param shallow Whether the execution will be shallow * @param enabledFilters The filters enabled on the Session * * @return The query plan * * @throws QueryException Indicates a problem translating the query * @throws MappingException Indicates a problem translating the query */ @SuppressWarnings("unchecked") public HQLQueryPlan getHQLQueryPlan(String queryString, boolean shallow, Map<String,Filter> enabledFilters) throws QueryException, MappingException { final HQLQueryPlanKey key = new HQLQueryPlanKey( queryString, shallow, enabledFilters ); HQLQueryPlan value = (HQLQueryPlan) queryPlanCache.get( key ); if ( value == null ) { LOG.tracev( "Unable to locate HQL query plan in cache; generating ({0})", queryString ); value = new HQLQueryPlan( queryString, shallow, enabledFilters, factory ); queryPlanCache.putIfAbsent( key, value ); } else { LOG.tracev( "Located HQL query plan in cache ({0})", queryString ); } return value; }
public Map<String,Filter> getEnabledFilters() { // First, validate all the enabled filters... //TODO: this implementation has bad performance for ( Filter filter : enabledFilters.values() ) { filter.validate(); } return enabledFilters; }
/** * Set the named parameter's value for this filter. * * @param name The parameter's name. * @param value The value to be applied. * @return This FilterImpl instance (for method chaining). * @throws IllegalArgumentException Indicates that either the parameter was undefined or that the type * of the passed value did not match the configured type. */ public Filter setParameter(String name, Object value) throws IllegalArgumentException { // Make sure this is a defined parameter and check the incoming value type // TODO: what should be the actual exception type here? Type type = definition.getParameterType( name ); if ( type == null ) { throw new IllegalArgumentException( "Undefined filter parameter [" + name + "]" ); } if ( value != null && !type.getReturnedClass().isAssignableFrom( value.getClass() ) ) { throw new IllegalArgumentException( "Incorrect type for parameter [" + name + "]" ); } parameters.put( name, value ); return this; }
@Test public void testExecuteWithThreadBoundAndParameterizedFilter() { Filter filter = mock(Filter.class); given(session.enableFilter("myFilter")).willReturn(filter); hibernateTemplate.setFilterNames("myFilter"); final List l = new ArrayList(); l.add("test"); Filter f = hibernateTemplate.enableFilter("myFilter"); assertTrue("Correct filter", f == filter); InOrder ordered = inOrder(session); ordered.verify(session).getEnabledFilter("myFilter"); ordered.verify(session).enableFilter("myFilter"); }
@Test public void testExecuteWithThreadBoundAndParameterizedExistingFilter() { Filter filter = mock(Filter.class); given(session.enableFilter("myFilter")).willReturn(filter); hibernateTemplate.setFilterNames("myFilter"); final List l = new ArrayList(); l.add("test"); Filter f = hibernateTemplate.enableFilter("myFilter"); assertTrue("Correct filter", f == filter); verify(session).getEnabledFilter("myFilter"); }
public Filter enableFilter(String filterName) { errorIfClosed(); checkTransactionSynchStatus(); FilterImpl filter = new FilterImpl( factory.getFilterDefinition(filterName) ); enabledFilters.put(filterName, filter); return filter; }
public Map getEnabledFilters() { errorIfClosed(); checkTransactionSynchStatus(); // First, validate all the enabled filters... //TODO: this implementation has bad performance Iterator itr = enabledFilters.values().iterator(); while ( itr.hasNext() ) { final Filter filter = (Filter) itr.next(); filter.validate(); } return enabledFilters; }
/** * Return an enabled Hibernate {@link Filter} for the given filter name. The returned {@code Filter} instance can be used to set filter parameters. * * @param filterName the name of the filter * @return the enabled Hibernate {@code Filter} (either already enabled or enabled on the fly by this operation) * @throws IllegalStateException if we are not running within a transactional Session (in which case this operation does not make sense) */ @Override public Filter enableFilter(final String filterName) throws IllegalStateException { Session session = SessionFactoryUtils2.getSession(getSessionFactory(), false); Filter filter = session.getEnabledFilter(filterName); if (filter == null) { filter = session.enableFilter(filterName); } return filter; }
public Filter enableFilter(String filterName) throws IllegalStateException { Session session = SessionFactoryUtils.getSession(getSessionFactory(), false); Filter filter = session.getEnabledFilter(filterName); if (filter == null) { filter = session.enableFilter(filterName); } return filter; }
public void applyFilter(Session session) { for (int i = 0; i < filterNames.size(); i++) { Filter filter = session.enableFilter(filterNames.get(i)); HashMap<String, Object> params = filterParams.get(i); for (Entry<String, Object> filterParam : params.entrySet()) { filter.setParameter(filterParam.getKey(), filterParam.getValue()); } } }
public static void mainCardsAnnotated() { //HibernateUtil.setupDatabase(); primeDatabase(); AnnotationConfiguration configuration = new AnnotationConfiguration(); SessionFactory factory = configuration.configure("test/gov/nih/nci/security/instancelevel/domainobjects/annotated.hibernate.cfg.xml").buildSessionFactory(); Session session = factory.openSession(); Transaction tx = session.beginTransaction(); Map fds= configuration.getFilterDefinitions(); //Show all users System.out.println("ALL CARDS"); displayCards(session); //Show Cards with Suit Name = Heart Filter filter = session.enableFilter("cardName"); filter.setParameter("cardName","Ace"); System.out.println("Annotated: Cards with cardName = Ace"); displayCards(session); /* //Show activated users Filter filter = session.enableFilter("activatedFilter"); filter.setParameter("activatedParam",new Boolean(true)); System.out.println("ACTIVATED USERS"); displayUsers(session); //Show non-activated users filter.setParameter("activatedParam",new Boolean(false)); System.out.println("NON-ACTIVATED USERS"); displayUsers(session); */ session.close(); HibernateUtil.closeDatabaseConnection(); //HibernateUtil.checkData("select * from User"); }
public static void mainCardsNonAnnotated() { HibernateUtil.setupDatabase(); primeDatabase(); Configuration c = new Configuration(); SessionFactory factory = c.configure("test/gov/nih/nci/security/instancelevel/domainobjects/nonannotated.hibernate.cfg.xml").buildSessionFactory(); Session session = factory.openSession(); Transaction tx = session.beginTransaction(); //Show all users System.out.println("ALL CARDS"); displayCards(session); //Show Cards with Suit Name = Heart /* Filter filter = session.enableFilter("cardName"); filter.setParameter("cardName","Ace");*/ Filter filter2 = session.enableFilter("imageName"); filter2.setParameter("imageName","Ace1"); System.out.println("Non Annotated: Cards with imageName = Ace1"); displayCards(session); /* //Show activated users Filter filter = session.enableFilter("activatedFilter"); filter.setParameter("activatedParam",new Boolean(true)); System.out.println("ACTIVATED USERS"); displayUsers(session); //Show non-activated users filter.setParameter("activatedParam",new Boolean(false)); System.out.println("NON-ACTIVATED USERS"); displayUsers(session); */ session.close(); HibernateUtil.closeDatabaseConnection(); //HibernateUtil.checkData("select * from User"); }
public static void mainUsers() { //HibernateUtil.setupDatabase(); //primeDatabase(); //insert the users insertUser("a",true);/* insertUser("b",true); insertUser("c",false); insertUser("e",false); insertUser("e",false);*/ AnnotationConfiguration configuration = new AnnotationConfiguration(); SessionFactory factory = configuration.configure().buildSessionFactory(); Session session = factory.openSession(); Transaction tx = session.beginTransaction(); //Show all users System.out.println("ALL USERS"); displayUsers(session); //Show activated users Map fds= configuration.getFilterDefinitions(); Filter filter = session.enableFilter("activatedFilter"); filter.setParameter("activatedParam",new Boolean(true)); System.out.println("ACTIVATED USERS"); displayUsers(session); //Show non-activated users filter.setParameter("activatedParam",new Boolean(false)); System.out.println("NON-ACTIVATED USERS"); displayUsers(session); session.close(); //HibernateUtil.checkData("select * from User"); }
public HQLQueryPlan(String hql, boolean shallow, Map<String,Filter> enabledFilters, SessionFactoryImplementor factory, EntityGraphQueryHint entityGraphQueryHint) { this( hql, null, shallow, enabledFilters, factory, entityGraphQueryHint ); }
@SuppressWarnings("unchecked") protected HQLQueryPlan( String hql, String collectionRole, boolean shallow, Map<String,Filter> enabledFilters, SessionFactoryImplementor factory, EntityGraphQueryHint entityGraphQueryHint) { this.sourceQuery = hql; this.shallow = shallow; final Set<String> copy = new HashSet<String>(); copy.addAll( enabledFilters.keySet() ); this.enabledFilterNames = java.util.Collections.unmodifiableSet( copy ); final String[] concreteQueryStrings = QuerySplitter.concreteQueries( hql, factory ); final int length = concreteQueryStrings.length; this.translators = new QueryTranslator[length]; final List<String> sqlStringList = new ArrayList<String>(); final Set<Serializable> combinedQuerySpaces = new HashSet<Serializable>(); final boolean hasCollectionRole = (collectionRole == null); final Map querySubstitutions = factory.getSettings().getQuerySubstitutions(); final QueryTranslatorFactory queryTranslatorFactory = factory.getSettings().getQueryTranslatorFactory(); for ( int i=0; i<length; i++ ) { if ( hasCollectionRole ) { translators[i] = queryTranslatorFactory .createQueryTranslator( hql, concreteQueryStrings[i], enabledFilters, factory, entityGraphQueryHint ); translators[i].compile( querySubstitutions, shallow ); } else { translators[i] = queryTranslatorFactory .createFilterTranslator( hql, concreteQueryStrings[i], enabledFilters, factory ); ( (FilterTranslator) translators[i] ).compile( collectionRole, querySubstitutions, shallow ); } combinedQuerySpaces.addAll( translators[i].getQuerySpaces() ); sqlStringList.addAll( translators[i].collectSqlStrings() ); } this.sqlStrings = ArrayHelper.toStringArray( sqlStringList ); this.querySpaces = combinedQuerySpaces; if ( length == 0 ) { parameterMetadata = new ParameterMetadata( null, null ); returnMetadata = null; } else { this.parameterMetadata = buildParameterMetadata( translators[0].getParameterTranslations(), hql ); if ( translators[0].isManipulationStatement() ) { returnMetadata = null; } else { final Type[] types = ( length > 1 ) ? new Type[translators[0].getReturnTypes().length] : translators[0].getReturnTypes(); returnMetadata = new ReturnMetadata( translators[0].getReturnAliases(), types ); } } }
public LoadQueryInfluencers(SessionFactoryImplementor sessionFactory) { this( sessionFactory, new HashMap<String,Filter>(), new HashSet<String>() ); }
private LoadQueryInfluencers(SessionFactoryImplementor sessionFactory, Map<String,Filter> enabledFilters, Set<String> enabledFetchProfileNames) { this.sessionFactory = sessionFactory; this.enabledFilters = enabledFilters; this.enabledFetchProfileNames = enabledFetchProfileNames; }
public Filter getEnabledFilter(String filterName) { return enabledFilters.get( filterName ); }