Example usage for org.hibernate Session getSessionFactory

List of usage examples for org.hibernate Session getSessionFactory

Introduction

In this page you can find the example usage for org.hibernate Session getSessionFactory.

Prototype

SessionFactory getSessionFactory();

Source Link

Document

Get the session factory which created this session.

Usage

From source file:ee.ria.xroad.opmonitordaemon.OperationalDataRecordManager.java

License:Open Source License

private static int getConfiguredBatchSize(Session session) {
    if (configuredBatchSize == 0) {
        Properties props = ((SessionFactoryImpl) session.getSessionFactory()).getProperties();

        configuredBatchSize = ConfigurationHelper.getInt(Environment.STATEMENT_BATCH_SIZE, props,
                DEFAULT_BATCH_SIZE);// w w w . j  av  a 2s .co m

        log.debug("Configured JDBC batch size is {}", configuredBatchSize);
    }

    return configuredBatchSize;
}

From source file:fr.univrouen.poste.web.admin.IndexController.java

License:Apache License

private String getHbm2ddlAuto() {
    Session session = entityManager.unwrap(Session.class);
    SessionFactoryImpl sessionImpl = (SessionFactoryImpl) session.getSessionFactory();
    Settings setting = sessionImpl.getSettings();
    String hbm2ddlAuto = setting.isAutoCreateSchema() ? "create" : "update";
    return hbm2ddlAuto;
}

From source file:functionaltests.db.schedulerdb.TestJobRemove.java

License:Open Source License

private void checkAllEntitiesDeleted(String... skipClasses) {
    Set<String> skip = ImmutableSet.copyOf(skipClasses);

    Session session = dbManager.getSessionFactory().openSession();
    try {//from  w ww  .j a  v  a  2  s  .c om
        for (ClassMetadata metadata : session.getSessionFactory().getAllClassMetadata().values()) {
            if (!skip.contains(metadata.getEntityName())) {
                System.out.println("Check " + metadata.getEntityName());
                List<Object> list = session.createCriteria(metadata.getEntityName()).list();
                Assert.assertEquals("Unexpected " + metadata.getEntityName(), 0, list.size());
            }
        }
    } finally {
        session.close();
    }
}

From source file:gov.medicaid.services.impl.SequenceGeneratorBean.java

License:Apache License

/**
 * Creates a new sequence if necessary./*from ww  w  .j a v  a2s.c om*/
 *
 * @param sequenceName the sequence to get the next set of values for
 * @return the generator
 */
private MultipleHiLoPerTableGenerator configure(String sequenceName) {
    Properties params = new Properties();
    params.put(MultipleHiLoPerTableGenerator.ID_TABLE, "CMS_SEQUENCE");
    params.put(MultipleHiLoPerTableGenerator.PK_COLUMN_NAME, "SEQ_NAME");
    params.put(MultipleHiLoPerTableGenerator.PK_VALUE_NAME, sequenceName);
    params.put(MultipleHiLoPerTableGenerator.VALUE_COLUMN_NAME, "NEXT_HI");
    params.put(MultipleHiLoPerTableGenerator.MAX_LO, MAXIMUM_LO);
    params.put(MultipleHiLoPerTableGenerator.IDENTIFIER_NORMALIZER, new ObjectNameNormalizer() {
        /**
         * Returns false.
         */
        protected boolean isUseQuotedIdentifiersGlobally() {
            return false;
        }

        /**
         * Returns the default naming strategy.
         */
        protected NamingStrategy getNamingStrategy() {
            return EJB3NamingStrategy.INSTANCE;
        }
    });

    Session sess = (Session) em.getDelegate();
    SessionFactoryImplementor impl = (SessionFactoryImplementor) sess.getSessionFactory();
    MultipleHiLoPerTableGenerator generator = new MultipleHiLoPerTableGenerator();
    generator.configure(LongType.INSTANCE, params, impl.getDialect());
    generators.put(sequenceName, generator);
    return generator;
}

From source file:gov.nih.nci.caarray.util.CaArrayHibernateHelperImpl.java

License:BSD License

private void disableFilters(Session session) {
    Set<String> filters = session.getSessionFactory().getDefinedFilterNames();
    for (String filterName : filters) {
        // we only want to disable the security filters. assume security filters are ones
        // with GROUP_NAMES and APPLICATION_ID parameters
        FilterDefinition fd = session.getSessionFactory().getFilterDefinition(filterName);
        if (fd.getParameterNames().contains("GROUP_NAMES")
                && fd.getParameterNames().contains("APPLICATION_ID")) {
            session.disableFilter(filterName);
        }//w  w  w  . j a  v a  2  s .  c o  m
    }
}

From source file:gov.nih.nci.caintegrator.security.SecurityManagerImplTest.java

License:BSD License

@Test
public void testInitializeFiltersForUserGroups() throws CSException {
    Session session = mock(Session.class);
    SessionFactory sessionFactory = mock(SessionFactory.class);
    when(session.getSessionFactory()).thenReturn(sessionFactory);
    securityManager.initializeFiltersForUserGroups(USERNAME, session);
    verify(sessionFactory, times(1)).getDefinedFilterNames();
}

From source file:gov.nih.nci.caintegrator.security.SecurityManagerImplTest.java

License:BSD License

@Test
public void testInitializeFiltersForUserGroupsUserDoesNotExist() throws CSException {
    Session session = mock(Session.class);
    SessionFactory sessionFactory = mock(SessionFactory.class);
    when(session.getSessionFactory()).thenReturn(sessionFactory);
    securityManager.initializeFiltersForUserGroups(USER_DOES_NOT_EXIST, session);
    verify(sessionFactory, never()).getDefinedFilterNames();
}

From source file:gov.nih.nci.security.authorization.instancelevel.InstanceLevelSecurityHelper.java

License:BSD License

/**
 * This method initializes the filter that are already added to the Sessionfactory.
 * <br>//from ww w  . j av a2  s  .c o  m
 * This method also initializes the defined filters configured in HBM/Classes/Packages based on the definedFilterNamesMap. 
 * If definedFilterNamesMap contains 'ALL' as the Filter Name (key) then all defined filters are enabled.
 * <br>
 * This method first obtains the list of all the defined filters from the SessionFactory in the passes Session object. 
 * It then just iterates through the filter list and sets the group names and the application name parameter. 
 * 
 * @param groupNames The names of the groups which are invoking the query
 * @param session The Hibernate Session initialized to execute this query
 * @param authorizationManager The CSM AuthorizationManager instance for this application
 * @param definedFilterNamesMap - Map of defined Filter Names and string value ( enable / disable ) to indicate that the filter should be enabled of disabled.<br>.
 *                            
 */
public static void initializeFiltersForGroups(String[] groupNames, Session session,
        AuthorizationManager authorizationManager, Map<String, String> definedFilterNamesMap) {

    List<String> sessionGroupFilterNamesList = new ArrayList<String>();
    List<String> sessionDefinedFilterNamesList = new ArrayList<String>();
    boolean enableAllDefinedFilterNames = false;

    Set definedFilterNames = null;
    if (definedFilterNamesMap != null && !definedFilterNamesMap.isEmpty()) {
        definedFilterNames = definedFilterNamesMap.keySet();
        if (definedFilterNames.contains("ALL"))
            enableAllDefinedFilterNames = true;
    }

    SessionFactory sessionFactory = session.getSessionFactory();
    Set sessionFilterNamesSet = sessionFactory.getDefinedFilterNames();

    Iterator sessionFilterNamesSetIterator = sessionFilterNamesSet.iterator();
    while (sessionFilterNamesSetIterator.hasNext()) {
        String filterName = (String) sessionFilterNamesSetIterator.next();

        if (null != definedFilterNames) {
            if (enableAllDefinedFilterNames) {
                sessionDefinedFilterNamesList.add(filterName);
            } else {
                if (definedFilterNames.contains(filterName)) {
                    String value = (String) definedFilterNamesMap.get(filterName);
                    if (Constants.ENABLE.equalsIgnoreCase(value)) {
                        sessionDefinedFilterNamesList.add(filterName);
                    }
                }
            }
        }
        FilterDefinition filterDefinition = sessionFactory.getFilterDefinition(filterName);
        if (filterDefinition != null) {

            Set<String> parameterNamesSet = filterDefinition.getParameterNames();
            if (parameterNamesSet != null && parameterNamesSet.contains("GROUP_NAMES")) {
                sessionGroupFilterNamesList.add(filterName);
                // remove this filter name from sessionDefinedFilterNamesList if it exists in there.
                if (sessionDefinedFilterNamesList.contains(filterName))
                    sessionDefinedFilterNamesList.remove(filterName);
            }
        }
    }

    //Enable the User Filters from CSM database for the application
    Iterator sessionGroupFilterNamesListIterator = sessionGroupFilterNamesList.iterator();
    while (sessionGroupFilterNamesListIterator.hasNext()) {
        String filterName = (String) sessionGroupFilterNamesListIterator.next();
        Filter filter = session.enableFilter(filterName);
        filter.setParameterList("GROUP_NAMES", groupNames);
        filter.setParameter("APPLICATION_ID", authorizationManager.getApplicationContext().getApplicationId());
    }
    //Enable the Defined Filters available in HBM/Classes.
    Iterator sessionDefinedFilterNamesListIterator = sessionDefinedFilterNamesList.iterator();
    while (sessionDefinedFilterNamesListIterator.hasNext()) {
        String filterName = (String) sessionDefinedFilterNamesListIterator.next();
        Filter filter = session.enableFilter(filterName);
    }
}

From source file:gov.nih.nci.security.authorization.instancelevel.InstanceLevelSecurityHelper.java

License:BSD License

/**
 * This method initializes the User filter from CSM Database that are already added to the Sessionfactory.
 * <br>//  www  .  jav a  2  s .  c om
 * This method also initializes the defined filters configured in HBM/Classes/Packages based on the definedFilterNamesMap.
 * If definedFilterNamesMap contains 'ALL' as the Filter Name (key) then all defined filters are enabled. 
 * <br>
 * This method first obtains the list of all the defined filters from the SessionFactory in the passes Session object. 
 * It then just iterates through the filter list and sets the user name and the application name parameter. 
 * 
 * @param userName The name of the logged in user or group which is invoking the query
 * @param session The Hibernate Session initialized to execute this query
 * @param authorizationManager The CSM AuthorizationManager instance for this application
 * @param definedFilterNamesMap - Map of defined Filter Names and string value ( enable / disable ) to indicate that the filter should be enabled of disabled.
 * 
 */
public static void initializeFilters(String userName, Session session,
        AuthorizationManager authorizationManager, Map<String, String> definedFilterNamesMap) {
    List<String> initUserFilterNames = new ArrayList<String>();
    List<String> initSessionDefinedFilterNames = new ArrayList<String>();

    boolean enableAllSessionDefinedFilters = false;

    Set definedFilterNames = null;
    if (definedFilterNamesMap != null && !definedFilterNamesMap.isEmpty()) {
        definedFilterNames = definedFilterNamesMap.keySet();
        if (definedFilterNames.contains("ALL"))
            enableAllSessionDefinedFilters = true;
    }

    Iterator sessionFilterNamesSetIterator = session.getSessionFactory().getDefinedFilterNames().iterator();
    while (sessionFilterNamesSetIterator.hasNext()) {
        String filterName = (String) sessionFilterNamesSetIterator.next();
        if (enableAllSessionDefinedFilters) {
            initSessionDefinedFilterNames.add(filterName);
        } else if (definedFilterNames != null && definedFilterNames.contains(filterName)) {
            String value = (String) definedFilterNamesMap.get(filterName);
            if (Constants.ENABLE.equalsIgnoreCase(value)) {
                initSessionDefinedFilterNames.add(filterName);
            }
        }

        FilterDefinition filterDefinition = session.getSessionFactory().getFilterDefinition(filterName);
        if (filterDefinition != null) {
            Set<String> parameterNamesSet = filterDefinition.getParameterNames();
            if (parameterNamesSet != null && parameterNamesSet.contains("USER_NAME")) {
                initUserFilterNames.add(filterName);
                // remove this filter name from sessionDefinedFilterNamesList if it exists in there.
                initSessionDefinedFilterNames.remove(filterName);
            }
        }
    }

    //Enable the User Filters from CSM database for the application
    Iterator sessionUserFilterNamesListIterator = initUserFilterNames.iterator();
    while (sessionUserFilterNamesListIterator.hasNext()) {
        String filterName = (String) sessionUserFilterNamesListIterator.next();
        Filter filter = session.enableFilter(filterName);
        filter.setParameter("USER_NAME", userName);
        filter.setParameter("APPLICATION_ID", authorizationManager.getApplicationContext().getApplicationId());
    }
    //Enable the Defined Filters available in HBM/Classes.
    Iterator sessionDefinedFilterNamesListIterator = initSessionDefinedFilterNames.iterator();
    while (sessionDefinedFilterNamesListIterator.hasNext()) {
        String filterName = (String) sessionDefinedFilterNamesListIterator.next();
        Filter filter = session.enableFilter(filterName);
    }
}

From source file:gov.nih.nci.security.upt.util.HibernateHelper.java

License:BSD License

private static String modifySQLForUser(FilterClause filterClause, String generatedSQL, Session session,
        String peiTableOrViewName) {
    String targetClassName = null;
    if (StringUtils.isBlank(filterClause.getTargetClassAlias()))
        targetClassName = filterClause.getTargetClassName().substring(0,
                filterClause.getTargetClassName().indexOf(" - "));
    else/*from   ww w  .  j ava  2  s . com*/
        targetClassName = filterClause.getTargetClassAlias();
    String targetClassAttributeName = null;
    if (StringUtils.isBlank(filterClause.getTargetClassAttributeAlias()))
        targetClassAttributeName = filterClause.getTargetClassAttributeName();
    else
        targetClassAttributeName = filterClause.getTargetClassAttributeAlias();

    String CSM_QUERY = " select pe.attribute_value from " + "csm_protection_group pg, "
            + "csm_protection_element pe, " + "csm_pg_pe pgpe, " + "csm_user_group_role_pg ugrpg, "
            + "csm_user u, " + "csm_role_privilege rp, " + "csm_role r, " + "csm_privilege p "
            + "where ugrpg.role_id = r.role_id " + "and ugrpg.user_id = u.user_id and "
            + "ugrpg.protection_group_id = ANY " + "(select pg1.protection_group_id "
            + "from csm_protection_group pg1 " + "where pg1.protection_group_id = pg.protection_group_id "
            + "or pg1.protection_group_id = " + "(select pg2.parent_protection_group_id "
            + "from csm_protection_group pg2 " + "where pg2.protection_group_id = pg.protection_group_id)) "
            + "and pg.protection_group_id = pgpe.protection_group_id "
            + "and pgpe.protection_element_id = pe.protection_element_id " + "and r.role_id = rp.role_id "
            + "and rp.privilege_id = p.privilege_id " + "and pe.object_id= '" + targetClassName + "' "
            + "and pe.attribute='" + targetClassAttributeName + "' " + "and p.privilege_name='READ' "
            + "and u.login_name=:USER_NAME " + "and pe.application_id=:APPLICATION_ID";

    String CSM_QUERY_2 = "select upei.attribute_value from " + peiTableOrViewName + " upei where "
            + "upei.login_name=:USER_NAME and upei.application_id =:APPLICATION_ID and upei.privilege_name='READ'";

    StringBuffer result = new StringBuffer();
    String query = generatedSQL.substring(generatedSQL.indexOf('-') + 1, generatedSQL.length());
    query = query.trim();
    query = query.substring(0, query.indexOf('?'));
    String delimiters = "+-*/(),. ";
    StringTokenizer st = new StringTokenizer(query, delimiters, true);
    while (st.hasMoreTokens()) {
        String w = st.nextToken();
        if (w.equals("this_")) {
            result = result.append("table_name_csm_");
        } else if (w.equals("y0_")) {
            result = result.append("");
        } else if (w.equals("as")) {
            result = result.append("");
        } else {
            result = result.append(w);
        }
    }
    SessionFactory sessionFactory = session.getSessionFactory();
    ClassMetadata classMetadata = sessionFactory.getClassMetadata(filterClause.getClassName());
    String columnName = null;
    if (classMetadata instanceof AbstractEntityPersister) {
        AbstractEntityPersister abstractEntityPersister = (AbstractEntityPersister) classMetadata;
        String Id = abstractEntityPersister.getIdentifierPropertyName();
        String[] columns = abstractEntityPersister.getPropertyColumnNames(Id);
        columnName = columns[0];
    }
    if (!StringUtils.isBlank(peiTableOrViewName)) {
        query = columnName + " in (" + result.toString() + CSM_QUERY_2 + "))";
    } else {
        query = columnName + " in (" + result.toString() + CSM_QUERY + "))";
    }

    return query.toString();
}