org.hibernate.SessionFactory

Here are the examples of the java api org.hibernate.SessionFactory taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

817 Examples 7

19 Source : HibernateUtil.java
with Apache License 2.0
from yugabyte

public clreplaced HibernateUtil {

    private static StandardServiceRegistry registry;

    private static SessionFactory sessionFactory;

    public static SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
            try {
                // Create registry
                registry = new StandardServiceRegistryBuilder().configure().build();
                // Create MetadataSources
                MetadataSources sources = new MetadataSources(registry);
                // Create Metadata
                Metadata metadata = sources.getMetadataBuilder().build();
                // Create SessionFactory
                sessionFactory = metadata.getSessionFactoryBuilder().build();
            } catch (Exception e) {
                e.printStackTrace();
                if (registry != null) {
                    StandardServiceRegistryBuilder.destroy(registry);
                }
            }
        }
        return sessionFactory;
    }
}

19 Source : HeartJobDetail.java
with Apache License 2.0
from youseries

/**
 * @author Jacky.gao
 * @since 2016年12月29日
 */
public clreplaced HeartJobDetail extends JobDetailImpl {

    private static final long serialVersionUID = 1653542848201958245L;

    private SessionFactory sessionFactory;

    private String currentInstanceName;

    public HeartJobDetail(SessionFactory sessionFactory, String currentInstanceName) {
        this.sessionFactory = sessionFactory;
        this.currentInstanceName = currentInstanceName;
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public String getCurrentInstanceName() {
        return currentInstanceName;
    }

    public void setCurrentInstanceName(String currentInstanceName) {
        this.currentInstanceName = currentInstanceName;
    }
}

19 Source : HeartJobDetail.java
with Apache License 2.0
from youseries

public void setSessionFactory(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}

19 Source : HeartbeatDetectionJob.java
with Apache License 2.0
from youseries

private HeartJobDetail buildHeartJobDetail(String currentInstanceName) {
    SessionFactory sessionFactory = EnvironmentUtils.getEnvironment().getSessionFactory();
    HeartJobDetail jobDetail = new HeartJobDetail(sessionFactory, currentInstanceName);
    jobDetail.setKey(new JobKey("UfloHeartJob", "uflo_background_system_job"));
    jobDetail.setJobClreplaced(HeartJob.clreplaced);
    return jobDetail;
}

19 Source : hibernateUtil.java
with MIT License
from yocaning

public clreplaced hibernateUtil {

    public static Session session;

    public static SessionFactory sf;

    static {
        Configuration cfg = new Configuration().configure();
        sf = cfg.buildSessionFactory();
    }

    public static Session getSession() {
        session = sf.openSession();
        return session;
    }
}

19 Source : HibernateSessionFactoryManager.java
with Apache License 2.0
from yahoo

/**
 * Factory manager for Hibernate sessions.
 */
public clreplaced HibernateSessionFactoryManager {

    private static SessionFactory sessionFactory;

    /**
     * Get a new session factory.
     */
    public static SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
            Configuration cfg = new Configuration();
            // add clreplaced
            cfg.addPackage("com.yahoo.cubed.model");
            cfg.addAnnotatedClreplaced(Field.clreplaced);
            cfg.addAnnotatedClreplaced(Pipeline.clreplaced);
            cfg.addAnnotatedClreplaced(PipelineProjection.clreplaced);
            cfg.addAnnotatedClreplaced(PipelineProjectionVM.clreplaced);
            cfg.addAnnotatedClreplaced(FieldKey.clreplaced);
            cfg.addAnnotatedClreplaced(Schema.clreplaced);
            cfg.addAnnotatedClreplaced(FunnelGroup.clreplaced);
            // add connection
            cfg.setProperty("hibernate.connection.driver_clreplaced", ConfigurationLoader.getProperty(ConfigurationLoader.DRIVER));
            cfg.setProperty("hibernate.connection.url", ConfigurationLoader.getProperty(ConfigurationLoader.DATABASEURL));
            cfg.setProperty("hibernate.connection.username", ConfigurationLoader.getProperty(ConfigurationLoader.USERNAME));
            cfg.setProperty("hibernate.connection.preplacedword", ConfigurationLoader.getProperty(ConfigurationLoader.PreplacedWORD));
            cfg.setProperty("hibernate.dialect", ConfigurationLoader.getProperty(ConfigurationLoader.DIALECT));
            cfg.setProperty("hibernate.connection.autoReconnect", "true");
            ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
            sessionFactory = cfg.buildSessionFactory(serviceRegistry);
        }
        return sessionFactory;
    }
}

19 Source : DAOImpl.java
with GNU General Public License v3.0
from xenv

/**
 * @see DAO
 */
@Repository
public clreplaced DAOImpl implements DAO {

    private SessionFactory sessionFactory;

    @Resource(name = "sf")
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

19 Source : DAOImpl.java
with GNU General Public License v3.0
from xenv

@Resource(name = "sf")
public void setSessionFactory(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}

19 Source : BaseDaoHibernate4.java
with Apache License 2.0
from weijieqiu

/**
 * Created by Administrator on 2018/7/1.
 */
public clreplaced BaseDaoHibernate4<T> implements BaseDao<T> {

    // DAO组件进行持久化操作底层依赖的SessionFactory组件
    private SessionFactory sessionFactory;

    // 依赖注入SessionFactory所需的setter方法
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public SessionFactory getSessionFactory() {
        return this.sessionFactory;
    }

    // 根据ID加载实体
    @SuppressWarnings("unchecked")
    public T get(Clreplaced<T> enreplacedyClazz, Serializable id) {
        return (T) getSessionFactory().getCurrentSession().get(enreplacedyClazz, id);
    }

    // 保存实体
    public Serializable save(T enreplacedy) {
        return getSessionFactory().getCurrentSession().save(enreplacedy);
    }

    // 更新实体
    public void update(T enreplacedy) {
        getSessionFactory().getCurrentSession().saveOrUpdate(enreplacedy);
    }

    // 删除实体
    public void delete(T enreplacedy) {
        getSessionFactory().getCurrentSession().delete(enreplacedy);
    }

    // 根据ID删除实体
    public void delete(Clreplaced<T> enreplacedyClazz, Serializable id) {
        getSessionFactory().getCurrentSession().createQuery("delete " + enreplacedyClazz.getSimpleName() + " en where en.id = ?0").setParameter("0", id).executeUpdate();
    }

    // 获取所有实体
    public List<T> findAll(Clreplaced<T> enreplacedyClazz) {
        return find("select en from " + enreplacedyClazz.getSimpleName() + " en");
    }

    // 获取实体总数
    public long findCount(Clreplaced<T> enreplacedyClazz) {
        List<?> l = find("select count(*) from " + enreplacedyClazz.getSimpleName());
        // 返回查询得到的实体总数
        if (l != null && l.size() == 1) {
            return (Long) l.get(0);
        }
        return 0;
    }

    // 根据HQL语句查询实体
    @SuppressWarnings("unchecked")
    protected List<T> find(String hql) {
        return (List<T>) getSessionFactory().getCurrentSession().createQuery(hql).list();
    }

    // 根据带占位符参数HQL语句查询实体
    @SuppressWarnings("unchecked")
    protected List<T> find(String hql, Object... params) {
        // 创建查询
        Query query = getSessionFactory().getCurrentSession().createQuery(hql);
        // 为包含占位符的HQL语句设置参数
        for (int i = 0, len = params.length; i < len; i++) {
            query.setParameter(i + "", params[i]);
        }
        return (List<T>) query.list();
    }

    // 根据带占位符参数HQL语句查询实体
    @SuppressWarnings("unchecked")
    protected Object findUnique(String hql, Object... params) {
        // 创建查询
        Query query = getSessionFactory().getCurrentSession().createQuery(hql);
        // 为包含占位符的HQL语句设置参数
        for (int i = 0, len = params.length; i < len; i++) {
            query.setParameter(i + "", params[i]);
        }
        return query.uniqueResult();
    }

    /**
     * 使用hql 语句进行分页查询操作
     *
     * @param hql      需要查询的hql语句
     * @param pageNo   查询第pageNo页的记录
     * @param pageSize 每页需要显示的记录数
     * @return 当前页的所有记录
     */
    @SuppressWarnings("unchecked")
    protected List<T> findByPage(String hql, int pageNo, int pageSize) {
        // 创建查询
        return getSessionFactory().getCurrentSession().createQuery(hql).setFirstResult((pageNo - 1) * pageSize).setMaxResults(pageSize).list();
    }

    /**
     * 使用hql 语句进行分页查询操作
     *
     * @param hql      需要查询的hql语句
     * @param params   如果hql带占位符参数,params用于传入占位符参数
     * @param pageNo   查询第pageNo页的记录
     * @param pageSize 每页需要显示的记录数
     * @return 当前页的所有记录
     */
    @SuppressWarnings("unchecked")
    protected List<T> findByPage(String hql, int pageNo, int pageSize, Object... params) {
        // 创建查询
        Query query = getSessionFactory().getCurrentSession().createQuery(hql);
        // 为包含占位符的HQL语句设置参数
        for (int i = 0, len = params.length; i < len; i++) {
            query.setParameter(i + "", params[i]);
        }
        // 执行分页,并返回查询结果
        return query.setFirstResult((pageNo - 1) * pageSize).setMaxResults(pageSize).list();
    }
}

19 Source : BaseDaoHibernate4.java
with Apache License 2.0
from weijieqiu

// 依赖注入SessionFactory所需的setter方法
public void setSessionFactory(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}

19 Source : HibernateTransactionManagerConfiguration.java
with Apache License 2.0
from vladmihalcea

@Bean
@Primary
public SessionFactory sessionFactory(SessionFactory originalSessionFactory) {
    return HypersistenceHibernatePersistenceProvider.decorate(originalSessionFactory);
}

19 Source : HibernateTransactionManagerConfiguration.java
with Apache License 2.0
from vladmihalcea

@Bean
public TransactionTemplate transactionTemplate(SessionFactory sessionFactory) {
    return new TransactionTemplate(transactionManager(sessionFactory));
}

19 Source : ForumServiceImpl.java
with Apache License 2.0
from vladmihalcea

/**
 * @author Vlad Mihalcea
 */
@Service
public clreplaced ForumServiceImpl implements ForumService {

    @Autowired
    private PostDAO postDAO;

    @Autowired
    private TagDAO tagDAO;

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    @Transactional
    public Post newPost(String replacedle, String... tags) {
        Post post = new Post();
        post.setreplacedle(replacedle);
        post.getTags().addAll(tagDAO.findByName(tags));
        return postDAO.persist(post);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Post> findAllByreplacedle(String replacedle) {
        return postDAO.findByreplacedle(replacedle);
    }

    @Override
    @Transactional
    public Post findById(Long id) {
        return postDAO.findById(id);
    }

    @Override
    public List<Post> findAll(int maxResults) {
        return postDAO.findAll(maxResults);
    }
}

19 Source : HibernateTransactionManagerConfiguration.java
with Apache License 2.0
from vladmihalcea

@Bean
public SessionFactory sessionFactory(SessionFactory originalSessionFactory) {
    return HypersistenceHibernatePersistenceProvider.decorate(originalSessionFactory);
}

19 Source : HibernateTransactionManagerConfiguration.java
with Apache License 2.0
from vladmihalcea

@Bean
public HypersistenceOptimizer hypersistenceOptimizer(SessionFactory sessionFactory) {
    return new HypersistenceOptimizer(new HibernateConfig(sessionFactory));
}

19 Source : HibernatePersonRepository.java
with MIT License
from Vip-Augus

/**
 * Hibernate implementation of the {@link PersonRepository} API.
 *
 * @author Sam Brannen
 * @since 3.0
 */
@Repository
public clreplaced HibernatePersonRepository implements PersonRepository {

    private final SessionFactory sessionFactory;

    @Autowired
    public HibernatePersonRepository(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Override
    public Person save(Person person) {
        this.sessionFactory.getCurrentSession().save(person);
        return person;
    }

    @Override
    public Person findByName(String name) {
        return (Person) this.sessionFactory.getCurrentSession().createQuery("from Person person where person.name = :name").setParameter("name", name).getSingleResult();
    }
}

19 Source : HibernateNativeEntityManagerFactoryIntegrationTests.java
with MIT License
from Vip-Augus

/**
 * Hibernate-specific JPA tests with native SessionFactory setup and getCurrentSession interaction.
 *
 * @author Juergen Hoeller
 * @since 5.1
 */
public clreplaced HibernateNativeEnreplacedyManagerFactoryIntegrationTests extends AbstractContainerEnreplacedyManagerFactoryIntegrationTests {

    @Autowired
    private SessionFactory sessionFactory;

    @Autowired
    private ApplicationContext applicationContext;

    @Override
    protected String[] getConfigLocations() {
        return new String[] { "/org/springframework/orm/jpa/hibernate/hibernate-manager-native.xml", "/org/springframework/orm/jpa/memdb.xml", "/org/springframework/orm/jpa/inject.xml" };
    }

    @Test
    public void testEnreplacedyManagerFactoryImplementsEnreplacedyManagerFactoryInfo() {
        replacedertFalse("Must not have introduced config interface", enreplacedyManagerFactory instanceof EnreplacedyManagerFactoryInfo);
    }

    @Test
    @SuppressWarnings("unchecked")
    public void testEnreplacedyListener() {
        String firstName = "Tony";
        insertPerson(firstName);
        List<Person> people = sharedEnreplacedyManager.createQuery("select p from Person as p").getResultList();
        replacedertEquals(1, people.size());
        replacedertEquals(firstName, people.get(0).getFirstName());
        replacedertSame(applicationContext, people.get(0).postLoaded);
    }

    @Test
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public void testCurrentSession() {
        String firstName = "Tony";
        insertPerson(firstName);
        Query q = sessionFactory.getCurrentSession().createQuery("select p from Person as p");
        List<Person> people = q.getResultList();
        replacedertEquals(1, people.size());
        replacedertEquals(firstName, people.get(0).getFirstName());
        replacedertSame(applicationContext, people.get(0).postLoaded);
    }

    // SPR-16956
    @Test
    public void testReadOnly() {
        replacedertSame(FlushMode.AUTO, sessionFactory.getCurrentSession().getHibernateFlushMode());
        replacedertFalse(sessionFactory.getCurrentSession().isDefaultReadOnly());
        endTransaction();
        this.transactionDefinition.setReadOnly(true);
        startNewTransaction();
        replacedertSame(FlushMode.MANUAL, sessionFactory.getCurrentSession().getHibernateFlushMode());
        replacedertTrue(sessionFactory.getCurrentSession().isDefaultReadOnly());
    }
}

19 Source : OpenSessionInViewInterceptor.java
with MIT License
from Vip-Augus

/**
 * Spring web request interceptor that binds a Hibernate {@code Session} to the
 * thread for the entire processing of the request.
 *
 * <p>This clreplaced is a concrete expression of the "Open Session in View" pattern, which
 * is a pattern that allows for the lazy loading of replacedociations in web views despite
 * the original transactions already being completed.
 *
 * <p>This interceptor makes Hibernate Sessions available via the current thread,
 * which will be autodetected by transaction managers. It is suitable for service layer
 * transactions via {@link org.springframework.orm.hibernate5.HibernateTransactionManager}
 * as well as for non-transactional execution (if configured appropriately).
 *
 * <p>In contrast to {@link OpenSessionInViewFilter}, this interceptor is configured
 * in a Spring application context and can thus take advantage of bean wiring.
 *
 * <p><b>WARNING:</b> Applying this interceptor to existing logic can cause issues
 * that have not appeared before, through the use of a single Hibernate
 * {@code Session} for the processing of an entire request. In particular, the
 * rereplacedociation of persistent objects with a Hibernate {@code Session} has to
 * occur at the very beginning of request processing, to avoid clashes with already
 * loaded instances of the same objects.
 *
 * @author Juergen Hoeller
 * @since 4.2
 * @see OpenSessionInViewFilter
 * @see OpenSessionInterceptor
 * @see org.springframework.orm.hibernate5.HibernateTransactionManager
 * @see TransactionSynchronizationManager
 * @see SessionFactory#getCurrentSession()
 */
public clreplaced OpenSessionInViewInterceptor implements AsyncWebRequestInterceptor {

    /**
     * Suffix that gets appended to the {@code SessionFactory}
     * {@code toString()} representation for the "participate in existing
     * session handling" request attribute.
     * @see #getParticipateAttributeName
     */
    public static final String PARTICIPATE_SUFFIX = ".PARTICIPATE";

    protected final Log logger = LogFactory.getLog(getClreplaced());

    @Nullable
    private SessionFactory sessionFactory;

    /**
     * Set the Hibernate SessionFactory that should be used to create Hibernate Sessions.
     */
    public void setSessionFactory(@Nullable SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    /**
     * Return the Hibernate SessionFactory that should be used to create Hibernate Sessions.
     */
    @Nullable
    public SessionFactory getSessionFactory() {
        return this.sessionFactory;
    }

    private SessionFactory obtainSessionFactory() {
        SessionFactory sf = getSessionFactory();
        replacedert.state(sf != null, "No SessionFactory set");
        return sf;
    }

    /**
     * Open a new Hibernate {@code Session} according and bind it to the thread via the
     * {@link TransactionSynchronizationManager}.
     */
    @Override
    public void preHandle(WebRequest request) throws DataAccessException {
        String key = getParticipateAttributeName();
        WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
        if (asyncManager.hasConcurrentResult() && applySessionBindingInterceptor(asyncManager, key)) {
            return;
        }
        if (TransactionSynchronizationManager.hasResource(obtainSessionFactory())) {
            // Do not modify the Session: just mark the request accordingly.
            Integer count = (Integer) request.getAttribute(key, WebRequest.SCOPE_REQUEST);
            int newCount = (count != null ? count + 1 : 1);
            request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST);
        } else {
            logger.debug("Opening Hibernate Session in OpenSessionInViewInterceptor");
            Session session = openSession();
            SessionHolder sessionHolder = new SessionHolder(session);
            TransactionSynchronizationManager.bindResource(obtainSessionFactory(), sessionHolder);
            AsyncRequestInterceptor asyncRequestInterceptor = new AsyncRequestInterceptor(obtainSessionFactory(), sessionHolder);
            asyncManager.registerCallableInterceptor(key, asyncRequestInterceptor);
            asyncManager.registerDeferredResultInterceptor(key, asyncRequestInterceptor);
        }
    }

    @Override
    public void postHandle(WebRequest request, @Nullable ModelMap model) {
    }

    /**
     * Unbind the Hibernate {@code Session} from the thread and close it).
     * @see TransactionSynchronizationManager
     */
    @Override
    public void afterCompletion(WebRequest request, @Nullable Exception ex) throws DataAccessException {
        if (!decrementParticipateCount(request)) {
            SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(obtainSessionFactory());
            logger.debug("Closing Hibernate Session in OpenSessionInViewInterceptor");
            SessionFactoryUtils.closeSession(sessionHolder.getSession());
        }
    }

    private boolean decrementParticipateCount(WebRequest request) {
        String participateAttributeName = getParticipateAttributeName();
        Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
        if (count == null) {
            return false;
        }
        // Do not modify the Session: just clear the marker.
        if (count > 1) {
            request.setAttribute(participateAttributeName, count - 1, WebRequest.SCOPE_REQUEST);
        } else {
            request.removeAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
        }
        return true;
    }

    @Override
    public void afterConcurrentHandlingStarted(WebRequest request) {
        if (!decrementParticipateCount(request)) {
            TransactionSynchronizationManager.unbindResource(obtainSessionFactory());
        }
    }

    /**
     * Open a Session for the SessionFactory that this interceptor uses.
     * <p>The default implementation delegates to the {@link SessionFactory#openSession}
     * method and sets the {@link Session}'s flush mode to "MANUAL".
     * @return the Session to use
     * @throws DataAccessResourceFailureException if the Session could not be created
     * @see FlushMode#MANUAL
     */
    @SuppressWarnings("deprecation")
    protected Session openSession() throws DataAccessResourceFailureException {
        try {
            Session session = obtainSessionFactory().openSession();
            session.setFlushMode(FlushMode.MANUAL);
            return session;
        } catch (HibernateException ex) {
            throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
        }
    }

    /**
     * Return the name of the request attribute that identifies that a request is
     * already intercepted.
     * <p>The default implementation takes the {@code toString()} representation
     * of the {@code SessionFactory} instance and appends {@link #PARTICIPATE_SUFFIX}.
     */
    protected String getParticipateAttributeName() {
        return obtainSessionFactory().toString() + PARTICIPATE_SUFFIX;
    }

    private boolean applySessionBindingInterceptor(WebAsyncManager asyncManager, String key) {
        CallableProcessingInterceptor cpi = asyncManager.getCallableInterceptor(key);
        if (cpi == null) {
            return false;
        }
        ((AsyncRequestInterceptor) cpi).bindSession();
        return true;
    }
}

19 Source : OpenSessionInViewInterceptor.java
with MIT License
from Vip-Augus

private SessionFactory obtainSessionFactory() {
    SessionFactory sf = getSessionFactory();
    replacedert.state(sf != null, "No SessionFactory set");
    return sf;
}

19 Source : OpenSessionInViewInterceptor.java
with MIT License
from Vip-Augus

/**
 * Set the Hibernate SessionFactory that should be used to create Hibernate Sessions.
 */
public void setSessionFactory(@Nullable SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}

19 Source : OpenSessionInterceptor.java
with MIT License
from Vip-Augus

/**
 * Simple AOP Alliance {@link MethodInterceptor} implementation that binds a new
 * Hibernate {@link Session} for each method invocation, if none bound before.
 *
 * <p>This is a simple Hibernate Session scoping interceptor along the lines of
 * {@link OpenSessionInViewInterceptor}, just for use with AOP setup instead of
 * MVC setup. It opens a new {@link Session} with flush mode "MANUAL" since the
 * Session is only meant for reading, except when participating in a transaction.
 *
 * @author Juergen Hoeller
 * @since 4.2
 * @see OpenSessionInViewInterceptor
 * @see OpenSessionInViewFilter
 * @see org.springframework.orm.hibernate5.HibernateTransactionManager
 * @see TransactionSynchronizationManager
 * @see SessionFactory#getCurrentSession()
 */
public clreplaced OpenSessionInterceptor implements MethodInterceptor, InitializingBean {

    @Nullable
    private SessionFactory sessionFactory;

    /**
     * Set the Hibernate SessionFactory that should be used to create Hibernate Sessions.
     */
    public void setSessionFactory(@Nullable SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    /**
     * Return the Hibernate SessionFactory that should be used to create Hibernate Sessions.
     */
    @Nullable
    public SessionFactory getSessionFactory() {
        return this.sessionFactory;
    }

    @Override
    public void afterPropertiesSet() {
        if (getSessionFactory() == null) {
            throw new IllegalArgumentException("Property 'sessionFactory' is required");
        }
    }

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        SessionFactory sf = getSessionFactory();
        replacedert.state(sf != null, "No SessionFactory set");
        if (!TransactionSynchronizationManager.hasResource(sf)) {
            // New Session to be bound for the current method's scope...
            Session session = openSession(sf);
            try {
                TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
                return invocation.proceed();
            } finally {
                SessionFactoryUtils.closeSession(session);
                TransactionSynchronizationManager.unbindResource(sf);
            }
        } else {
            // Pre-bound Session found -> simply proceed.
            return invocation.proceed();
        }
    }

    /**
     * Open a Session for the given SessionFactory.
     * <p>The default implementation delegates to the {@link SessionFactory#openSession}
     * method and sets the {@link Session}'s flush mode to "MANUAL".
     * @param sessionFactory the SessionFactory to use
     * @return the Session to use
     * @throws DataAccessResourceFailureException if the Session could not be created
     * @since 5.0
     * @see FlushMode#MANUAL
     */
    @SuppressWarnings("deprecation")
    protected Session openSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
        Session session = openSession();
        if (session == null) {
            try {
                session = sessionFactory.openSession();
                session.setFlushMode(FlushMode.MANUAL);
            } catch (HibernateException ex) {
                throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
            }
        }
        return session;
    }

    /**
     * Open a Session for the given SessionFactory.
     * @deprecated as of 5.0, in favor of {@link #openSession(SessionFactory)}
     */
    @Deprecated
    @Nullable
    protected Session openSession() throws DataAccessResourceFailureException {
        return null;
    }
}

19 Source : HibernateDaoSupport.java
with MIT License
from Vip-Augus

/**
 * Set the Hibernate SessionFactory to be used by this DAO.
 * Will automatically create a HibernateTemplate for the given SessionFactory.
 * @see #createHibernateTemplate
 * @see #setHibernateTemplate
 */
public final void setSessionFactory(SessionFactory sessionFactory) {
    if (this.hibernateTemplate == null || sessionFactory != this.hibernateTemplate.getSessionFactory()) {
        this.hibernateTemplate = createHibernateTemplate(sessionFactory);
    }
}

19 Source : HibernateDaoSupport.java
with MIT License
from Vip-Augus

/**
 * Create a HibernateTemplate for the given SessionFactory.
 * Only invoked if populating the DAO with a SessionFactory reference!
 * <p>Can be overridden in subclreplacedes to provide a HibernateTemplate instance
 * with different configuration, or a custom HibernateTemplate subclreplaced.
 * @param sessionFactory the Hibernate SessionFactory to create a HibernateTemplate for
 * @return the new HibernateTemplate instance
 * @see #setSessionFactory
 */
protected HibernateTemplate createHibernateTemplate(SessionFactory sessionFactory) {
    return new HibernateTemplate(sessionFactory);
}

19 Source : SpringSessionSynchronization.java
with MIT License
from Vip-Augus

/**
 * Callback for resource cleanup at the end of a Spring-managed transaction
 * for a pre-bound Hibernate Session.
 *
 * @author Juergen Hoeller
 * @since 4.2
 */
public clreplaced SpringSessionSynchronization implements TransactionSynchronization, Ordered {

    private final SessionHolder sessionHolder;

    private final SessionFactory sessionFactory;

    private final boolean newSession;

    private boolean holderActive = true;

    public SpringSessionSynchronization(SessionHolder sessionHolder, SessionFactory sessionFactory) {
        this(sessionHolder, sessionFactory, false);
    }

    public SpringSessionSynchronization(SessionHolder sessionHolder, SessionFactory sessionFactory, boolean newSession) {
        this.sessionHolder = sessionHolder;
        this.sessionFactory = sessionFactory;
        this.newSession = newSession;
    }

    private Session getCurrentSession() {
        return this.sessionHolder.getSession();
    }

    @Override
    public int getOrder() {
        return SessionFactoryUtils.SESSION_SYNCHRONIZATION_ORDER;
    }

    @Override
    public void suspend() {
        if (this.holderActive) {
            TransactionSynchronizationManager.unbindResource(this.sessionFactory);
            // Eagerly disconnect the Session here, to make release mode "on_close" work on JBoss.
            getCurrentSession().disconnect();
        }
    }

    @Override
    public void resume() {
        if (this.holderActive) {
            TransactionSynchronizationManager.bindResource(this.sessionFactory, this.sessionHolder);
        }
    }

    @Override
    public void flush() {
        SessionFactoryUtils.flush(getCurrentSession(), false);
    }

    @Override
    public void beforeCommit(boolean readOnly) throws DataAccessException {
        if (!readOnly) {
            Session session = getCurrentSession();
            // Read-write transaction -> flush the Hibernate Session.
            // Further check: only flush when not FlushMode.MANUAL.
            if (!FlushMode.MANUAL.equals(SessionFactoryUtils.getFlushMode(session))) {
                SessionFactoryUtils.flush(getCurrentSession(), true);
            }
        }
    }

    @Override
    @SuppressWarnings("deprecation")
    public void beforeCompletion() {
        try {
            Session session = this.sessionHolder.getSession();
            if (this.sessionHolder.getPreviousFlushMode() != null) {
                // In case of pre-bound Session, restore previous flush mode.
                session.setFlushMode(this.sessionHolder.getPreviousFlushMode());
            }
            // Eagerly disconnect the Session here, to make release mode "on_close" work nicely.
            session.disconnect();
        } finally {
            // Unbind at this point if it's a new Session...
            if (this.newSession) {
                TransactionSynchronizationManager.unbindResource(this.sessionFactory);
                this.holderActive = false;
            }
        }
    }

    @Override
    public void afterCommit() {
    }

    @Override
    public void afterCompletion(int status) {
        try {
            if (status != STATUS_COMMITTED) {
                // Clear all pending inserts/updates/deletes in the Session.
                // Necessary for pre-bound Sessions, to avoid inconsistent state.
                this.sessionHolder.getSession().clear();
            }
        } finally {
            this.sessionHolder.setSynchronizedWithTransaction(false);
            // Call close() at this point if it's a new Session...
            if (this.newSession) {
                SessionFactoryUtils.closeSession(this.sessionHolder.getSession());
            }
        }
    }
}

19 Source : HibernateTransactionManager.java
with MIT License
from Vip-Augus

/**
 * Set the SessionFactory that this instance should manage transactions for.
 */
public void setSessionFactory(@Nullable SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}

19 Source : HibernateTransactionManager.java
with MIT License
from Vip-Augus

/**
 * Obtain the SessionFactory for actual use.
 * @return the SessionFactory (never {@code null})
 * @throws IllegalStateException in case of no SessionFactory set
 * @since 5.0
 */
protected final SessionFactory obtainSessionFactory() {
    SessionFactory sessionFactory = getSessionFactory();
    replacedert.state(sessionFactory != null, "No SessionFactory set");
    return sessionFactory;
}

19 Source : HibernateTemplate.java
with MIT License
from Vip-Augus

/**
 * Helper clreplaced that simplifies Hibernate data access code. Automatically
 * converts HibernateExceptions into DataAccessExceptions, following the
 * {@code org.springframework.dao} exception hierarchy.
 *
 * <p>The central method is {@code execute}, supporting Hibernate access code
 * implementing the {@link HibernateCallback} interface. It provides Hibernate Session
 * handling such that neither the HibernateCallback implementation nor the calling
 * code needs to explicitly care about retrieving/closing Hibernate Sessions,
 * or handling Session lifecycle exceptions. For typical single step actions,
 * there are various convenience methods (find, load, saveOrUpdate, delete).
 *
 * <p>Can be used within a service implementation via direct instantiation
 * with a SessionFactory reference, or get prepared in an application context
 * and given to services as bean reference. Note: The SessionFactory should
 * always be configured as bean in the application context, in the first case
 * given to the service directly, in the second case to the prepared template.
 *
 * <p><b>NOTE: Hibernate access code can also be coded against the native Hibernate
 * {@link Session}. Hence, for newly started projects, consider adopting the standard
 * Hibernate style of coding against {@link SessionFactory#getCurrentSession()}.
 * Alternatively, use {@link #execute(HibernateCallback)} with Java 8 lambda code blocks
 * against the callback-provided {@code Session} which results in elegant code as well,
 * decoupled from the Hibernate Session lifecycle. The remaining operations on this
 * HibernateTemplate are deprecated in the meantime and primarily exist as a migration
 * helper for older Hibernate 3.x/4.x data access code in existing applications.</b>
 *
 * @author Juergen Hoeller
 * @since 4.2
 * @see #setSessionFactory
 * @see HibernateCallback
 * @see Session
 * @see LocalSessionFactoryBean
 * @see HibernateTransactionManager
 * @see org.springframework.orm.hibernate5.support.OpenSessionInViewFilter
 * @see org.springframework.orm.hibernate5.support.OpenSessionInViewInterceptor
 */
public clreplaced HibernateTemplate implements HibernateOperations, InitializingBean {

    private static final Method createQueryMethod;

    private static final Method getNamedQueryMethod;

    static {
        // Hibernate 5.2's createQuery method declares a new subtype as return type,
        // so we need to use reflection for binary compatibility with 5.0/5.1 here.
        try {
            createQueryMethod = Session.clreplaced.getMethod("createQuery", String.clreplaced);
            getNamedQueryMethod = Session.clreplaced.getMethod("getNamedQuery", String.clreplaced);
        } catch (NoSuchMethodException ex) {
            throw new IllegalStateException("Incompatible Hibernate Session API", ex);
        }
    }

    protected final Log logger = LogFactory.getLog(getClreplaced());

    @Nullable
    private SessionFactory sessionFactory;

    @Nullable
    private String[] filterNames;

    private boolean exposeNativeSession = false;

    private boolean checkWriteOperations = true;

    private boolean cacheQueries = false;

    @Nullable
    private String queryCacheRegion;

    private int fetchSize = 0;

    private int maxResults = 0;

    /**
     * Create a new HibernateTemplate instance.
     */
    public HibernateTemplate() {
    }

    /**
     * Create a new HibernateTemplate instance.
     * @param sessionFactory the SessionFactory to create Sessions with
     */
    public HibernateTemplate(SessionFactory sessionFactory) {
        setSessionFactory(sessionFactory);
        afterPropertiesSet();
    }

    /**
     * Set the Hibernate SessionFactory that should be used to create
     * Hibernate Sessions.
     */
    public void setSessionFactory(@Nullable SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    /**
     * Return the Hibernate SessionFactory that should be used to create
     * Hibernate Sessions.
     */
    @Nullable
    public SessionFactory getSessionFactory() {
        return this.sessionFactory;
    }

    /**
     * Obtain the SessionFactory for actual use.
     * @return the SessionFactory (never {@code null})
     * @throws IllegalStateException in case of no SessionFactory set
     * @since 5.0
     */
    protected final SessionFactory obtainSessionFactory() {
        SessionFactory sessionFactory = getSessionFactory();
        replacedert.state(sessionFactory != null, "No SessionFactory set");
        return sessionFactory;
    }

    /**
     * Set one or more names of Hibernate filters to be activated for all
     * Sessions that this accessor works with.
     * <p>Each of those filters will be enabled at the beginning of each
     * operation and correspondingly disabled at the end of the operation.
     * This will work for newly opened Sessions as well as for existing
     * Sessions (for example, within a transaction).
     * @see #enableFilters(Session)
     * @see Session#enableFilter(String)
     */
    public void setFilterNames(@Nullable String... filterNames) {
        this.filterNames = filterNames;
    }

    /**
     * Return the names of Hibernate filters to be activated, if any.
     */
    @Nullable
    public String[] getFilterNames() {
        return this.filterNames;
    }

    /**
     * Set whether to expose the native Hibernate Session to
     * HibernateCallback code.
     * <p>Default is "false": a Session proxy will be returned, suppressing
     * {@code close} calls and automatically applying query cache
     * settings and transaction timeouts.
     * @see HibernateCallback
     * @see Session
     * @see #setCacheQueries
     * @see #setQueryCacheRegion
     * @see #prepareQuery
     * @see #prepareCriteria
     */
    public void setExposeNativeSession(boolean exposeNativeSession) {
        this.exposeNativeSession = exposeNativeSession;
    }

    /**
     * Return whether to expose the native Hibernate Session to
     * HibernateCallback code, or rather a Session proxy.
     */
    public boolean isExposeNativeSession() {
        return this.exposeNativeSession;
    }

    /**
     * Set whether to check that the Hibernate Session is not in read-only mode
     * in case of write operations (save/update/delete).
     * <p>Default is "true", for fail-fast behavior when attempting write operations
     * within a read-only transaction. Turn this off to allow save/update/delete
     * on a Session with flush mode MANUAL.
     * @see #checkWriteOperationAllowed
     * @see org.springframework.transaction.TransactionDefinition#isReadOnly
     */
    public void setCheckWriteOperations(boolean checkWriteOperations) {
        this.checkWriteOperations = checkWriteOperations;
    }

    /**
     * Return whether to check that the Hibernate Session is not in read-only
     * mode in case of write operations (save/update/delete).
     */
    public boolean isCheckWriteOperations() {
        return this.checkWriteOperations;
    }

    /**
     * Set whether to cache all queries executed by this template.
     * <p>If this is "true", all Query and Criteria objects created by
     * this template will be marked as cacheable (including all
     * queries through find methods).
     * <p>To specify the query region to be used for queries cached
     * by this template, set the "queryCacheRegion" property.
     * @see #setQueryCacheRegion
     * @see org.hibernate.Query#setCacheable
     * @see Criteria#setCacheable
     */
    public void setCacheQueries(boolean cacheQueries) {
        this.cacheQueries = cacheQueries;
    }

    /**
     * Return whether to cache all queries executed by this template.
     */
    public boolean isCacheQueries() {
        return this.cacheQueries;
    }

    /**
     * Set the name of the cache region for queries executed by this template.
     * <p>If this is specified, it will be applied to all Query and Criteria objects
     * created by this template (including all queries through find methods).
     * <p>The cache region will not take effect unless queries created by this
     * template are configured to be cached via the "cacheQueries" property.
     * @see #setCacheQueries
     * @see org.hibernate.Query#setCacheRegion
     * @see Criteria#setCacheRegion
     */
    public void setQueryCacheRegion(@Nullable String queryCacheRegion) {
        this.queryCacheRegion = queryCacheRegion;
    }

    /**
     * Return the name of the cache region for queries executed by this template.
     */
    @Nullable
    public String getQueryCacheRegion() {
        return this.queryCacheRegion;
    }

    /**
     * Set the fetch size for this HibernateTemplate. This is important for processing
     * large result sets: Setting this higher than the default value will increase
     * processing speed at the cost of memory consumption; setting this lower can
     * avoid transferring row data that will never be read by the application.
     * <p>Default is 0, indicating to use the JDBC driver's default.
     */
    public void setFetchSize(int fetchSize) {
        this.fetchSize = fetchSize;
    }

    /**
     * Return the fetch size specified for this HibernateTemplate.
     */
    public int getFetchSize() {
        return this.fetchSize;
    }

    /**
     * Set the maximum number of rows for this HibernateTemplate. This is important
     * for processing subsets of large result sets, avoiding to read and hold
     * the entire result set in the database or in the JDBC driver if we're
     * never interested in the entire result in the first place (for example,
     * when performing searches that might return a large number of matches).
     * <p>Default is 0, indicating to use the JDBC driver's default.
     */
    public void setMaxResults(int maxResults) {
        this.maxResults = maxResults;
    }

    /**
     * Return the maximum number of rows specified for this HibernateTemplate.
     */
    public int getMaxResults() {
        return this.maxResults;
    }

    @Override
    public void afterPropertiesSet() {
        if (getSessionFactory() == null) {
            throw new IllegalArgumentException("Property 'sessionFactory' is required");
        }
    }

    @Override
    @Nullable
    public <T> T execute(HibernateCallback<T> action) throws DataAccessException {
        return doExecute(action, false);
    }

    /**
     * Execute the action specified by the given action object within a
     * native {@link Session}.
     * <p>This execute variant overrides the template-wide
     * {@link #isExposeNativeSession() "exposeNativeSession"} setting.
     * @param action callback object that specifies the Hibernate action
     * @return a result object returned by the action, or {@code null}
     * @throws DataAccessException in case of Hibernate errors
     */
    @Nullable
    public <T> T executeWithNativeSession(HibernateCallback<T> action) {
        return doExecute(action, true);
    }

    /**
     * Execute the action specified by the given action object within a Session.
     * @param action callback object that specifies the Hibernate action
     * @param enforceNativeSession whether to enforce exposure of the native
     * Hibernate Session to callback code
     * @return a result object returned by the action, or {@code null}
     * @throws DataAccessException in case of Hibernate errors
     */
    @SuppressWarnings("deprecation")
    @Nullable
    protected <T> T doExecute(HibernateCallback<T> action, boolean enforceNativeSession) throws DataAccessException {
        replacedert.notNull(action, "Callback object must not be null");
        Session session = null;
        boolean isNew = false;
        try {
            session = obtainSessionFactory().getCurrentSession();
        } catch (HibernateException ex) {
            logger.debug("Could not retrieve pre-bound Hibernate session", ex);
        }
        if (session == null) {
            session = obtainSessionFactory().openSession();
            session.setFlushMode(FlushMode.MANUAL);
            isNew = true;
        }
        try {
            enableFilters(session);
            Session sessionToExpose = (enforceNativeSession || isExposeNativeSession() ? session : createSessionProxy(session));
            return action.doInHibernate(sessionToExpose);
        } catch (HibernateException ex) {
            throw SessionFactoryUtils.convertHibernateAccessException(ex);
        } catch (PersistenceException ex) {
            if (ex.getCause() instanceof HibernateException) {
                throw SessionFactoryUtils.convertHibernateAccessException((HibernateException) ex.getCause());
            }
            throw ex;
        } catch (RuntimeException ex) {
            // Callback code threw application exception...
            throw ex;
        } finally {
            if (isNew) {
                SessionFactoryUtils.closeSession(session);
            } else {
                disableFilters(session);
            }
        }
    }

    /**
     * Create a close-suppressing proxy for the given Hibernate Session.
     * The proxy also prepares returned Query and Criteria objects.
     * @param session the Hibernate Session to create a proxy for
     * @return the Session proxy
     * @see Session#close()
     * @see #prepareQuery
     * @see #prepareCriteria
     */
    protected Session createSessionProxy(Session session) {
        return (Session) Proxy.newProxyInstance(session.getClreplaced().getClreplacedLoader(), new Clreplaced<?>[] { Session.clreplaced }, new CloseSuppressingInvocationHandler(session));
    }

    /**
     * Enable the specified filters on the given Session.
     * @param session the current Hibernate Session
     * @see #setFilterNames
     * @see Session#enableFilter(String)
     */
    protected void enableFilters(Session session) {
        String[] filterNames = getFilterNames();
        if (filterNames != null) {
            for (String filterName : filterNames) {
                session.enableFilter(filterName);
            }
        }
    }

    /**
     * Disable the specified filters on the given Session.
     * @param session the current Hibernate Session
     * @see #setFilterNames
     * @see Session#disableFilter(String)
     */
    protected void disableFilters(Session session) {
        String[] filterNames = getFilterNames();
        if (filterNames != null) {
            for (String filterName : filterNames) {
                session.disableFilter(filterName);
            }
        }
    }

    // -------------------------------------------------------------------------
    // Convenience methods for loading individual objects
    // -------------------------------------------------------------------------
    @Override
    @Nullable
    public <T> T get(Clreplaced<T> enreplacedyClreplaced, Serializable id) throws DataAccessException {
        return get(enreplacedyClreplaced, id, null);
    }

    @Override
    @Nullable
    public <T> T get(final Clreplaced<T> enreplacedyClreplaced, final Serializable id, @Nullable final LockMode lockMode) throws DataAccessException {
        return executeWithNativeSession(session -> {
            if (lockMode != null) {
                return session.get(enreplacedyClreplaced, id, new LockOptions(lockMode));
            } else {
                return session.get(enreplacedyClreplaced, id);
            }
        });
    }

    @Override
    @Nullable
    public Object get(String enreplacedyName, Serializable id) throws DataAccessException {
        return get(enreplacedyName, id, null);
    }

    @Override
    @Nullable
    public Object get(final String enreplacedyName, final Serializable id, @Nullable final LockMode lockMode) throws DataAccessException {
        return executeWithNativeSession(session -> {
            if (lockMode != null) {
                return session.get(enreplacedyName, id, new LockOptions(lockMode));
            } else {
                return session.get(enreplacedyName, id);
            }
        });
    }

    @Override
    public <T> T load(Clreplaced<T> enreplacedyClreplaced, Serializable id) throws DataAccessException {
        return load(enreplacedyClreplaced, id, null);
    }

    @Override
    public <T> T load(final Clreplaced<T> enreplacedyClreplaced, final Serializable id, @Nullable final LockMode lockMode) throws DataAccessException {
        return nonNull(executeWithNativeSession(session -> {
            if (lockMode != null) {
                return session.load(enreplacedyClreplaced, id, new LockOptions(lockMode));
            } else {
                return session.load(enreplacedyClreplaced, id);
            }
        }));
    }

    @Override
    public Object load(String enreplacedyName, Serializable id) throws DataAccessException {
        return load(enreplacedyName, id, null);
    }

    @Override
    public Object load(final String enreplacedyName, final Serializable id, @Nullable final LockMode lockMode) throws DataAccessException {
        return nonNull(executeWithNativeSession(session -> {
            if (lockMode != null) {
                return session.load(enreplacedyName, id, new LockOptions(lockMode));
            } else {
                return session.load(enreplacedyName, id);
            }
        }));
    }

    @Override
    @SuppressWarnings({ "unchecked", "deprecation" })
    public <T> List<T> loadAll(final Clreplaced<T> enreplacedyClreplaced) throws DataAccessException {
        return nonNull(executeWithNativeSession((HibernateCallback<List<T>>) session -> {
            Criteria criteria = session.createCriteria(enreplacedyClreplaced);
            criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENreplacedY);
            prepareCriteria(criteria);
            return criteria.list();
        }));
    }

    @Override
    @SuppressWarnings({ "deprecation" })
    public void load(final Object enreplacedy, final Serializable id) throws DataAccessException {
        executeWithNativeSession(session -> {
            session.load(enreplacedy, id);
            return null;
        });
    }

    @Override
    public void refresh(final Object enreplacedy) throws DataAccessException {
        refresh(enreplacedy, null);
    }

    @Override
    public void refresh(final Object enreplacedy, @Nullable final LockMode lockMode) throws DataAccessException {
        executeWithNativeSession(session -> {
            if (lockMode != null) {
                session.refresh(enreplacedy, new LockOptions(lockMode));
            } else {
                session.refresh(enreplacedy);
            }
            return null;
        });
    }

    @Override
    public boolean contains(final Object enreplacedy) throws DataAccessException {
        Boolean result = executeWithNativeSession(session -> session.contains(enreplacedy));
        replacedert.state(result != null, "No contains result");
        return result;
    }

    @Override
    public void evict(final Object enreplacedy) throws DataAccessException {
        executeWithNativeSession(session -> {
            session.evict(enreplacedy);
            return null;
        });
    }

    @Override
    public void initialize(Object proxy) throws DataAccessException {
        try {
            Hibernate.initialize(proxy);
        } catch (HibernateException ex) {
            throw SessionFactoryUtils.convertHibernateAccessException(ex);
        }
    }

    @Override
    public Filter enableFilter(String filterName) throws IllegalStateException {
        Session session = obtainSessionFactory().getCurrentSession();
        Filter filter = session.getEnabledFilter(filterName);
        if (filter == null) {
            filter = session.enableFilter(filterName);
        }
        return filter;
    }

    // -------------------------------------------------------------------------
    // Convenience methods for storing individual objects
    // -------------------------------------------------------------------------
    @Override
    public void lock(final Object enreplacedy, final LockMode lockMode) throws DataAccessException {
        executeWithNativeSession(session -> {
            session.buildLockRequest(new LockOptions(lockMode)).lock(enreplacedy);
            return null;
        });
    }

    @Override
    public void lock(final String enreplacedyName, final Object enreplacedy, final LockMode lockMode) throws DataAccessException {
        executeWithNativeSession(session -> {
            session.buildLockRequest(new LockOptions(lockMode)).lock(enreplacedyName, enreplacedy);
            return null;
        });
    }

    @Override
    public Serializable save(final Object enreplacedy) throws DataAccessException {
        return nonNull(executeWithNativeSession(session -> {
            checkWriteOperationAllowed(session);
            return session.save(enreplacedy);
        }));
    }

    @Override
    public Serializable save(final String enreplacedyName, final Object enreplacedy) throws DataAccessException {
        return nonNull(executeWithNativeSession(session -> {
            checkWriteOperationAllowed(session);
            return session.save(enreplacedyName, enreplacedy);
        }));
    }

    @Override
    public void update(Object enreplacedy) throws DataAccessException {
        update(enreplacedy, null);
    }

    @Override
    public void update(final Object enreplacedy, @Nullable final LockMode lockMode) throws DataAccessException {
        executeWithNativeSession(session -> {
            checkWriteOperationAllowed(session);
            session.update(enreplacedy);
            if (lockMode != null) {
                session.buildLockRequest(new LockOptions(lockMode)).lock(enreplacedy);
            }
            return null;
        });
    }

    @Override
    public void update(String enreplacedyName, Object enreplacedy) throws DataAccessException {
        update(enreplacedyName, enreplacedy, null);
    }

    @Override
    public void update(final String enreplacedyName, final Object enreplacedy, @Nullable final LockMode lockMode) throws DataAccessException {
        executeWithNativeSession(session -> {
            checkWriteOperationAllowed(session);
            session.update(enreplacedyName, enreplacedy);
            if (lockMode != null) {
                session.buildLockRequest(new LockOptions(lockMode)).lock(enreplacedyName, enreplacedy);
            }
            return null;
        });
    }

    @Override
    public void saveOrUpdate(final Object enreplacedy) throws DataAccessException {
        executeWithNativeSession(session -> {
            checkWriteOperationAllowed(session);
            session.saveOrUpdate(enreplacedy);
            return null;
        });
    }

    @Override
    public void saveOrUpdate(final String enreplacedyName, final Object enreplacedy) throws DataAccessException {
        executeWithNativeSession(session -> {
            checkWriteOperationAllowed(session);
            session.saveOrUpdate(enreplacedyName, enreplacedy);
            return null;
        });
    }

    @Override
    public void replicate(final Object enreplacedy, final ReplicationMode replicationMode) throws DataAccessException {
        executeWithNativeSession(session -> {
            checkWriteOperationAllowed(session);
            session.replicate(enreplacedy, replicationMode);
            return null;
        });
    }

    @Override
    public void replicate(final String enreplacedyName, final Object enreplacedy, final ReplicationMode replicationMode) throws DataAccessException {
        executeWithNativeSession(session -> {
            checkWriteOperationAllowed(session);
            session.replicate(enreplacedyName, enreplacedy, replicationMode);
            return null;
        });
    }

    @Override
    public void persist(final Object enreplacedy) throws DataAccessException {
        executeWithNativeSession(session -> {
            checkWriteOperationAllowed(session);
            session.persist(enreplacedy);
            return null;
        });
    }

    @Override
    public void persist(final String enreplacedyName, final Object enreplacedy) throws DataAccessException {
        executeWithNativeSession(session -> {
            checkWriteOperationAllowed(session);
            session.persist(enreplacedyName, enreplacedy);
            return null;
        });
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> T merge(final T enreplacedy) throws DataAccessException {
        return nonNull(executeWithNativeSession(session -> {
            checkWriteOperationAllowed(session);
            return (T) session.merge(enreplacedy);
        }));
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> T merge(final String enreplacedyName, final T enreplacedy) throws DataAccessException {
        return nonNull(executeWithNativeSession(session -> {
            checkWriteOperationAllowed(session);
            return (T) session.merge(enreplacedyName, enreplacedy);
        }));
    }

    @Override
    public void delete(Object enreplacedy) throws DataAccessException {
        delete(enreplacedy, null);
    }

    @Override
    public void delete(final Object enreplacedy, @Nullable final LockMode lockMode) throws DataAccessException {
        executeWithNativeSession(session -> {
            checkWriteOperationAllowed(session);
            if (lockMode != null) {
                session.buildLockRequest(new LockOptions(lockMode)).lock(enreplacedy);
            }
            session.delete(enreplacedy);
            return null;
        });
    }

    @Override
    public void delete(String enreplacedyName, Object enreplacedy) throws DataAccessException {
        delete(enreplacedyName, enreplacedy, null);
    }

    @Override
    public void delete(final String enreplacedyName, final Object enreplacedy, @Nullable final LockMode lockMode) throws DataAccessException {
        executeWithNativeSession(session -> {
            checkWriteOperationAllowed(session);
            if (lockMode != null) {
                session.buildLockRequest(new LockOptions(lockMode)).lock(enreplacedyName, enreplacedy);
            }
            session.delete(enreplacedyName, enreplacedy);
            return null;
        });
    }

    @Override
    public void deleteAll(final Collection<?> enreplacedies) throws DataAccessException {
        executeWithNativeSession(session -> {
            checkWriteOperationAllowed(session);
            for (Object enreplacedy : enreplacedies) {
                session.delete(enreplacedy);
            }
            return null;
        });
    }

    @Override
    public void flush() throws DataAccessException {
        executeWithNativeSession(session -> {
            session.flush();
            return null;
        });
    }

    @Override
    public void clear() throws DataAccessException {
        executeWithNativeSession(session -> {
            session.clear();
            return null;
        });
    }

    // -------------------------------------------------------------------------
    // Convenience finder methods for detached criteria
    // -------------------------------------------------------------------------
    @Override
    public List<?> findByCriteria(DetachedCriteria criteria) throws DataAccessException {
        return findByCriteria(criteria, -1, -1);
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<?> findByCriteria(final DetachedCriteria criteria, final int firstResult, final int maxResults) throws DataAccessException {
        replacedert.notNull(criteria, "DetachedCriteria must not be null");
        return nonNull(executeWithNativeSession((HibernateCallback<List<?>>) session -> {
            Criteria executableCriteria = criteria.getExecutableCriteria(session);
            prepareCriteria(executableCriteria);
            if (firstResult >= 0) {
                executableCriteria.setFirstResult(firstResult);
            }
            if (maxResults > 0) {
                executableCriteria.setMaxResults(maxResults);
            }
            return executableCriteria.list();
        }));
    }

    @Override
    public <T> List<T> findByExample(T exampleEnreplacedy) throws DataAccessException {
        return findByExample(null, exampleEnreplacedy, -1, -1);
    }

    @Override
    public <T> List<T> findByExample(String enreplacedyName, T exampleEnreplacedy) throws DataAccessException {
        return findByExample(enreplacedyName, exampleEnreplacedy, -1, -1);
    }

    @Override
    public <T> List<T> findByExample(T exampleEnreplacedy, int firstResult, int maxResults) throws DataAccessException {
        return findByExample(null, exampleEnreplacedy, firstResult, maxResults);
    }

    @Override
    @SuppressWarnings({ "unchecked", "deprecation" })
    public <T> List<T> findByExample(@Nullable final String enreplacedyName, final T exampleEnreplacedy, final int firstResult, final int maxResults) throws DataAccessException {
        replacedert.notNull(exampleEnreplacedy, "Example enreplacedy must not be null");
        return nonNull(executeWithNativeSession((HibernateCallback<List<T>>) session -> {
            Criteria executableCriteria = (enreplacedyName != null ? session.createCriteria(enreplacedyName) : session.createCriteria(exampleEnreplacedy.getClreplaced()));
            executableCriteria.add(Example.create(exampleEnreplacedy));
            prepareCriteria(executableCriteria);
            if (firstResult >= 0) {
                executableCriteria.setFirstResult(firstResult);
            }
            if (maxResults > 0) {
                executableCriteria.setMaxResults(maxResults);
            }
            return executableCriteria.list();
        }));
    }

    // -------------------------------------------------------------------------
    // Convenience finder methods for HQL strings
    // -------------------------------------------------------------------------
    @Deprecated
    @Override
    @SuppressWarnings({ "rawtypes", "unchecked", "deprecation" })
    public List<?> find(final String queryString, @Nullable final Object... values) throws DataAccessException {
        return nonNull(executeWithNativeSession((HibernateCallback<List<?>>) session -> {
            org.hibernate.Query queryObject = queryObject(ReflectionUtils.invokeMethod(createQueryMethod, session, queryString));
            prepareQuery(queryObject);
            if (values != null) {
                for (int i = 0; i < values.length; i++) {
                    queryObject.setParameter(i, values[i]);
                }
            }
            return queryObject.list();
        }));
    }

    @Deprecated
    @Override
    public List<?> findByNamedParam(String queryString, String paramName, Object value) throws DataAccessException {
        return findByNamedParam(queryString, new String[] { paramName }, new Object[] { value });
    }

    @Deprecated
    @Override
    @SuppressWarnings({ "rawtypes", "unchecked", "deprecation" })
    public List<?> findByNamedParam(final String queryString, final String[] paramNames, final Object[] values) throws DataAccessException {
        if (paramNames.length != values.length) {
            throw new IllegalArgumentException("Length of paramNames array must match length of values array");
        }
        return nonNull(executeWithNativeSession((HibernateCallback<List<?>>) session -> {
            org.hibernate.Query queryObject = queryObject(ReflectionUtils.invokeMethod(createQueryMethod, session, queryString));
            prepareQuery(queryObject);
            for (int i = 0; i < values.length; i++) {
                applyNamedParameterToQuery(queryObject, paramNames[i], values[i]);
            }
            return queryObject.list();
        }));
    }

    @Deprecated
    @Override
    @SuppressWarnings({ "rawtypes", "unchecked", "deprecation" })
    public List<?> findByValueBean(final String queryString, final Object valueBean) throws DataAccessException {
        return nonNull(executeWithNativeSession((HibernateCallback<List<?>>) session -> {
            org.hibernate.Query queryObject = queryObject(ReflectionUtils.invokeMethod(createQueryMethod, session, queryString));
            prepareQuery(queryObject);
            queryObject.setProperties(valueBean);
            return queryObject.list();
        }));
    }

    // -------------------------------------------------------------------------
    // Convenience finder methods for named queries
    // -------------------------------------------------------------------------
    @Deprecated
    @Override
    @SuppressWarnings({ "rawtypes", "unchecked", "deprecation" })
    public List<?> findByNamedQuery(final String queryName, @Nullable final Object... values) throws DataAccessException {
        return nonNull(executeWithNativeSession((HibernateCallback<List<?>>) session -> {
            org.hibernate.Query queryObject = queryObject(ReflectionUtils.invokeMethod(getNamedQueryMethod, session, queryName));
            prepareQuery(queryObject);
            if (values != null) {
                for (int i = 0; i < values.length; i++) {
                    queryObject.setParameter(i, values[i]);
                }
            }
            return queryObject.list();
        }));
    }

    @Deprecated
    @Override
    public List<?> findByNamedQueryAndNamedParam(String queryName, String paramName, Object value) throws DataAccessException {
        return findByNamedQueryAndNamedParam(queryName, new String[] { paramName }, new Object[] { value });
    }

    @Deprecated
    @Override
    @SuppressWarnings({ "rawtypes", "unchecked", "deprecation" })
    public List<?> findByNamedQueryAndNamedParam(final String queryName, @Nullable final String[] paramNames, @Nullable final Object[] values) throws DataAccessException {
        if (values != null && (paramNames == null || paramNames.length != values.length)) {
            throw new IllegalArgumentException("Length of paramNames array must match length of values array");
        }
        return nonNull(executeWithNativeSession((HibernateCallback<List<?>>) session -> {
            org.hibernate.Query queryObject = (org.hibernate.Query) nonNull(ReflectionUtils.invokeMethod(getNamedQueryMethod, session, queryName));
            prepareQuery(queryObject);
            if (values != null) {
                for (int i = 0; i < values.length; i++) {
                    applyNamedParameterToQuery(queryObject, paramNames[i], values[i]);
                }
            }
            return queryObject.list();
        }));
    }

    @Deprecated
    @Override
    @SuppressWarnings({ "rawtypes", "unchecked", "deprecation" })
    public List<?> findByNamedQueryAndValueBean(final String queryName, final Object valueBean) throws DataAccessException {
        return nonNull(executeWithNativeSession((HibernateCallback<List<?>>) session -> {
            org.hibernate.Query queryObject = queryObject(ReflectionUtils.invokeMethod(getNamedQueryMethod, session, queryName));
            prepareQuery(queryObject);
            queryObject.setProperties(valueBean);
            return queryObject.list();
        }));
    }

    // -------------------------------------------------------------------------
    // Convenience query methods for iteration and bulk updates/deletes
    // -------------------------------------------------------------------------
    @Deprecated
    @Override
    @SuppressWarnings({ "rawtypes", "deprecation" })
    public Iterator<?> iterate(final String queryString, @Nullable final Object... values) throws DataAccessException {
        return nonNull(executeWithNativeSession((HibernateCallback<Iterator<?>>) session -> {
            org.hibernate.Query queryObject = queryObject(ReflectionUtils.invokeMethod(createQueryMethod, session, queryString));
            prepareQuery(queryObject);
            if (values != null) {
                for (int i = 0; i < values.length; i++) {
                    queryObject.setParameter(i, values[i]);
                }
            }
            return queryObject.iterate();
        }));
    }

    @Deprecated
    @Override
    public void closeIterator(Iterator<?> it) throws DataAccessException {
        try {
            Hibernate.close(it);
        } catch (HibernateException ex) {
            throw SessionFactoryUtils.convertHibernateAccessException(ex);
        }
    }

    @Deprecated
    @Override
    @SuppressWarnings({ "rawtypes", "deprecation" })
    public int bulkUpdate(final String queryString, @Nullable final Object... values) throws DataAccessException {
        Integer result = executeWithNativeSession(session -> {
            org.hibernate.Query queryObject = queryObject(ReflectionUtils.invokeMethod(createQueryMethod, session, queryString));
            prepareQuery(queryObject);
            if (values != null) {
                for (int i = 0; i < values.length; i++) {
                    queryObject.setParameter(i, values[i]);
                }
            }
            return queryObject.executeUpdate();
        });
        replacedert.state(result != null, "No update count");
        return result;
    }

    // -------------------------------------------------------------------------
    // Helper methods used by the operations above
    // -------------------------------------------------------------------------
    /**
     * Check whether write operations are allowed on the given Session.
     * <p>Default implementation throws an InvalidDataAccessApiUsageException in
     * case of {@code FlushMode.MANUAL}. Can be overridden in subclreplacedes.
     * @param session current Hibernate Session
     * @throws InvalidDataAccessApiUsageException if write operations are not allowed
     * @see #setCheckWriteOperations
     * @see Session#getFlushMode()
     * @see FlushMode#MANUAL
     */
    protected void checkWriteOperationAllowed(Session session) throws InvalidDataAccessApiUsageException {
        if (isCheckWriteOperations() && SessionFactoryUtils.getFlushMode(session).lessThan(FlushMode.COMMIT)) {
            throw new InvalidDataAccessApiUsageException("Write operations are not allowed in read-only mode (FlushMode.MANUAL): " + "Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.");
        }
    }

    /**
     * Prepare the given Criteria object, applying cache settings and/or
     * a transaction timeout.
     * @param criteria the Criteria object to prepare
     * @see #setCacheQueries
     * @see #setQueryCacheRegion
     */
    protected void prepareCriteria(Criteria criteria) {
        if (isCacheQueries()) {
            criteria.setCacheable(true);
            if (getQueryCacheRegion() != null) {
                criteria.setCacheRegion(getQueryCacheRegion());
            }
        }
        if (getFetchSize() > 0) {
            criteria.setFetchSize(getFetchSize());
        }
        if (getMaxResults() > 0) {
            criteria.setMaxResults(getMaxResults());
        }
        ResourceHolderSupport sessionHolder = (ResourceHolderSupport) TransactionSynchronizationManager.getResource(obtainSessionFactory());
        if (sessionHolder != null && sessionHolder.hasTimeout()) {
            criteria.setTimeout(sessionHolder.getTimeToLiveInSeconds());
        }
    }

    /**
     * Prepare the given Query object, applying cache settings and/or
     * a transaction timeout.
     * @param queryObject the Query object to prepare
     * @see #setCacheQueries
     * @see #setQueryCacheRegion
     */
    @SuppressWarnings({ "rawtypes", "deprecation" })
    protected void prepareQuery(org.hibernate.Query queryObject) {
        if (isCacheQueries()) {
            queryObject.setCacheable(true);
            if (getQueryCacheRegion() != null) {
                queryObject.setCacheRegion(getQueryCacheRegion());
            }
        }
        if (getFetchSize() > 0) {
            queryObject.setFetchSize(getFetchSize());
        }
        if (getMaxResults() > 0) {
            queryObject.setMaxResults(getMaxResults());
        }
        ResourceHolderSupport sessionHolder = (ResourceHolderSupport) TransactionSynchronizationManager.getResource(obtainSessionFactory());
        if (sessionHolder != null && sessionHolder.hasTimeout()) {
            queryObject.setTimeout(sessionHolder.getTimeToLiveInSeconds());
        }
    }

    /**
     * Apply the given name parameter to the given Query object.
     * @param queryObject the Query object
     * @param paramName the name of the parameter
     * @param value the value of the parameter
     * @throws HibernateException if thrown by the Query object
     */
    @Deprecated
    @SuppressWarnings({ "rawtypes", "deprecation" })
    protected void applyNamedParameterToQuery(org.hibernate.Query queryObject, String paramName, Object value) throws HibernateException {
        if (value instanceof Collection) {
            queryObject.setParameterList(paramName, (Collection<?>) value);
        } else if (value instanceof Object[]) {
            queryObject.setParameterList(paramName, (Object[]) value);
        } else {
            queryObject.setParameter(paramName, value);
        }
    }

    @Deprecated
    @SuppressWarnings({ "rawtypes", "deprecation" })
    private static org.hibernate.Query queryObject(@Nullable Object result) {
        replacedert.state(result != null, "No Hibernate Query");
        return (org.hibernate.Query) result;
    }

    private static <T> T nonNull(@Nullable T result) {
        replacedert.state(result != null, "No result");
        return result;
    }

    /**
     * Invocation handler that suppresses close calls on Hibernate Sessions.
     * Also prepares returned Query and Criteria objects.
     * @see Session#close
     */
    private clreplaced CloseSuppressingInvocationHandler implements InvocationHandler {

        private final Session target;

        public CloseSuppressingInvocationHandler(Session target) {
            this.target = target;
        }

        @Override
        @SuppressWarnings({ "rawtypes", "deprecation" })
        @Nullable
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            // Invocation on Session interface coming in...
            if (method.getName().equals("equals")) {
                // Only consider equal when proxies are identical.
                return (proxy == args[0]);
            } else if (method.getName().equals("hashCode")) {
                // Use hashCode of Session proxy.
                return System.idenreplacedyHashCode(proxy);
            } else if (method.getName().equals("close")) {
                // Handle close method: suppress, not valid.
                return null;
            }
            // Invoke method on target Session.
            try {
                Object retVal = method.invoke(this.target, args);
                // If return value is a Query or Criteria, apply transaction timeout.
                // Applies to createQuery, getNamedQuery, createCriteria.
                if (retVal instanceof Criteria) {
                    prepareCriteria(((Criteria) retVal));
                } else if (retVal instanceof org.hibernate.Query) {
                    prepareQuery(((org.hibernate.Query) retVal));
                }
                return retVal;
            } catch (InvocationTargetException ex) {
                throw ex.getTargetException();
            }
        }
    }
}

19 Source : HibernateTemplate.java
with MIT License
from Vip-Augus

/**
 * Set the Hibernate SessionFactory that should be used to create
 * Hibernate Sessions.
 */
public void setSessionFactory(@Nullable SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}

19 Source : TestDaoService.java
with Apache License 2.0
from tmobile

@org.springframework.stereotype.Component
public clreplaced TestDaoService {

    @Autowired
    private SessionFactory sessionFactory;

    @Autowired
    private AppLookUpDao appFullNameDao;

    @Autowired
    private ComponentDao componentDao;

    @Autowired
    private ComponentTypeDao componentTypeDao;

    @Autowired
    private EnvironmentDao envDao;

    @Autowired
    private HealthCheckDao healthCheckDao;

    @Autowired
    private RegionMessageDao regionMessageDao;

    public static int environmentID = 1, compID, appID, parentCompID, counterID, envCounterID, counterMatrixID, regionID, healthCheckTypeID, healthCheckID = 1, healthCheckParamID, apiStatusID, dailyCompStatusID, appRoleID, k8sContainerStatsID, k8sPodsStatusID, k8sApiStatusID, tpsLatencyID, tpsServiceID, appSessionID, compMessageID;

    public static int getLastCreatedEnvironmentID() {
        return environmentID - 1;
    }

    public static int getEnvironmentsCount() {
        return environmentID;
    }

    public AppFullName createAppFullName() {
        AppFullName afn = getAppFullName();
        appFullNameDao.saveAppFullName(afn);
        appID++;
        return afn;
    }

    public AppFullName getAppFullName() {
        ComponentType ct = ComponentType.APP;
        componentTypeDao.saveComponentType(ct);
        createComponent();
        AppFullName afn = new AppFullName();
        afn.setComponentId(compID);
        afn.setComponentName("component_1");
        afn.setComponentFullName("component_full_name_1");
        return afn;
    }

    public Component createComponent() {
        Component ce = getComponent();
        componentDao.saveComponent(ce);
        compID++;
        return ce;
    }

    public synchronized Component createComponent(Component comp) {
        if (comp.getParentComponentId() != 0) {
            parentCompID++;
        }
        componentDao.saveComponent(comp);
        compID++;
        return comp;
    }

    public Component getComponent() {
        Component ce = new Component();
        ce.setComponentName("component_1");
        ce.setComponentType("APP");
        ce.setAppFullName("app_full_name_1");
        ce.setComponentDate(new Timestamp(new Date().getTime()));
        ce.setPlatform("Marathon");
        return ce;
    }

    public Environment createEnvironment(String envName, int lock) {
        return createEnvironment(envName, lock, EnvironmentType.MARATHON);
    }

    public synchronized Environment createEnvironment(String envName, int lock, EnvironmentType type) {
        Environment env = new Environment();
        env.setEnvironmentName(envName);
        env.setEnvironmentDesc("env_desc_1");
        env.setEnvLock(lock);
        env.setDisplayOrder(0);
        switch(type) {
            case MARATHON:
                env.setMarathonUrl("http://localhost:8080");
                env.setMarathonUserName("marathon_user_1");
                env.setMarathonPreplacedword("marathon_preplaced_1");
                break;
            case K8S:
                env.setK8sUrl("http://localhost");
                env.setK8sUserName("k8s_user_1");
                env.setK8sPreplacedword("k8s_preplaced_1");
                break;
            default:
                break;
        }
        envDao.addEnvironment(env);
        environmentID++;
        return env;
    }

    public ComponentType createComponentType() {
        ComponentType ct = ComponentType.APP;
        componentTypeDao.saveComponentType(ct);
        return ct;
    }

    public ComponentType createComponentType(String value) {
        ComponentType ct = ComponentType.valueOf(value);
        componentTypeDao.saveComponentType(ct);
        return ct;
    }

    public CounterMetricEnreplacedy createCounterMetricEnreplacedy(Session session, EnvCounterEnreplacedy ece) {
        CounterMetricEnreplacedy cme = new CounterMetricEnreplacedy();
        cme.setMetricId(1);
        cme.setEnvCounter(ece);
        cme.setMetricDate(new Date());
        cme.setMetricVal(1.0f);
        session.save(cme);
        counterMatrixID++;
        return cme;
    }

    public EnvCounterEnreplacedy createEnvCounterEnreplacedy(Session session, CounterEnreplacedy ce) {
        EnvCounterEnreplacedy ece = new EnvCounterEnreplacedy();
        ece.setCounterId(1);
        ece.setEnvCounterId(1);
        ece.setMetricTypeId(1);
        ece.setParameter1("param_value_1");
        ece.setParameter2("param_value_2");
        ece.setCounterNum(ce);
        ece.setEnvironment(null);
        session.save(ece);
        envCounterID++;
        return ece;
    }

    public CounterEnreplacedy createCounterEnreplacedy(Session session) {
        CounterEnreplacedy ce = new CounterEnreplacedy();
        ce.setCounterId(1);
        ce.setCounterName("counter_1");
        ce.setCounterDesc("counter_desc_1");
        ce.setDelInd(0);
        ce.setPosition(1);
        session.save(ce);
        counterID++;
        return ce;
    }

    public synchronized RegionEnreplacedy createRegionEnreplacedy(Session session, String regionName) {
        RegionEnreplacedy region = new RegionEnreplacedy();
        region.setRegionDesc("region_desc_1");
        region.setRegionName(regionName);
        region.setRegionLock(0);
        session.save(region);
        regionID++;
        return region;
    }

    public RegionEnreplacedy createRegionEnreplacedy(Session session) {
        return createRegionEnreplacedy(session, "region_1");
    }

    public HealthCheckTypeEnreplacedy createHealthCheckTypeEnreplacedy(Session session) {
        HealthCheckTypeEnreplacedy hcte = new HealthCheckTypeEnreplacedy();
        hcte.setHealthCheckTypeName("healthchecktype_1");
        hcte.setHealthCheckTypeDesc("healthchecktype_desc_1");
        hcte.setHealthCheckTypeClreplaced("healtchecktype.clreplaced");
        session.save(hcte);
        healthCheckTypeID++;
        return hcte;
    }

    public HealthCheckVO createHealthCheck(String envName) {
        return createHealthCheck(envName, ComponentType.APP.name());
    }

    public HealthCheckVO createHealthCheck(String envName, String compType) {
        HealthCheckVO hc = getHealthCheck(envName, compType);
        healthCheckDao.editHealthCheck(hc);
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        HealthCheckParamEnreplacedy hcpe = new HealthCheckParamEnreplacedy();
        hcpe.setHealthCheck(session.get(HealthCheckEnreplacedy.clreplaced, new Integer(healthCheckID)));
        hcpe.setHealthCheckParamKey(hc.getHealthCheckParamList().get(0).getHealthCheckParamKey());
        hcpe.setHealthCheckParamVal(hc.getHealthCheckParamList().get(0).getHealthCheckParamValue());
        session.save(hcpe);
        healthCheckParamID++;
        tx.commit();
        session.close();
        healthCheckID++;
        return hc;
    }

    public HealthCheckVO getHealthCheck(String envName) {
        return getHealthCheck(envName, ComponentType.APP.name());
    }

    public HealthCheckVO getHealthCheck(String envName, String componentType) {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        Environment env = createEnvironment(envName, 0);
        ComponentType compType = createComponentType(componentType);
        createComponent();
        Component component = getComponent();
        component.setParentComponentId(TestDaoService.compID);
        component.setParentComponentName("parent_comp_name_1");
        component.setDelInd(0);
        createComponent(component);
        RegionEnreplacedy region = createRegionEnreplacedy(session);
        HealthCheckTypeEnreplacedy healthCheckType = createHealthCheckTypeEnreplacedy(session);
        tx.commit();
        session.close();
        HealthCheckVO hcv = new HealthCheckVO();
        hcv.setComponentId(TestDaoService.compID);
        hcv.setComponentName(component.getComponentName());
        hcv.setComponentType(compType.componentTypeName());
        hcv.setDelInd(false);
        hcv.setEnvironmentId(TestDaoService.getLastCreatedEnvironmentID());
        HealthCheckParamVO hcp = new HealthCheckParamVO();
        hcp.setHealthCheckParamKey("key_1");
        hcp.setHealthCheckParamValue("value_1");
        List<HealthCheckParamVO> hcps = new ArrayList<HealthCheckParamVO>();
        hcps.add(hcp);
        hcv.setHealthCheckParamList(hcps);
        hcv.setHealthCheckTypeId(TestDaoService.healthCheckTypeID);
        hcv.setHealthCheckTypeName(healthCheckType.getHealthCheckTypeName());
        hcv.setMaxRetryCount(3);
        hcv.setParentComponentId(1);
        hcv.setParentComponentName("parent_1");
        hcv.setRegionId(TestDaoService.regionID);
        hcv.setRegionName(region.getRegionName());
        return hcv;
    }

    // public ApiStatusEnreplacedy createApiStatusEnreplacedy(Session session, String envName) {
    // // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    // ApiStatusEnreplacedy apse = new ApiStatusEnreplacedy();
    // session = sessionFactory.openSession();
    // Transaction trx = session.beginTransaction();
    // 
    // createEnvironment(envName, 0);
    // EnvironmentEnreplacedy envEnreplacedy = envDao.getEnvironmentFromName(envName);
    // 
    // createComponentType();
    // createComponent();
    // ComponentEnreplacedy parentComponentEnreplacedy = session.get(ComponentEnreplacedy.clreplaced, compID);
    // createComponent();
    // ComponentEnreplacedy componentEnreplacedy = session.get(ComponentEnreplacedy.clreplaced, compID);
    // componentEnreplacedy.setParentComponent(parentComponentEnreplacedy);
    // parentCompID++;
    // session.save(componentEnreplacedy);
    // 
    // apse.setEnvironment(envEnreplacedy);
    // apse.setComponent(componentEnreplacedy);
    // long date = System.currentTimeMillis();
    // apse.setStatsDate(new java.sql.Date(date));
    // apse.setDeltaValue(1);
    // apse.setTotalApi(1);
    // session.save(apse);
    // apiStatusID++;
    // trx.commit();
    // session.close();
    // return apse;
    // 
    // }
    // 
    // 
    // public AppRoleEnreplacedy createAppRoleEnreplacedy() {
    // AppRoleEnreplacedy appRoleEnreplacedy=new AppRoleEnreplacedy();
    // Session session = sessionFactory.openSession();
    // Transaction trx = session.beginTransaction();
    // ComponentTypeEnreplacedy cte = new ComponentTypeEnreplacedy();
    // cte.setComponentTypeId(ComponentType.APP.ordinal());
    // cte.setComponentTypeName(ComponentType.APP.name());
    // 
    // AppLookUpEnreplacedy aluEnreplacedy = new AppLookUpEnreplacedy();
    // aluEnreplacedy.setApplookupId(1);
    // aluEnreplacedy.setComponentFullName("component_full_name_1");
    // 
    // ComponentEnreplacedy compEnreplacedy = new ComponentEnreplacedy();
    // compEnreplacedy.setAppLookUpEnreplacedy(aluEnreplacedy);
    // compEnreplacedy.setComponentId(1);
    // compEnreplacedy.setComponentName("component_1");
    // compEnreplacedy.setComponentType(cte);
    // compEnreplacedy.setComponentDesc("component_desc");
    // compEnreplacedy.setDelInd(1);
    // 
    // ComponentEnreplacedy parentComp = new ComponentEnreplacedy();
    // compEnreplacedy.setAppLookUpEnreplacedy(aluEnreplacedy);
    // compEnreplacedy.setComponentId(1);
    // compEnreplacedy.setComponentName("parent_component_1");
    // compEnreplacedy.setComponentType(cte);
    // compEnreplacedy.setParentComponent(parentComp);
    // appRoleEnreplacedy.setComponent(compEnreplacedy);
    // appRoleEnreplacedy.setAppRoleName("appRoleName");
    // session.save(appRoleEnreplacedy);
    // trx.commit();
    // session.close();
    // appRoleID++;
    // return appRoleEnreplacedy;
    // }
    // 
    // public DaillyCompStatusEnreplacedy getDailyStatusEnreplacedy(String envName) {
    // DaillyCompStatusEnreplacedy daillyCompStatusEnreplacedy=new DaillyCompStatusEnreplacedy();
    // Session session = sessionFactory.openSession();
    // Transaction trx = session.beginTransaction();
    // createHealthCheck(envName);
    // daillyCompStatusEnreplacedy.setHealthCheck(session.get(HealthCheckEnreplacedy.clreplaced, new Integer(healthCheckID)));
    // 
    // StatusEnreplacedy se=new StatusEnreplacedy();
    // se.setStatusId(1);
    // se.setStatusName("statusName");
    // daillyCompStatusEnreplacedy.setStatus(se);
    // 
    // createComponentType();
    // createComponent();
    // ComponentEnreplacedy parentComponentEnreplacedy = session.get(ComponentEnreplacedy.clreplaced, compID);
    // createComponent();
    // ComponentEnreplacedy componentEnreplacedy = session.get(ComponentEnreplacedy.clreplaced, compID);
    // componentEnreplacedy.setParentComponent(parentComponentEnreplacedy);
    // parentCompID++;
    // session.save(componentEnreplacedy);
    // 
    // long date = System.currentTimeMillis();
    // daillyCompStatusEnreplacedy.setStatusDate(new java.sql.Date(date));
    // 
    // session.save(se);
    // session.save(daillyCompStatusEnreplacedy);
    // dailyCompStatusID++;
    // trx.commit();
    // session.close();
    // return daillyCompStatusEnreplacedy;
    // 
    // }
    // 
    // public K8sContainerStatusEnreplacedy createK8sContainerStatusEnreplacedy(Session session, String envName) {
    // K8sContainerStatusEnreplacedy k8sContainerStatusEnreplacedy=new K8sContainerStatusEnreplacedy();
    // session = sessionFactory.openSession();
    // Transaction trx = session.beginTransaction();
    // 
    // createEnvironment(envName, 0);
    // EnvironmentEnreplacedy envEnreplacedy = envDao.getEnvironmentFromName(envName);
    // 
    // createComponentType();
    // createComponent();
    // ComponentEnreplacedy parentComponentEnreplacedy = session.get(ComponentEnreplacedy.clreplaced, compID);
    // createComponent();
    // ComponentEnreplacedy componentEnreplacedy = session.get(ComponentEnreplacedy.clreplaced, compID);
    // componentEnreplacedy.setParentComponent(parentComponentEnreplacedy);
    // parentCompID++;
    // session.save(componentEnreplacedy);
    // 
    // k8sContainerStatusEnreplacedy.setEnvironment(envEnreplacedy);
    // k8sContainerStatusEnreplacedy.setComponent(componentEnreplacedy);
    // long date = System.currentTimeMillis();
    // k8sContainerStatusEnreplacedy.setStatsDate(new java.sql.Date(date));
    // k8sContainerStatusEnreplacedy.setTotalContainer(1);
    // 
    // session.save(k8sContainerStatusEnreplacedy);
    // k8sContainerStatsID++;
    // trx.commit();
    // session.close();
    // return k8sContainerStatusEnreplacedy;
    // 
    // }
    public K8sApiStatusEnreplacedy createK8sApiStatusEnreplacedy(Session session, String envName) {
        K8sApiStatusEnreplacedy k8sApiStatusEnreplacedy = new K8sApiStatusEnreplacedy();
        session = sessionFactory.openSession();
        Transaction trx = session.beginTransaction();
        createEnvironment(envName, 0);
        EnvironmentEnreplacedy envEnreplacedy = envDao.getEnvironmentFromName(envName);
        createComponentType();
        createComponent();
        ComponentEnreplacedy parentComponentEnreplacedy = session.get(ComponentEnreplacedy.clreplaced, compID);
        createComponent();
        ComponentEnreplacedy componentEnreplacedy = session.get(ComponentEnreplacedy.clreplaced, compID);
        componentEnreplacedy.setParentComponent(parentComponentEnreplacedy);
        parentCompID++;
        session.save(componentEnreplacedy);
        k8sApiStatusEnreplacedy.setComponent(componentEnreplacedy);
        k8sApiStatusEnreplacedy.setEnvironment(envEnreplacedy);
        k8sApiStatusEnreplacedy.setDeltaValue(1);
        k8sApiStatusEnreplacedy.setTotalApi(1);
        long date = System.currentTimeMillis();
        k8sApiStatusEnreplacedy.setStatusDate(new java.sql.Date(date));
        k8sApiStatusID++;
        trx.commit();
        session.close();
        return k8sApiStatusEnreplacedy;
    }

    // test
    public K8sTpsLatencyHistoryEnreplacedy createK8sTpsLatencyHistoryEnreplacedy(Session session, String envName) {
        K8sTpsLatencyHistoryEnreplacedy historyEnreplacedy = new K8sTpsLatencyHistoryEnreplacedy();
        session = sessionFactory.openSession();
        Transaction trx = session.beginTransaction();
        createEnvironment(envName, 0);
        EnvironmentEnreplacedy envEnreplacedy = envDao.getEnvironmentFromName(envName);
        createComponentType();
        createComponent();
        ComponentEnreplacedy parentComponentEnreplacedy = session.get(ComponentEnreplacedy.clreplaced, compID);
        createComponent();
        ComponentEnreplacedy componentEnreplacedy = session.get(ComponentEnreplacedy.clreplaced, compID);
        componentEnreplacedy.setParentComponent(parentComponentEnreplacedy);
        parentCompID++;
        session.save(componentEnreplacedy);
        historyEnreplacedy.setComponent(componentEnreplacedy);
        historyEnreplacedy.setEnvironment(envEnreplacedy);
        historyEnreplacedy.setLatencyValue(0.0);
        historyEnreplacedy.setTpsValue(0.0);
        long date = System.currentTimeMillis();
        historyEnreplacedy.setStatusDate(new java.sql.Date(date));
        tpsLatencyID++;
        trx.commit();
        session.close();
        return historyEnreplacedy;
    }

    // test
    public TpsServiceEnreplacedy createTpsServiceEnreplacedy(Session session, String envName) {
        TpsServiceEnreplacedy tse = new TpsServiceEnreplacedy();
        session = sessionFactory.openSession();
        Transaction trx = session.beginTransaction();
        createEnvironment(envName, 0);
        EnvironmentEnreplacedy envEnreplacedy = envDao.getEnvironmentFromName(envName);
        createComponentType();
        createComponent();
        ComponentEnreplacedy parentComponentEnreplacedy = session.get(ComponentEnreplacedy.clreplaced, compID);
        createComponent();
        ComponentEnreplacedy componentEnreplacedy = session.get(ComponentEnreplacedy.clreplaced, compID);
        componentEnreplacedy.setParentComponent(parentComponentEnreplacedy);
        parentCompID++;
        session.save(componentEnreplacedy);
        tse.setComponent(componentEnreplacedy);
        tse.setEnvironment(envEnreplacedy);
        tse.setLatencyValue(0.0);
        tse.setTpsValue(0.0);
        tpsServiceID++;
        session.save(tse);
        trx.commit();
        session.close();
        return tse;
    }

    public ApiStatusEnreplacedy createApiStatusEnreplacedy(String envName) {
        // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        ApiStatusEnreplacedy apse = new ApiStatusEnreplacedy();
        Session session = sessionFactory.openSession();
        Transaction trx = session.beginTransaction();
        createEnvironment(envName, 0);
        EnvironmentEnreplacedy envEnreplacedy = envDao.getEnvironmentFromName(envName);
        createComponentType();
        createComponent();
        ComponentEnreplacedy parentComponentEnreplacedy = session.get(ComponentEnreplacedy.clreplaced, compID);
        createComponent();
        ComponentEnreplacedy componentEnreplacedy = session.get(ComponentEnreplacedy.clreplaced, compID);
        componentEnreplacedy.setParentComponent(parentComponentEnreplacedy);
        parentCompID++;
        session.save(componentEnreplacedy);
        apse.setEnvironment(envEnreplacedy);
        apse.setComponent(componentEnreplacedy);
        long date = System.currentTimeMillis();
        apse.setStatusDate(new java.sql.Date(date));
        apse.setDeltaValue(1);
        apse.setTotalApi(1);
        session.save(apse);
        apiStatusID++;
        trx.commit();
        session.close();
        return apse;
    }

    // test
    public K8sPodsContainersEnreplacedy createK8sPodsStatusEnreplacedy(Session session, String envName) {
        K8sPodsContainersEnreplacedy k8sPStE = new K8sPodsContainersEnreplacedy();
        session = sessionFactory.openSession();
        Transaction trx = session.beginTransaction();
        createEnvironment(envName, 0);
        EnvironmentEnreplacedy envEnreplacedy = envDao.getEnvironmentFromName(envName);
        createComponentType();
        createComponent();
        ComponentEnreplacedy parentComponentEnreplacedy = session.get(ComponentEnreplacedy.clreplaced, compID);
        createComponent();
        ComponentEnreplacedy componentEnreplacedy = session.get(ComponentEnreplacedy.clreplaced, compID);
        componentEnreplacedy.setParentComponent(parentComponentEnreplacedy);
        parentCompID++;
        session.save(componentEnreplacedy);
        k8sPStE.setEnvironment(envEnreplacedy);
        k8sPStE.setComponent(componentEnreplacedy);
        long date = System.currentTimeMillis();
        k8sPStE.setStatusDate(new java.sql.Date(date));
        k8sPStE.setTotalPods(1);
        k8sPStE.setTotalContainers(1);
        session.save(k8sPStE);
        k8sPodsStatusID++;
        trx.commit();
        session.close();
        return k8sPStE;
    }

    // test
    public AppRoleEnreplacedy createAppRoleEnreplacedy() {
        AppRoleEnreplacedy appRoleEnreplacedy = new AppRoleEnreplacedy();
        Session session = sessionFactory.openSession();
        Transaction trx = session.beginTransaction();
        // appRoleEnreplacedy.setAppRoleId(1);
        ComponentTypeEnreplacedy cte = new ComponentTypeEnreplacedy();
        cte.setComponentTypeId(ComponentType.APP.ordinal());
        cte.setComponentTypeName(ComponentType.APP.name());
        AppLookUpEnreplacedy aluEnreplacedy = new AppLookUpEnreplacedy();
        aluEnreplacedy.setApplookupId(1);
        aluEnreplacedy.setComponentFullName("component_full_name_1");
        ComponentEnreplacedy compEnreplacedy = new ComponentEnreplacedy();
        compEnreplacedy.setAppLookUpEnreplacedy(aluEnreplacedy);
        compEnreplacedy.setComponentId(1);
        compEnreplacedy.setComponentName("component_1");
        compEnreplacedy.setComponentType(cte);
        compEnreplacedy.setComponentDesc("component_desc");
        compEnreplacedy.setDelInd(1);
        ComponentEnreplacedy parentComp = new ComponentEnreplacedy();
        compEnreplacedy.setAppLookUpEnreplacedy(aluEnreplacedy);
        compEnreplacedy.setComponentId(1);
        compEnreplacedy.setComponentName("parent_component_1");
        compEnreplacedy.setComponentType(cte);
        compEnreplacedy.setParentComponent(parentComp);
        appRoleEnreplacedy.setComponent(compEnreplacedy);
        appRoleEnreplacedy.setAppRoleName("appRoleName");
        session.save(appRoleEnreplacedy);
        trx.commit();
        session.close();
        appRoleID++;
        return appRoleEnreplacedy;
    }

    // test
    public DaillyCompStatusEnreplacedy createDailyStatusEnreplacedy(String envName) {
        createHealthCheck(envName);
        Session session = sessionFactory.openSession();
        Transaction trx = session.beginTransaction();
        DaillyCompStatusEnreplacedy daillyCompStatusEnreplacedy = new DaillyCompStatusEnreplacedy();
        daillyCompStatusEnreplacedy.setHealthCheck(session.get(HealthCheckEnreplacedy.clreplaced, new Integer(healthCheckID - 1)));
        StatusEnreplacedy se = new StatusEnreplacedy();
        se.setStatusId(1);
        se.setStatusName("statusName");
        session.save(se);
        daillyCompStatusEnreplacedy.setStatus(se);
        long date = System.currentTimeMillis();
        daillyCompStatusEnreplacedy.setStatusDate(new java.sql.Date(date));
        session.save(daillyCompStatusEnreplacedy);
        dailyCompStatusID++;
        trx.commit();
        session.close();
        return daillyCompStatusEnreplacedy;
    }

    // test
    public ComponentMessages createComponentMessages(Session session, String envName, String region) {
        session = sessionFactory.openSession();
        createEnvironment(envName, 0);
        createComponentType();
        Component comp = createComponent();
        createComponent(comp);
        createRegionEnreplacedy(session, region);
        ComponentMessages cm = getComponentMessage();
        cm.setEnvironment(envName);
        cm.setComponentid("" + compID);
        cm.setRegion(region);
        regionMessageDao.saveCompMessage(cm);
        compMessageID++;
        session.close();
        return cm;
    }

    public ComponentMessages getComponentMessage() {
        ComponentMessages cm = new ComponentMessages();
        cm.setAuthToken("authToken_1");
        cm.setMessage("message");
        cm.setUserid("userid");
        cm.setUsername("username");
        return cm;
    }

    // test
    public K8sPodsContainersEnreplacedy createK8sContainerStatusEnreplacedy(Session session, String envName) {
        K8sPodsContainersEnreplacedy k8sContainerStatusEnreplacedy = new K8sPodsContainersEnreplacedy();
        session = sessionFactory.openSession();
        Transaction trx = session.beginTransaction();
        createEnvironment(envName, 0);
        EnvironmentEnreplacedy envEnreplacedy = envDao.getEnvironmentFromName(envName);
        createComponentType();
        createComponent();
        ComponentEnreplacedy parentComponentEnreplacedy = session.get(ComponentEnreplacedy.clreplaced, compID);
        createComponent();
        ComponentEnreplacedy componentEnreplacedy = session.get(ComponentEnreplacedy.clreplaced, compID);
        componentEnreplacedy.setParentComponent(parentComponentEnreplacedy);
        parentCompID++;
        session.save(componentEnreplacedy);
        k8sContainerStatusEnreplacedy.setEnvironment(envEnreplacedy);
        k8sContainerStatusEnreplacedy.setComponent(componentEnreplacedy);
        long date = System.currentTimeMillis();
        k8sContainerStatusEnreplacedy.setStatusDate(new java.sql.Date(date));
        k8sContainerStatusEnreplacedy.setTotalContainers(1);
        session.save(k8sContainerStatusEnreplacedy);
        k8sContainerStatsID++;
        trx.commit();
        session.close();
        return k8sContainerStatusEnreplacedy;
    }
    /*	public ComponentEnreplacedy getComponentEnreplacedy() {

		ComponentTypeEnreplacedy cte = new ComponentTypeEnreplacedy();
		cte.setComponentTypeId(ComponentType.APP.ordinal());
		cte.setComponentTypeName(ComponentType.APP.name());
		
		AppLookUpEnreplacedy aluEnreplacedy = new AppLookUpEnreplacedy();
		aluEnreplacedy.setApplookupId(1);
		aluEnreplacedy.setComponentFullName("component_full_name_1");

		ComponentEnreplacedy compEnreplacedy = new ComponentEnreplacedy();
		compEnreplacedy.setAppLookUpEnreplacedy(aluEnreplacedy);
		compEnreplacedy.setComponentId(1);
		compEnreplacedy.setComponentName("component_1");
		compEnreplacedy.setComponentType(cte);
		compEnreplacedy.setComponentDesc("component_desc");
		compEnreplacedy.setDelInd(1);

		ComponentEnreplacedy parentComp = new ComponentEnreplacedy();
		compEnreplacedy.setAppLookUpEnreplacedy(aluEnreplacedy);
		compEnreplacedy.setComponentId(1);
		compEnreplacedy.setComponentName("parent_component_1");
		compEnreplacedy.setComponentType(cte);
		
		AppRoleEnreplacedy are=new AppRoleEnreplacedy();
		are.setAppRoleId(1);
		are.setAppRoleName("appRoleName_1");
		are.setComponent(compEnreplacedy);

		compEnreplacedy.setParentComponent(parentComp);
		
		HealthCheckEnreplacedy hce=new HealthCheckEnreplacedy();
		hce.setComponent(compEnreplacedy);
		
		StatusEnreplacedy se=new StatusEnreplacedy();
		se.setStatusId(1);
		se.setStatusName("statusName");		
		hce.setCurrentStatus(se);
		return compEnreplacedy;

	}
    public EnvironmentMessages createEnvironmentmessages() {
    	EnvironmentMessages envMesg = new EnvironmentMessages();
    	envMesg.setAppMessage("appMessage");
    	envMesg.setGeneralMessage("generalMessage");
    	envMesg.setInfraMessage("infraMessage"); 
    	Session session=sessionFactory.openSession();
    	Transaction trx = session.beginTransaction();
    	session.save(envMesg);
    	trx.commit();
       	return envMesg;
  	}

	public EnvironmentEnreplacedy createEnvEnreplacedy() {
		EnvironmentEnreplacedy envty = new EnvironmentEnreplacedy();
		envty.setEnvironmentId(1);
		envty.setEnvLock(1);
		envty.setDisplayOrder(1);
		envty.setAppMessage("appMessage_1");
		envty.setEnvironmentDesc("environmentDesc_1");
		envty.setEnvironmentName("environmentName_1");
		envty.setGeneralMessage("generalMessage_1");
		envty.setMarathonCred("marathonCred_1");
		envty.setMarathonUrl("marathonUrl_1");
		return envty;
	}*/
}

19 Source : TpsLatencyStatusDaoImpl.java
with Apache License 2.0
from tmobile

@Repository
public clreplaced TpsLatencyStatusDaoImpl implements TpsLatencyStatusDao {

    @Autowired
    private SessionFactory sessionFactory;

    @Autowired
    private EnvironmentDao environmentDao;

    @Override
    public List<TpsLatencyHistory> getTotalTpsLatency(String startDate, String endDate, String environment, String componentIdsStrg) throws ParseException {
        List<TpsLatencyHistory> tpsLatStsList = new ArrayList<TpsLatencyHistory>();
        int envId;
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<Integer> comIdList = DaoUtil.convertCSVToList(componentIdsStrg);
        Date sDate = sdf.parse(startDate);
        Date eDate = sdf.parse(endDate);
        Session session = sessionFactory.openSession();
        List<Object[]> totTps = null;
        Criteria tpsLatencyCriteria = session.createCriteria(TpsLatencyHistoryEnreplacedy.clreplaced, "tpsLatSts");
        tpsLatencyCriteria.createCriteria("tpsLatSts.component", "component");
        tpsLatencyCriteria.add(Restrictions.gt("tpsLatSts.statusDate", sDate));
        tpsLatencyCriteria.add(Restrictions.le("tpsLatSts.statusDate", eDate));
        if (comIdList.size() > 0) {
            tpsLatencyCriteria.add(Restrictions.in("component.componentId", comIdList));
            if (environment != null && !environment.equalsIgnoreCase("all")) {
                envId = environmentDao.getEnironmentIdFromName(environment);
                tpsLatencyCriteria.add(Restrictions.eq("tpsLatSts.environment.environmentId", envId));
                Query parentTpsLatQuery = session.createQuery(HQLConstants.QUERY_GET_SUM_PARENT_TPS_LATENCY_HISTORY_ENV);
                parentTpsLatQuery.setParameter("envId", envId);
                parentTpsLatQuery.setParameter("startDate", sDate);
                parentTpsLatQuery.setParameter("endDate", eDate);
                parentTpsLatQuery.setParameterList("parentComponentList", comIdList);
                totTps = parentTpsLatQuery.list();
            } else {
                Query parentTpsLatQuery = session.createQuery(HQLConstants.QUERY_GET_SUM_PARENT_TPS_LATENCY_HISTORY_ALL_ENV);
                parentTpsLatQuery.setParameterList("parentComponentList", comIdList);
                parentTpsLatQuery.setParameter("startDate", sDate);
                parentTpsLatQuery.setParameter("endDate", eDate);
                totTps = parentTpsLatQuery.list();
            }
        } else {
            if (environment != null && !environment.equalsIgnoreCase("all")) {
                envId = environmentDao.getEnironmentIdFromName(environment);
                tpsLatencyCriteria.add(Restrictions.eq("tpsLatSts.environment.environmentId", envId));
                Query parentTpsLatQuery = session.createQuery(HQLConstants.QUERY_GET_SUM_ALL_TPS_LATENCY_HISTORY_ENV);
                parentTpsLatQuery.setParameter("envId", envId);
                totTps = parentTpsLatQuery.list();
            } else {
                Query parentTpsLatQuery = session.createQuery(HQLConstants.QUERY_GET_SUM_ALL_TPS_LATENCY_HISTORY_ALL_ENV);
                totTps = parentTpsLatQuery.list();
            }
        }
        ProjectionList projectionList = Projections.projectionList();
        projectionList.add(Projections.property("component.componentId"));
        projectionList.add(Projections.property("component.componentName"));
        projectionList.add(Projections.property("tpsLatSts.statusDate"));
        projectionList.add(Projections.property("tpsLatSts.tpsValue"));
        projectionList.add(Projections.property("tpsLatSts.latencyValue"));
        tpsLatencyCriteria.setProjection(projectionList);
        @SuppressWarnings("unchecked")
        List<Object[]> appList = tpsLatencyCriteria.list();
        for (Object[] aRow : appList) {
            createTPSLatency(tpsLatStsList, aRow);
        }
        // Adding Tps and Latency for parent component id
        for (Object[] aRow : totTps) {
            createTPSLatency(tpsLatStsList, aRow);
        }
        session.close();
        return tpsLatStsList;
    }

    private void createTPSLatency(List<TpsLatencyHistory> tpsLatStsList, Object[] aRow) {
        TpsLatencyHistory tpsLatencyStatus = new TpsLatencyHistory();
        Integer comId = (Integer) aRow[0];
        tpsLatencyStatus.setComponentId(comId);
        String comName = (String) aRow[1];
        tpsLatencyStatus.setComponentName(comName);
        Date statsDate = (Date) aRow[2];
        tpsLatencyStatus.setStatusDate(statsDate.toString());
        double tpsValue = (double) aRow[3];
        tpsLatencyStatus.setTpsValue(tpsValue);
        double latencyValue = (double) aRow[4];
        tpsLatencyStatus.setLatencyValue(latencyValue);
        tpsLatStsList.add(tpsLatencyStatus);
    }
}

19 Source : TpsLatencyDaoImpl.java
with Apache License 2.0
from tmobile

@Repository
public clreplaced TpsLatencyDaoImpl implements TpsLatencyDao {

    @Autowired
    private SessionFactory sessionFactory;

    @Autowired
    private EnvironmentDao environmentDao;

    @SuppressWarnings("unchecked")
    @Override
    public List<TpsLatency> getCurrentTpsLatency(String environment, String platform) {
        Session session = sessionFactory.openSession();
        Query appTpsLatQuery = null;
        Criteria tpsLatCriteria = session.createCriteria(TpsServiceEnreplacedy.clreplaced, "tpsServ");
        tpsLatCriteria.createCriteria("tpsServ.component", "component");
        int envId = environmentDao.getEnironmentIdFromName(environment);
        tpsLatCriteria.add(Restrictions.eq("environment.environmentId", envId));
        if (platform != null && !platform.equalsIgnoreCase("All")) {
            tpsLatCriteria.add(Restrictions.eq("component.platform", platform));
        }
        List<TpsServiceEnreplacedy> apiTpsLatList = (List<TpsServiceEnreplacedy>) tpsLatCriteria.list();
        if (platform == null || platform.equalsIgnoreCase("All")) {
            appTpsLatQuery = session.createQuery(HQLConstants.QUERY_GET_SUM_TPS_VALUE);
            appTpsLatQuery.setParameter("envId", envId);
        } else {
            appTpsLatQuery = session.createQuery(HQLConstants.QUERY_GET_SUM_TPS_VALUE_PLATFORM);
            appTpsLatQuery.setParameter("envId", envId);
            appTpsLatQuery.setParameter("platform", platform);
        }
        List<TpsLatency> rettps = DaoUtil.convertToTpsLatency(apiTpsLatList, appTpsLatQuery);
        session.close();
        return rettps;
    }

    /* Get the TPS & Latency history */
    @Override
    public List<TpsLatencyHistory> getTpsAndLatOfParent(String startDate, String endDate, String environment, String componentIdsStrg, String platform) throws ParseException {
        List<TpsLatencyHistory> tpsLatList = DaoUtil.getTpsAndLatOfParent(startDate, endDate, environment, componentIdsStrg, platform, TpsLatencyHistoryEnreplacedy.clreplaced, sessionFactory, environmentDao);
        return tpsLatList;
    }

    @Override
    public List<TpsLatencyHistory> getTpsAndLatOfComponent(String startDate, String endDate, String environment, String componentIdsStrg, String platform) throws ParseException {
        List<TpsLatencyHistory> listOfTpsLatency = DaoUtil.getTpsAndLatOfComponent(startDate, endDate, environment, componentIdsStrg, Constants.PLATFORM_MESOS, TpsLatencyHistoryEnreplacedy.clreplaced, sessionFactory, environmentDao);
        return listOfTpsLatency;
    }

    @Override
    public TpsLatency getCurrentTpsAndLatency(String environment, String componentIdsStrg, boolean isParent, String platform) {
        TpsLatency tpsLat = DaoUtil.getCurrentTpsAndLatency(environment, componentIdsStrg, isParent, platform, sessionFactory, environmentDao);
        return tpsLat;
    }
}

19 Source : RegionMessageDaoImpl.java
with Apache License 2.0
from tmobile

/**
 * Updates the Message for component Implements RegionMessageDao
 */
@Repository
public clreplaced RegionMessageDaoImpl implements RegionMessageDao {

    @Autowired
    private SessionFactory sessionFactory;

    @Autowired
    private EnvironmentDao environmentDao;

    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");

    private static final int HOURS_TO_ADD = -24;

    private static Date getPreviousDayDate() {
        final Calendar cal = Calendar.getInstance();
        cal.add(Calendar.HOUR, HOURS_TO_ADD);
        return cal.getTime();
    }

    /**
     * Get the Component message for the componentId for the given environmentName and regionName
     */
    public List<Messages> getCompRegionMessage(String environmentName, String componentId, String regionName) {
        if (componentId == null || environmentName == null || regionName == null) {
            throw new IllegalArgumentException("Request Method parameter cannot be null");
        }
        int regionId = getRegionId(regionName);
        int environmentId = environmentDao.getEnironmentIdFromName(environmentName);
        Long compId = Long.parseLong(componentId);
        Set<Integer> childCompIdList = getAllChildWithStatusChange(compId.intValue(), regionId, environmentId, null);
        childCompIdList.add(compId.intValue());
        List<Messages> msgList = new ArrayList<Messages>();
        Session session = sessionFactory.openSession();
        Query query = session.createQuery(HQLConstants.QUERY_COMP_FAILURE_LOG);
        Date previousDay = getPreviousDayDate();
        for (Integer childCompId : childCompIdList) {
            query.setInteger("envId", environmentId).setInteger("regId", regionId).setInteger("compId", childCompId).setDate("prevoiusDay", previousDay);
            @SuppressWarnings("unchecked")
            List<Object[]> resultList = query.list();
            msgList.addAll(makeMessage(resultList));
        }
        query = session.createQuery(HQLConstants.QUERY_COMP_MESSAGE);
        query.setInteger("envId", environmentId).setInteger("regId", regionId).setParameterList("compIds", childCompIdList).setDate("prevoiusDay", previousDay);
        @SuppressWarnings("unchecked")
        List<Object[]> resultList = query.list();
        msgList.addAll(makeMessage(resultList));
        session.close();
        return msgList;
    }

    /**
     * Convert the result set to List of Messages
     *
     * @param resultList
     * @return
     */
    private List<Messages> makeMessage(List<Object[]> resultList) {
        List<Messages> messageList = new ArrayList<Messages>();
        for (Object[] resultObj : resultList) {
            Messages msg = new Messages();
            msg.setComponentName((String) resultObj[0]);
            msg.setMessageId((Integer) resultObj[1]);
            msg.setMessageDate(sdf.format((java.sql.Timestamp) resultObj[2]));
            msg.setMessage((String) resultObj[3]);
            msg.setUserId((String) resultObj[4]);
            messageList.add(msg);
        }
        return messageList;
    }

    /**
     * Gets the list of messages related to a component for a particular date
     */
    @Override
    public List<Messages> getCompRegionMessage(final String environmentName, final String componentId, final String regionName, final String histDateString) {
        if (componentId == null || environmentName == null || regionName == null || histDateString == null) {
            throw new IllegalArgumentException("Request Method parameter cannot be null");
        }
        Calendar histDate = Calendar.getInstance();
        try {
            histDate.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(histDateString));
            histDate.setTimeZone(TimeZone.getTimeZone("GMT"));
        } catch (ParseException e) {
            throw new IllegalArgumentException("History Date must be of yyyy-MM-dd format");
        }
        int regionId = getRegionId(regionName);
        int environmentId = environmentDao.getEnironmentIdFromName(environmentName);
        Long compId = Long.parseLong(componentId);
        Set<Integer> childCompIdList = getAllChildWithStatusChange(compId.intValue(), regionId, environmentId, histDate);
        childCompIdList.add(compId.intValue());
        List<Messages> msgList = new ArrayList<Messages>();
        // Getting messages till 11:59:59 pm of this day.
        histDate.add(Calendar.SECOND, ((24 * 60 * 60) - 1));
        Session session = sessionFactory.openSession();
        Query query = session.createQuery(HQLConstants.QUERY_COMP_FAILURE_LOG_HIS);
        for (Integer childCompId : childCompIdList) {
            query.setInteger("envId", environmentId).setInteger("regId", regionId).setInteger("compId", childCompId).setString("hisDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(histDate.getTime()));
            @SuppressWarnings("unchecked")
            List<Messages> resultList = makeMessage(query.list());
            List<Messages> messageList = new ArrayList<Messages>();
            Messages previousDateMessage = null;
            for (Messages resultMsg : resultList) {
                if (resultMsg.getMessageDate().startsWith(histDateString)) {
                    messageList.add(resultMsg);
                } else if (previousDateMessage == null) {
                    previousDateMessage = resultMsg;
                }
            }
            if (messageList.size() > 0) {
                msgList.addAll(messageList);
            } else if (previousDateMessage != null) {
                msgList.add(previousDateMessage);
            }
        }
        query = session.createQuery(HQLConstants.QUERY_COMP_MESSAGE_HIS);
        query.setInteger("envId", environmentId).setInteger("regId", regionId).setParameterList("compIds", childCompIdList).setCalendarDate("hisDate", histDate);
        @SuppressWarnings("unchecked")
        List<Object[]> resultList = query.list();
        msgList.addAll(makeMessage(resultList));
        session.close();
        return msgList;
    }

    /**
     * Returns the list of all the child component_id for the given parent_component_id.
     *
     * @param componentId
     * @return
     */
    @SuppressWarnings("unchecked")
    private Set<Integer> getAllChildWithStatusChange(int componentId, int regionId, int environmentId, Calendar histDate) {
        Session session = sessionFactory.openSession();
        Query query = session.createQuery(HQLConstants.QUERY_GET_CHILDREN_WITH_ERROR).setInteger("envId", environmentId).setInteger("regId", regionId).setInteger("parentCompId", componentId);
        if (histDate == null) {
            query.setDate("statusChangeTime", getPreviousDayDate());
        } else {
            query.setDate("statusChangeTime", histDate.getTime());
        }
        Set<Integer> childrenList = new HashSet<Integer>();
        for (ComponentEnreplacedy compObj : (List<ComponentEnreplacedy>) query.list()) {
            childrenList.add(compObj.getComponentId());
        }
        session.close();
        return childrenList;
    }

    /**
     * Insert data in ComponentMessages.
     */
    @Override
    public void saveCompMessage(ComponentMessages compMessage) {
        final int envId = environmentDao.getEnironmentIdFromName(compMessage.getEnvironment());
        final int regionId = getRegionId(compMessage.getRegion());
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        ComponentMessageEnreplacedy cme = new ComponentMessageEnreplacedy();
        cme.setMessage(compMessage.getMessage());
        cme.setUserId(compMessage.getUserid());
        cme.setUserName(compMessage.getUsername());
        cme.setMessageDate(new java.sql.Timestamp(System.currentTimeMillis()));
        ComponentEnreplacedy comp = new ComponentEnreplacedy();
        comp.setComponentId(Integer.parseInt(compMessage.getComponentid()));
        cme.setComponent(comp);
        EnvironmentEnreplacedy env = new EnvironmentEnreplacedy();
        env.setEnvironmentId(envId);
        cme.setEnvironment(env);
        RegionEnreplacedy reg = new RegionEnreplacedy();
        reg.setRegionId(regionId);
        cme.setRegion(reg);
        session.save(cme);
        tx.commit();
        session.close();
    }

    /**
     * Get region Id from region Name.
     *
     * @param region
     * @return
     */
    private int getRegionId(final String regionName) {
        if (regionName == null || regionName.trim().length() == 0) {
            throw new IllegalArgumentException("Region Name is not valid");
        }
        Session session = sessionFactory.openSession();
        Query query = session.createQuery(HQLConstants.GET_REGION_ID_FROM_NAME).setString("regName", regionName);
        RegionEnreplacedy reg = (RegionEnreplacedy) query.uniqueResult();
        session.close();
        return reg.getRegionId();
    }

    /**
     * Updates the message of component_message for the given message_id.
     */
    @Override
    public void updateCompMessage(ComponentMessages compMessage) {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        Query query = session.createQuery(HQLConstants.QUERY_UPDATE_COMP_MESSAGE).setString("msg", compMessage.getMessage()).setInteger("messageId", compMessage.getMessageId());
        query.executeUpdate();
        tx.commit();
        session.close();
    }
}

19 Source : K8sTpsLatencyDaoImpl.java
with Apache License 2.0
from tmobile

@Repository
public clreplaced K8sTpsLatencyDaoImpl implements K8sTpsLatencyDao {

    @Autowired
    private SessionFactory sessionFactory;

    @Autowired
    private EnvironmentDao environmentDao;

    @SuppressWarnings("unchecked")
    @Override
    public List<TpsLatency> getCurrentTpsLatency(String environment) {
        Session session = sessionFactory.openSession();
        Criteria tpsLatCriteria = session.createCriteria(TpsServiceEnreplacedy.clreplaced);
        int envId = environmentDao.getEnironmentIdFromName(environment);
        tpsLatCriteria.add(Restrictions.eq("environment.environmentId", envId));
        List<TpsServiceEnreplacedy> apiTpsLatList = (List<TpsServiceEnreplacedy>) tpsLatCriteria.list();
        Query appTpsLatQuery = session.createQuery(HQLConstants.QUERY_GET_SUM_TPS_VALUE);
        appTpsLatQuery.setParameter("envId", envId);
        List<TpsLatency> rettps = DaoUtil.convertToTpsLatency(apiTpsLatList, appTpsLatQuery);
        session.close();
        return rettps;
    }

    /* Get the TPS & Latency history */
    @Override
    public List<TpsLatencyHistory> getTpsAndLatOfParent(String startDate, String endDate, String environment, String componentIdsStrg, String platform) throws ParseException {
        List<TpsLatencyHistory> tpsLatList = DaoUtil.getTpsAndLatOfParent(startDate, endDate, environment, componentIdsStrg, platform, K8sTpsLatencyHistoryEnreplacedy.clreplaced, sessionFactory, environmentDao);
        return tpsLatList;
    }

    @Override
    public List<TpsLatencyHistory> getTpsAndLatOfComponent(String startDate, String endDate, String environment, String componentIdsStrg, String platform) throws ParseException {
        List<TpsLatencyHistory> listOfTpsLatency = DaoUtil.getTpsAndLatOfComponent(startDate, endDate, environment, componentIdsStrg, Constants.PLATFORM_K8S, K8sTpsLatencyHistoryEnreplacedy.clreplaced, sessionFactory, environmentDao);
        return listOfTpsLatency;
    }

    @Override
    public TpsLatency getCurrentTpsAndLatency(String environment, String componentIdsStrg, boolean isParent) {
        TpsLatency tpsLat = DaoUtil.getCurrentTpsAndLatency(environment, componentIdsStrg, isParent, null, sessionFactory, environmentDao);
        return tpsLat;
    }
}

19 Source : K8sPodsStatusDaoImpl.java
with Apache License 2.0
from tmobile

@Repository
public clreplaced K8sPodsStatusDaoImpl implements K8sPodsStatusDao {

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public List<ApiStatus> getPodsStatus(String startDate, String endDate, int envId, String componentIdsStrg, boolean isParentComponents) throws ParseException {
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<Integer> comIdList = DaoUtil.convertCSVToList(componentIdsStrg);
        Date sDate = sdf.parse(startDate);
        Date eDate = sdf.parse(endDate);
        Session session = sessionFactory.openSession();
        Criteria containerCriteria = session.createCriteria(K8sPodsContainersEnreplacedy.clreplaced, "contSts");
        containerCriteria.createCriteria("contSts.component", "component");
        containerCriteria.add(Restrictions.gt("contSts.statusDate", sDate));
        containerCriteria.add(Restrictions.le("contSts.statusDate", eDate));
        DaoUtil.addEnvironmentToCriteria(envId, isParentComponents, comIdList, containerCriteria);
        ProjectionList projectionList = Projections.projectionList();
        projectionList.add(Projections.property("component.componentId"));
        projectionList.add(Projections.property("statusDate"));
        projectionList.add(Projections.property("totalPods"));
        projectionList.add(Projections.property("environment.environmentId"));
        containerCriteria.setProjection(projectionList);
        @SuppressWarnings("unchecked")
        List<Object[]> K8sPodsList = containerCriteria.list();
        List<ApiStatus> k8sList = new ArrayList<ApiStatus>();
        for (Object[] aRow : K8sPodsList) {
            ApiStatus k8sStatus = new ApiStatus();
            Integer comId = (Integer) aRow[0];
            k8sStatus.setComponentId(comId);
            Date statsDate = (Date) aRow[1];
            k8sStatus.setStatusDate(statsDate.toString());
            Integer totalPods = (Integer) aRow[2];
            k8sStatus.setTotalPods(totalPods);
            Integer environmentId = (Integer) aRow[3];
            k8sStatus.setEnvironmentId(environmentId);
            k8sList.add(k8sStatus);
        }
        session.close();
        return k8sList;
    }

    @Override
    public long getCurrentNumberOfPods(int envId, String componentIdsStrg, boolean isParentComponents) throws ParseException {
        List<Integer> comIdList = DaoUtil.convertCSVToList(componentIdsStrg);
        Session session = sessionFactory.openSession();
        DetachedCriteria subMaxDate = DetachedCriteria.forClreplaced(K8sPodsContainersEnreplacedy.clreplaced);
        subMaxDate.setProjection(Projections.max("statusDate"));
        Criteria crtCurrentCont = session.createCriteria(K8sPodsContainersEnreplacedy.clreplaced, "contSts");
        crtCurrentCont.createCriteria("contSts.component", "component");
        crtCurrentCont.add(Property.forName("statusDate").eq(subMaxDate));
        DaoUtil.addEnvironmentToCriteria(envId, isParentComponents, comIdList, crtCurrentCont);
        crtCurrentCont.setProjection(Projections.sum("totalPods"));
        long currentNumOfCont = (long) (crtCurrentCont.uniqueResult() == null ? (long) 0 : crtCurrentCont.uniqueResult());
        session.close();
        return currentNumOfCont;
    }

    /**
     * Function to get the number of pods or containters of K8s objects, based on the object argument preplaceded.
     * @param environment
     * @param objPodsCont :: Possible values are either "pods" or "containers"
     * @return
     */
    @Override
    public long getRemK8sObjectPods(int envId, String objPodsCont) {
        Session session = sessionFactory.openSession();
        DetachedCriteria subMaxDate = DetachedCriteria.forClreplaced(K8sObjectPodsEnreplacedy.clreplaced);
        subMaxDate.setProjection(Projections.max("statusDate"));
        Criteria crtCurrentCont = session.createCriteria(K8sObjectPodsEnreplacedy.clreplaced, "objPods");
        crtCurrentCont.createCriteria("objPods.environment", "environment");
        crtCurrentCont.add(Property.forName("statusDate").eq(subMaxDate));
        if (envId != 0) {
            crtCurrentCont.add(Restrictions.eq("environment.environmentId", envId));
        }
        crtCurrentCont.add(Restrictions.eq("environment.envLock", 0));
        crtCurrentCont.setProjection(Projections.sum(objPodsCont));
        long currentNumOfCont = (long) (crtCurrentCont.uniqueResult() == null ? (long) 0 : crtCurrentCont.uniqueResult());
        session.close();
        return currentNumOfCont;
    }
}

19 Source : K8sContainerStatusDaoImpl.java
with Apache License 2.0
from tmobile

@Repository
public clreplaced K8sContainerStatusDaoImpl implements K8sContainerStatusDao {

    @Autowired
    private SessionFactory sessionFactory;

    /*
	 * Get APP containers, based on the input parameters date, environment & component ids
	 */
    @Override
    public List<K8sPodsContainersEnreplacedy> getEnvContainers(String startDate, String endDate, int envId, String componentIdsStrg, boolean isParentComponents) throws ParseException {
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<Integer> comIdList = DaoUtil.convertCSVToList(componentIdsStrg);
        Date sDate = sdf.parse(startDate);
        Date eDate = sdf.parse(endDate);
        Session session = sessionFactory.openSession();
        Criteria containerCriteria = session.createCriteria(K8sPodsContainersEnreplacedy.clreplaced, "contSts");
        containerCriteria.createCriteria("contSts.component", "component");
        containerCriteria.add(Restrictions.gt("contSts.statusDate", sDate));
        containerCriteria.add(Restrictions.le("contSts.statusDate", eDate));
        DaoUtil.addEnvironmentToCriteria(envId, isParentComponents, comIdList, containerCriteria);
        @SuppressWarnings("unchecked")
        List<K8sPodsContainersEnreplacedy> listContEnreplacedy = containerCriteria.list();
        session.close();
        return listContEnreplacedy;
    }

    @Override
    public List<K8sContainerStatus> getAllContainersOfParent(String startDate, String endDate, int envId, String componentIdsStrg) throws ParseException {
        final SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        List<Integer> comIdList = DaoUtil.convertCSVToList(componentIdsStrg);
        Date sDate = sdf1.parse(startDate);
        Date eDate = sdf1.parse(endDate);
        Session session = sessionFactory.openSession();
        Criteria containerCriteria = session.createCriteria(K8sPodsContainersEnreplacedy.clreplaced, "contSts");
        containerCriteria.createCriteria("contSts.component", "component");
        containerCriteria.createCriteria("contSts.environment", "environment");
        containerCriteria.add(Restrictions.ge("contSts.statusDate", sDate));
        containerCriteria.add(Restrictions.le("contSts.statusDate", eDate));
        if (envId != 0) {
            containerCriteria.add(Restrictions.eq("environment.environmentId", envId));
        }
        containerCriteria.add(Restrictions.eq("environment.envLock", 0));
        if (comIdList != null && comIdList.size() != 0) {
            containerCriteria.add(Restrictions.in("component.parentComponent.componentId", comIdList));
        }
        ProjectionList projectionList = DaoUtil.getContainerStatusProjectionList();
        containerCriteria.setProjection(projectionList);
        @SuppressWarnings("unchecked")
        List<Object[]> conList = containerCriteria.list();
        List<K8sContainerStatus> contStatusList = new ArrayList<K8sContainerStatus>();
        for (Object[] aRow : conList) {
            K8sContainerStatus contStatus = new K8sContainerStatus();
            Integer comId = (Integer) aRow[0];
            contStatus.setComponentId(comId);
            Date statsDate = (Date) aRow[1];
            contStatus.setStatusDate(statsDate.toString());
            long totalCont = (long) aRow[2];
            contStatus.setTotalContainers(totalCont);
            contStatusList.add(contStatus);
        }
        session.close();
        return contStatusList;
    }

    @Override
    public long getCurrentNumberOfContainsers(int envId, String componentIdsStrg, boolean isParentComponents) throws ParseException {
        List<Integer> comIdList = DaoUtil.convertCSVToList(componentIdsStrg);
        Session session = sessionFactory.openSession();
        DetachedCriteria subMaxDate = DetachedCriteria.forClreplaced(K8sPodsContainersEnreplacedy.clreplaced);
        subMaxDate.setProjection(Projections.max("statusDate"));
        Criteria crtCurrentCont = session.createCriteria(K8sPodsContainersEnreplacedy.clreplaced, "contSts");
        crtCurrentCont.createCriteria("contSts.component", "component");
        crtCurrentCont.add(Property.forName("statusDate").eq(subMaxDate));
        DaoUtil.addEnvironmentToCriteria(envId, isParentComponents, comIdList, crtCurrentCont);
        crtCurrentCont.setProjection(Projections.sum("totalContainers"));
        long currentNumOfCont = (long) (crtCurrentCont.uniqueResult() == null ? (long) 0 : crtCurrentCont.uniqueResult());
        session.close();
        return currentNumOfCont;
    }

    @Override
    public List<ApiStatus> getRemK8sObjPodsCont(String startDate, String endDate, int envId) throws ParseException {
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date sDate = sdf.parse(startDate);
        Date eDate = sdf.parse(endDate);
        Session session = sessionFactory.openSession();
        Criteria podsCriteria = session.createCriteria(K8sObjectPodsEnreplacedy.clreplaced, "objPods");
        podsCriteria.createCriteria("objPods.environment", "environment");
        podsCriteria.add(Restrictions.gt("objPods.statusDate", sDate));
        podsCriteria.add(Restrictions.le("objPods.statusDate", eDate));
        if (envId != 0) {
            podsCriteria.add(Restrictions.eq("environment.environmentId", envId));
        }
        podsCriteria.add(Restrictions.eq("environment.envLock", 0));
        ProjectionList projectionList = Projections.projectionList();
        projectionList.add(Projections.property("objPods.objectName"));
        projectionList.add(Projections.sum("objPods.pods"));
        projectionList.add(Projections.sum("objPods.containers"));
        projectionList.add(Projections.property("objPods.statusDate"));
        projectionList.add(Projections.groupProperty("objPods.objectName"));
        projectionList.add(Projections.groupProperty("objPods.statusDate"));
        podsCriteria.setProjection(projectionList);
        podsCriteria.addOrder(Order.asc("objPods.statusDate"));
        @SuppressWarnings("unchecked")
        List<Object[]> appList = podsCriteria.list();
        List<ApiStatus> apiStatusList = new ArrayList<ApiStatus>();
        for (Object[] aRow : appList) {
            ApiStatus apisStatus = new ApiStatus();
            String objName = (String) aRow[0];
            apisStatus.setComponentName(objName);
            long pods = (long) aRow[1];
            apisStatus.setTotalPods(pods);
            long cont = (long) aRow[2];
            apisStatus.setTotalContainers(cont);
            Date statsDate = (Date) aRow[3];
            apisStatus.setStatusDate(statsDate.toString());
            apiStatusList.add(apisStatus);
        }
        session.close();
        return apiStatusList;
    }
}

19 Source : K8sApiStatusDaoImpl.java
with Apache License 2.0
from tmobile

@Repository
public clreplaced K8sApiStatusDaoImpl implements K8sApiStatusDao {

    @Autowired
    private SessionFactory sessionFactory;

    /*
	 * Get Application APIS , based on the input parameters date, environment & component ids
	 */
    @Override
    public List<ApiStatus> getEnvApis(String startDate, String endDate, int envId, String componentIdsStrg) throws ParseException {
        Session session = sessionFactory.openSession();
        return DaoUtil.getEnvApis(startDate, endDate, envId, componentIdsStrg, session, K8sApiStatusEnreplacedy.clreplaced);
    }

    @Override
    public long getCurrentNumberOfApis(int envId, String componentIdsStrg) throws ParseException {
        List<Integer> comIdList = DaoUtil.convertCSVToList(componentIdsStrg);
        Session session = sessionFactory.openSession();
        DetachedCriteria subMaxDate = DetachedCriteria.forClreplaced(K8sApiStatusEnreplacedy.clreplaced);
        subMaxDate.setProjection(Projections.max("statusDate"));
        Criteria crtCurrenrApi = session.createCriteria(K8sApiStatusEnreplacedy.clreplaced);
        crtCurrenrApi.add(Property.forName("statusDate").eq(subMaxDate));
        DaoUtil.addEnvironmentToCriteria(envId, comIdList, crtCurrenrApi);
        crtCurrenrApi.setProjection(Projections.sum("totalApi"));
        long currentNumberOfApi = (long) (crtCurrenrApi.uniqueResult() == null ? (long) 0 : crtCurrenrApi.uniqueResult());
        session.close();
        return currentNumberOfApi;
    }
}

19 Source : CounterMatrixDaoImpl.java
with Apache License 2.0
from tmobile

/**
 * Data access operations on Counters Matrix
 * Implements CounterMatrixDao
 * Counters Matrix Features
 */
@Repository
public clreplaced CounterMatrixDaoImpl implements CounterMatrixDao {

    @Autowired
    private EnvironmentDao environmentDao;

    @Autowired
    private SessionFactory sessionFactory;

    private static final int HOURS_TO_ADD = -24;

    /**
     * Get All the global Counters for the given platform
     * @param platform
     * @return
     */
    @Override
    public List<Counters> getCounters(String platform) {
        final Map<Integer, List<Float>> metrixMap = getMetrixTrend(platform);
        Session session = sessionFactory.openSession();
        List<Counters> counterList = getCounterList(metrixMap, createCounterCriteria(0, session, platform), platform);
        session.close();
        return counterList;
    }

    /**
     * Function to get a list of counters from the created counterCriteria
     * @param metrixMap
     * @param counterCriteria
     * @param platform
     * @return
     */
    @SuppressWarnings("unchecked")
    private List<Counters> getCounterList(final Map<Integer, List<Float>> metrixMap, Criteria counterCriteria, String platform) {
        List<Counters> counterList = new ArrayList<Counters>();
        for (Object[] counterObj : (List<Object[]>) counterCriteria.list()) {
            Counters counter = new Counters();
            counter.setCounterName(String.valueOf(counterObj[0]));
            counter.setMetricDate(String.valueOf(counterObj[1]));
            float metricVal = Float.parseFloat(String.valueOf(counterObj[2]));
            /*Checking the Up time: And making sure the value is 100 or less than 100*/
            if (counter.getCounterName().equalsIgnoreCase("Up Time In %")) {
                metricVal = metricVal > 100 ? metricVal / 2 : metricVal;
            }
            counter.setMetricVal(metricVal);
            counter.setPosition(Integer.parseInt(String.valueOf(counterObj[3])));
            if (metrixMap != null) {
                counter.setTrend(metrixMap.get(Integer.valueOf(String.valueOf(counterObj[4]))));
            }
            counterList.add(counter);
        }
        return counterList;
    }

    /**
     * Get the Metrix trend - For ploating graph.
     *
     * @return
     */
    public Map<Integer, List<Float>> getMetrixTrend(String platform) {
        Session session = sessionFactory.openSession();
        Calendar c = Calendar.getInstance();
        c.add(Calendar.HOUR, -24);
        Map<Integer, List<Float>> mapOfMertix = createMatrixTrendMap(createCriteriaMatrixTrend(0, session, platform), platform, 0);
        session.close();
        return mapOfMertix;
    }

    /**
     * Function to get a map of matrix trends from the counterCriteria
     * @param counterCriteria
     * @return
     */
    @SuppressWarnings("unchecked")
    private Map<Integer, List<Float>> createMatrixTrendMap(Criteria counterCriteria, String platform, int envId) {
        Map<Integer, List<Float>> mapOfMertix = new HashMap<Integer, List<Float>>();
        Map<Integer, Integer> envCounterMap = null;
        if ((platform == null || platform.equals("All")) && envId != 0) {
            envCounterMap = getCounterEnvCount();
        }
        for (Object[] counterObj : (List<Object[]>) counterCriteria.list()) {
            List<Float> metricList = mapOfMertix.get(Integer.valueOf(String.valueOf(counterObj[0])));
            if (platform == null || platform.equals("All")) {
                if ((Integer.valueOf(String.valueOf(counterObj[2])) == 1 && envCounterMap.get(Integer.valueOf(String.valueOf(counterObj[3]))) == 2)) {
                    continue;
                }
            }
            if (metricList == null) {
                metricList = new ArrayList<Float>();
            }
            int counterId = Integer.valueOf(String.valueOf(counterObj[0]));
            float metricVal;
            metricVal = Float.valueOf(String.valueOf(counterObj[1]));
            if (counterId == 5) {
                metricVal = metricVal > 100 ? metricVal / 2 : metricVal;
            }
            metricList.add(metricVal);
            mapOfMertix.put(counterId, metricList);
        }
        return mapOfMertix;
    }

    /**
     * Get list of all counter in the given platform & environment
     *
     * @param environment
     * @param platform
     * @return List<Counters>
     */
    @Override
    public List<Counters> getEnvironmentCounters(String environment, String platform) {
        final int envId = environmentDao.getEnironmentIdFromName(environment);
        final Map<Integer, List<Float>> metrixMap = getEnvironmentMetrixTrend(envId, platform);
        Session session = sessionFactory.openSession();
        List<Counters> counterList = getCounterList(metrixMap, createCounterCriteria(envId, session, platform), platform);
        session.close();
        return counterList;
    }

    /**
     * Function to create criteria for CounterEnreplacedy clreplaced
     * @param envId
     * @param session
     * @param platform
     * @return Criteria
     */
    private Criteria createCounterCriteria(final int envId, Session session, String platform) {
        DetachedCriteria counterSubquery = DetachedCriteria.forClreplaced(CounterMetricEnreplacedy.clreplaced, "cm").setProjection(Property.forName("metricDate").max());
        Criteria counterCriteria = session.createCriteria(CounterEnreplacedy.clreplaced, "counter");
        counterCriteria.addOrder(Order.asc("counter.position"));
        Criteria envCounCriteria = counterCriteria.createCriteria("counter.envCounter", "ec");
        if (platform != null && !platform.equalsIgnoreCase("All")) {
            envCounCriteria.add(Restrictions.eq("ec.platform", platform));
        }
        Criteria metricCriteria = envCounCriteria.createCriteria("ec.countMetric", "counterMetric");
        counterSubquery.add(Property.forName("ec.envCounterId").eqProperty("cm.envCounterId"));
        metricCriteria.add(Subqueries.propertyEq("counterMetric.metricDate", counterSubquery));
        // metricCriteria.add(Restrictions.le("counterMetric.metricDate", new Date()));
        counterCriteria.add(Restrictions.eq("counter.delInd", 0));
        if (envId != 0) {
            envCounCriteria.add(Restrictions.eq("environmentId", envId));
        } else {
            envCounCriteria.add(Restrictions.isNull("environmentId"));
        }
        counterCriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENreplacedY);
        ProjectionList projectionList = Projections.projectionList();
        projectionList.add(Projections.max("counter.counterName"));
        projectionList.add(Projections.max("counterMetric.metricDate"));
        projectionList.add(Projections.sum("counterMetric.metricVal"));
        projectionList.add(Projections.max("counter.position"));
        projectionList.add(Projections.property("counter.counterId"));
        projectionList.add(Projections.groupProperty("counter.counterId"));
        counterCriteria.setProjection(projectionList);
        return counterCriteria;
    }

    /**
     * Get Environment Metrix Trend with environment.
     *
     * @param envId
     * @param platform
     * @return
     */
    private Map<Integer, List<Float>> getEnvironmentMetrixTrend(final int envId, String platform) {
        Session session = sessionFactory.openSession();
        Map<Integer, List<Float>> mapOfMertix = createMatrixTrendMap(createCriteriaMatrixTrend(envId, session, platform), platform, envId);
        session.close();
        return mapOfMertix;
    }

    private Criteria createCriteriaMatrixTrend(final int envId, Session session, String platform) {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.HOUR, HOURS_TO_ADD);
        Criteria counterCriteria = session.createCriteria(CounterEnreplacedy.clreplaced, "counter");
        counterCriteria.addOrder(Order.asc("counter.position"));
        Criteria envCounCriteria = counterCriteria.createCriteria("counter.envCounter", "ec");
        if (platform != null && !platform.equalsIgnoreCase("All")) {
            envCounCriteria.add(Restrictions.eq("ec.platform", platform));
        }
        Criteria metricCriteria = envCounCriteria.createCriteria("ec.countMetric", "counterMetric");
        counterCriteria.add(Restrictions.eq("counter.delInd", 0));
        if (envId != 0) {
            Criteria environmentCriteria = envCounCriteria.createCriteria("ec.environment", "environment");
            environmentCriteria.add(Restrictions.eq("environment.environmentId", envId));
        } else {
            envCounCriteria.add(Restrictions.isNull("environmentId"));
        }
        metricCriteria.add(Restrictions.gt("counterMetric.metricDate", c.getTime()));
        metricCriteria.addOrder(Order.asc("counterMetric.metricDate"));
        ProjectionList projectionList = Projections.projectionList();
        projectionList.add(Projections.property("counter.counterId"));
        projectionList.add(Projections.sum("counterMetric.metricVal"));
        projectionList.add(Projections.count("counter.counterId"));
        projectionList.add(Projections.max("ec.environment.environmentId"));
        projectionList.add(Projections.groupProperty("counter.counterId"));
        projectionList.add(Projections.groupProperty("counterMetric.metricDate"));
        counterCriteria.setProjection(projectionList);
        return counterCriteria;
    }

    /**
     * Get Environment Metrix Trend with environment.
     *
     * @param envId
     * @return
     */
    private Map<Integer, Integer> getCounterEnvCount() {
        Session session = sessionFactory.openSession();
        Map<Integer, Integer> mapOfMertix = new HashMap<Integer, Integer>();
        Criteria counterCriteria = session.createCriteria(EnvCounterEnreplacedy.clreplaced, "envCounter");
        counterCriteria.add(Restrictions.isNotNull("environmentId"));
        ProjectionList projectionList = Projections.projectionList();
        projectionList.add(Projections.property("envCounter.environmentId"));
        projectionList.add(Projections.count("envCounter.environmentId"));
        projectionList.add(Projections.groupProperty("envCounter.counterId"));
        projectionList.add(Projections.groupProperty("envCounter.environmentId"));
        counterCriteria.setProjection(projectionList);
        for (Object[] counterObj : (List<Object[]>) counterCriteria.list()) {
            mapOfMertix.put(Integer.valueOf(String.valueOf(counterObj[0])), Integer.valueOf(String.valueOf(counterObj[1])));
        }
        session.close();
        return mapOfMertix;
    }
}

19 Source : ContainerStatusDaoImpl.java
with Apache License 2.0
from tmobile

/**
 * Dao Clreplaced to get the container stats.
 */
@Repository
public clreplaced ContainerStatusDaoImpl implements ContainerStatusDao {

    @Autowired
    private SessionFactory sessionFactory;

    /*
	 * Get APP containers, based on the input parameters date, environment & component ids
	 */
    @Override
    public List<ContainerStatusEnreplacedy> getEnvContainers(String startDate, String endDate, int envId, String componentIdsStrg, boolean isParentComponents) throws ParseException {
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<Integer> comIdList = DaoUtil.convertCSVToList(componentIdsStrg);
        Date sDate = sdf.parse(startDate);
        Date eDate = sdf.parse(endDate);
        Session session = sessionFactory.openSession();
        Criteria containerCriteria = session.createCriteria(ContainerStatusEnreplacedy.clreplaced, "contSts");
        containerCriteria.createCriteria("contSts.component", "component");
        containerCriteria.add(Restrictions.ge("contSts.statsDate", sDate));
        containerCriteria.add(Restrictions.le("contSts.statsDate", eDate));
        DaoUtil.addEnvironmentToCriteria(envId, isParentComponents, comIdList, containerCriteria);
        @SuppressWarnings("unchecked")
        List<ContainerStatusEnreplacedy> listContEnreplacedy = containerCriteria.list();
        session.close();
        return listContEnreplacedy;
    }

    @Override
    public List<ContainerStatus> getAllContainersOfParent(String startDate, String endDate, int envId, String componentIdsStrg) throws ParseException {
        final SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        List<Integer> comIdList = DaoUtil.convertCSVToList(componentIdsStrg);
        Date sDate = sdf1.parse(startDate);
        Date eDate = sdf1.parse(endDate);
        Session session = sessionFactory.openSession();
        Criteria containerCriteria = session.createCriteria(ContainerStatusEnreplacedy.clreplaced, "contSts");
        containerCriteria.createCriteria("contSts.component", "component");
        containerCriteria.createCriteria("contSts.environment", "environment");
        containerCriteria.add(Restrictions.ge("contSts.statsDate", sDate));
        containerCriteria.add(Restrictions.le("contSts.statsDate", eDate));
        if (envId != 0) {
            containerCriteria.add(Restrictions.eq("environment.environmentId", envId));
        }
        containerCriteria.add(Restrictions.eq("environment.envLock", 0));
        if (comIdList != null && comIdList.size() != 0) {
            containerCriteria.add(Restrictions.in("component.parentComponent.componentId", comIdList));
        }
        ProjectionList projectionList = Projections.projectionList();
        projectionList.add(Projections.property("component.parentComponent.componentId"));
        projectionList.add(Projections.property("contSts.statsDate"));
        projectionList.add(Projections.sum("contSts.totalContainer"));
        projectionList.add(Projections.groupProperty("component.parentComponent.componentId"));
        projectionList.add(Projections.groupProperty("contSts.statsDate"));
        containerCriteria.setProjection(projectionList);
        @SuppressWarnings("unchecked")
        List<Object[]> conList = containerCriteria.list();
        List<ContainerStatus> contStatusList = DaoUtil.createContainerStatuses(conList);
        session.close();
        return contStatusList;
    }

    @Override
    public long getCurrentNumberOfContainsers(int envId, String componentIdsStrg, boolean isParentComponents) throws ParseException {
        List<Integer> comIdList = DaoUtil.convertCSVToList(componentIdsStrg);
        Session session = sessionFactory.openSession();
        DetachedCriteria subMaxDate = DetachedCriteria.forClreplaced(ContainerStatusEnreplacedy.clreplaced);
        subMaxDate.setProjection(Projections.max("statsDate"));
        Criteria crtCurrentCont = session.createCriteria(ContainerStatusEnreplacedy.clreplaced, "contSts");
        crtCurrentCont.createCriteria("contSts.component", "component");
        crtCurrentCont.add(Property.forName("statsDate").eq(subMaxDate));
        DaoUtil.addEnvironmentToCriteria(envId, isParentComponents, comIdList, crtCurrentCont);
        crtCurrentCont.setProjection(Projections.sum("totalContainer"));
        long currentNumOfCont = (long) (crtCurrentCont.uniqueResult() == null ? (long) 0 : crtCurrentCont.uniqueResult());
        session.close();
        return currentNumOfCont;
    }
}

19 Source : AvailabilityPercentageDaoImpl.java
with Apache License 2.0
from tmobile

/**
 * Implements AvailabilityPercentageDao to access availability percentage in the database
 */
@Repository
public clreplaced AvailabilityPercentageDaoImpl implements AvailabilityPercentageDao {

    private static final String SIMPLE_DATE_FORMAT = "yyyy-MM-dd";

    @Autowired
    private EnvironmentDao environmentDao;

    @Autowired
    private SessionFactory sessionFactory;

    public List<AvailabilityData> getAllAvailabilityPercentage(String environment, String interval, String platform, String region) throws ParseException {
        final int envId = environmentDao.getEnironmentIdFromName(environment);
        SimpleDateFormat sdf = new SimpleDateFormat(SIMPLE_DATE_FORMAT);
        Calendar cal = Calendar.getInstance();
        String startDate = null;
        String endDate = sdf.format(cal.getTime());
        if (interval.equalsIgnoreCase("D")) {
            startDate = sdf.format(cal.getTime());
        } else if (interval.equalsIgnoreCase("M")) {
            cal.add(Calendar.MONTH, -1);
            startDate = sdf.format(cal.getTime());
        } else if (interval.equalsIgnoreCase("Y")) {
            cal.add(Calendar.YEAR, -1);
            startDate = sdf.format(cal.getTime());
        } else {
            throw new IllegalArgumentException("The Interval is not valid");
        }
        return getAvailability(envId, startDate, endDate, platform, region);
    }

    private List<AvailabilityData> getAvailability(final int envId, final String startDate, final String endDate, String platform, String region) throws ParseException {
        List<AvailabilityData> appPercentage = getAppAvailabilityPercentage(envId, startDate, endDate, platform, region);
        List<AvailabilityData> infraPercentage = getInfraAvailability(envId, startDate, endDate, platform, region);
        infraPercentage.addAll(appPercentage);
        List<AvailabilityData> listPercentage = infraPercentage;
        return listPercentage;
    }

    /**
     * Get the Region wise Availability % of each App services.
     * @param envId
     * @param startDate
     * @param endDate
     * @param platform
     * @param region
     * @return
     * @throws ParseException
     */
    @SuppressWarnings("unchecked")
    private List<AvailabilityData> getAppAvailabilityPercentage(final int envId, final String startDate, final String endDate, String platform, String region) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(SIMPLE_DATE_FORMAT);
        Session session = sessionFactory.openSession();
        Query appQuery = null;
        Query apiQuery = null;
        if (platform.equalsIgnoreCase("All")) {
            appQuery = session.createQuery(HQLConstants.QUERY_GET_APP_AVAILABILITY_PERCENTAGE).setCacheable(true).setCacheRegion("QUERY_GET_APP_AVAILABILITY_PERCENTAGE");
            appQuery.setParameter("envId", envId);
            appQuery.setParameter("startDate", sdf.parse(startDate));
            appQuery.setParameter("endDate", sdf.parse(endDate));
            appQuery.setParameter("regionName", region);
            apiQuery = session.createQuery(HQLConstants.QUERY_GET_API_AVAILABILITY_PERCENTAGE).setCacheable(true).setCacheRegion("QUERY_GET_API_AVAILABILITY_PERCENTAGE");
            apiQuery.setParameter("envId", envId);
            apiQuery.setParameter("startDate", sdf.parse(startDate));
            apiQuery.setParameter("endDate", sdf.parse(endDate));
            apiQuery.setParameter("regionName", region);
        } else {
            appQuery = session.createQuery(HQLConstants.QUERY_GET_APP_AVAILABILITY_PERCENTAGE_PLATFORM).setCacheable(true).setCacheRegion("QUERY_GET_APP_AVAILABILITY_PERCENTAGE");
            appQuery.setParameter("envId", envId);
            appQuery.setParameter("startDate", sdf.parse(startDate));
            appQuery.setParameter("endDate", sdf.parse(endDate));
            appQuery.setParameter("regionName", region);
            appQuery.setParameter("platform", platform);
            apiQuery = session.createQuery(HQLConstants.QUERY_GET_API_AVAILABILITY_PERCENTAGE_PLATFORM).setCacheable(true).setCacheRegion("QUERY_GET_API_AVAILABILITY_PERCENTAGE");
            apiQuery.setParameter("envId", envId);
            apiQuery.setParameter("startDate", sdf.parse(startDate));
            apiQuery.setParameter("endDate", sdf.parse(endDate));
            apiQuery.setParameter("regionName", region);
            apiQuery.setParameter("platform", platform);
        }
        List<Object[]> appList = appQuery.list();
        List<Object[]> apiList = apiQuery.list();
        session.close();
        appList.addAll(apiList);
        List<AvailabilityData> listOfAvl = new ArrayList<AvailabilityData>();
        for (Object[] aRow : appList) {
            Integer comId = (Integer) aRow[0];
            if (aRow[1] != null) {
                Double percentage = (Double) aRow[1];
                AvailabilityData avlData = new AvailabilityData();
                avlData.setComponentId(comId);
                if (region.equalsIgnoreCase(Region.WEST_REGION.getRegionDescription()))
                    avlData.setAvailabilityPercentageWest(percentage);
                else
                    avlData.setAvailabilityPercentageEast(percentage);
                listOfAvl.add(avlData);
            }
        }
        return listOfAvl;
    }

    /**
     * Get the Region wise Availability % of each Infra services.
     * @param envId
     * @param startDate
     * @param endDate
     * @param platform
     * @param region
     * @return
     * @throws ParseException
     */
    private List<AvailabilityData> getInfraAvailability(final int envId, final String startDate, final String endDate, String platform, String region) throws ParseException {
        Session session = sessionFactory.openSession();
        SimpleDateFormat sdf = new SimpleDateFormat(SIMPLE_DATE_FORMAT);
        Query query = null;
        if (platform.equalsIgnoreCase("All")) {
            query = session.createQuery(HQLConstants.QUERY_GET_INFRA_AVAILABILITY_PERCENTAGE).setCacheable(true).setCacheRegion("QUERY_GET_INFRA_AVAILABILITY_PERCENTAGE");
            query.setParameter("envId", envId);
            query.setParameter("startDate", sdf.parse(startDate));
            query.setParameter("endDate", sdf.parse(endDate));
            query.setParameter("regionName", region);
        } else {
            query = session.createQuery(HQLConstants.QUERY_GET_INFRA_AVAILABILITY_PERCENTAGE_PLATFORM).setCacheable(true).setCacheRegion("QUERY_GET_INFRA_AVAILABILITY_PERCENTAGE");
            query.setParameter("envId", envId);
            query.setParameter("startDate", sdf.parse(startDate));
            query.setParameter("endDate", sdf.parse(endDate));
            query.setParameter("platform", platform);
            query.setParameter("regionName", region);
        }
        @SuppressWarnings("unchecked")
        List<Object[]> listResult = query.list();
        session.close();
        Map<Integer, AvailabilityData> avlMap = new HashMap<Integer, AvailabilityData>();
        for (Object[] aRow : listResult) {
            Integer comId = (Integer) aRow[0];
            Float percentage = (Float) aRow[1];
            AvailabilityData avlData = null;
            if (avlMap.get(comId) == null) {
                avlData = new AvailabilityData();
                avlData.setComponentId(comId);
                if (region.equalsIgnoreCase("West Region"))
                    avlData.setAvailabilityPercentageWest(percentage);
                else
                    avlData.setAvailabilityPercentageEast(percentage);
            } else {
                avlData = avlMap.get(comId);
                // double avlPerc = avlData.getAvailabilityPercentageWest();
                if (region.equalsIgnoreCase("West Region"))
                    avlData.setAvailabilityPercentageWest((avlData.getAvailabilityPercentageWest() + percentage) / 2);
                else
                    avlData.setAvailabilityPercentageEast((avlData.getAvailabilityPercentageEast() + percentage) / 2);
            }
            avlMap.put(comId, avlData);
        }
        List<AvailabilityData> listOfAvl = new ArrayList<AvailabilityData>(avlMap.values());
        return listOfAvl;
    }
}

19 Source : AuditDaoImpl.java
with Apache License 2.0
from tmobile

@Repository
public clreplaced AuditDaoImpl implements AuditDao {

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public void saveAuditLog(Audit audit) {
        AuditEnreplacedy auditEnreplacedy = new AuditEnreplacedy();
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        auditEnreplacedy.setAudit_log(audit.getAudit_log());
        auditEnreplacedy.setDate(audit.getDate());
        auditEnreplacedy.setUser_id(audit.getUser_id());
        session.save(auditEnreplacedy);
        tx.commit();
        session.close();
    }
}

19 Source : ApiStatusDaoImpl.java
with Apache License 2.0
from tmobile

/**
 *  Dao Clreplaced to get the API status.
 */
@Repository
public clreplaced ApiStatusDaoImpl implements ApiStatusDao {

    @Autowired
    private SessionFactory sessionFactory;

    /*
	 * Get Application APIS , based on the input parameters date, environment & component ids
	 */
    @Override
    public List<ApiStatus> getEnvApis(String startDate, String endDate, int envId, String componentIdsStrg) throws ParseException {
        Session session = sessionFactory.openSession();
        return DaoUtil.getEnvApis(startDate, endDate, envId, componentIdsStrg, session, ApiStatusEnreplacedy.clreplaced);
    }

    @Override
    public long getCurrentNumberOfApis(int envId, String componentIdsStrg) throws ParseException {
        List<Integer> comIdList = DaoUtil.convertCSVToList(componentIdsStrg);
        Session session = sessionFactory.openSession();
        DetachedCriteria subMaxDate = DetachedCriteria.forClreplaced(ApiStatusEnreplacedy.clreplaced);
        subMaxDate.setProjection(Projections.max("statusDate"));
        Criteria crtCurrenrApi = session.createCriteria(ApiStatusEnreplacedy.clreplaced);
        crtCurrenrApi.add(Property.forName("statusDate").eq(subMaxDate));
        DaoUtil.addEnvironmentToCriteria(envId, comIdList, crtCurrenrApi);
        crtCurrenrApi.setProjection(Projections.sum("totalApi"));
        long currentNumberOfApi = (long) (crtCurrenrApi.uniqueResult() == null ? (long) 0 : crtCurrenrApi.uniqueResult());
        session.close();
        return currentNumberOfApi;
    }
}

19 Source : AlertSubscribeDaoImpl.java
with Apache License 2.0
from tmobile

/**
 * Implementation of AlertSubscribeDao to access data of alertSubscription table
 */
@Repository
public clreplaced AlertSubscribeDaoImpl implements AlertSubscribeDao {

    @Autowired
    private SessionFactory sessionFactory;

    /**
     * Function to save the subscription to the DB
     */
    @Override
    public void saveSubscription(Subscription subscription, int subsType, int validationLevel, boolean isGlobalSubscription) {
        if (subscription == null) {
            throw new IllegalArgumentException("Subscription is null");
        }
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        AlertSubscriptionEnreplacedy ase = new AlertSubscriptionEnreplacedy();
        if (!isGlobalSubscription) {
            if (subscription.getComponentId() == 0) {
                throw new IllegalArgumentException("ComponentId is 0");
            }
            ComponentEnreplacedy component = new ComponentEnreplacedy();
            component.setComponentId(subscription.getComponentId());
            ase.setComponent(component);
        }
        ase.setSubscriptionVal(subscription.getSubsciptionVal());
        ase.setAuthToken(subscription.getAuthToken());
        ase.setSubscriptionType(subsType);
        ase.setValidationLevel(validationLevel);
        EnvironmentEnreplacedy env = new EnvironmentEnreplacedy();
        env.setEnvironmentId(subscription.getEnvironmentId());
        ase.setEnvironment(env);
        if (isGlobalSubscription) {
            ase.setGlobalComponentTypeId(subscription.getGlobalSubscriptionTypeId());
        }
        ase.setPlatform(subscription.getPlatform());
        session.save(ase);
        tx.commit();
        session.close();
    }

    /**
     * Function to delete the subscription from the DB
     */
    @Override
    public void deleteSububscription(String authToken) {
        if (authToken == null) {
            throw new IllegalArgumentException("authToken is null");
        }
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        Criteria aseCriteria = session.createCriteria(AlertSubscriptionEnreplacedy.clreplaced);
        aseCriteria.add(Restrictions.eq("authToken", authToken));
        AlertSubscriptionEnreplacedy ase = (AlertSubscriptionEnreplacedy) aseCriteria.uniqueResult();
        session.delete(ase);
        tx.commit();
        session.close();
    }

    /**
     * Function to get the subscription status to a component for a user
     */
    @Override
    public String getSubscriptionToken(final String userEmail, final int compId, final int environmentId) {
        Session session = sessionFactory.openSession();
        Criteria aseCriteria = session.createCriteria(AlertSubscriptionEnreplacedy.clreplaced);
        aseCriteria.createCriteria("component", "c");
        aseCriteria.createCriteria("environment", "e");
        aseCriteria.add(Restrictions.eq("subscriptionVal", userEmail));
        aseCriteria.add(Restrictions.eq("c.componentId", compId));
        aseCriteria.add(Restrictions.eq("e.environmentId", environmentId));
        AlertSubscriptionEnreplacedy ase = (AlertSubscriptionEnreplacedy) aseCriteria.uniqueResult();
        session.close();
        return ase == null ? null : ase.getAuthToken();
    }

    /**
     * Set the validation level as true/1 for the subscription with give authToken
     */
    @Override
    public void confirmSubscription(String authToken) {
        if (authToken == null) {
            throw new IllegalArgumentException("authToken is null");
        }
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        Criteria aseCriteria = session.createCriteria(AlertSubscriptionEnreplacedy.clreplaced);
        aseCriteria.add(Restrictions.eq("authToken", authToken));
        AlertSubscriptionEnreplacedy ase = (AlertSubscriptionEnreplacedy) aseCriteria.uniqueResult();
        ase.setValidationLevel(1);
        session.update(ase);
        tx.commit();
        session.close();
    }

    /**
     * Get the list of all the subscription for the given componentId and environmentId
     */
    @Override
    public List<AlertSubscriptionEnreplacedy> getSubscribedEmailIdList(final int componentId, final int environmentId) {
        Session session = sessionFactory.openSession();
        Criteria aseCriteria = session.createCriteria(AlertSubscriptionEnreplacedy.clreplaced);
        aseCriteria.createCriteria("component", "c");
        aseCriteria.createCriteria("environment", "e");
        aseCriteria.add(Restrictions.eq("c.componentId", componentId));
        aseCriteria.add(Restrictions.eq("e.environmentId", environmentId));
        @SuppressWarnings("unchecked")
        List<AlertSubscriptionEnreplacedy> alertSubscriptionList = (List<AlertSubscriptionEnreplacedy>) aseCriteria.list();
        session.close();
        return alertSubscriptionList;
    }

    /**
     * Function to check for if a DB row exist for the given componentId and environmentId and subsciptionText
     */
    @Override
    public boolean checkforDuplicates(final int componentId, final int environmentId, final String subsciptionText) {
        Session session = sessionFactory.openSession();
        Criteria aseCriteria = session.createCriteria(AlertSubscriptionEnreplacedy.clreplaced);
        aseCriteria.createCriteria("component", "c");
        aseCriteria.createCriteria("environment", "e");
        aseCriteria.add(Restrictions.eq("subscriptionVal", subsciptionText));
        aseCriteria.add(Restrictions.eq("c.componentId", componentId));
        aseCriteria.add(Restrictions.eq("e.environmentId", environmentId));
        Number rowCount = (Number) aseCriteria.setProjection(Projections.rowCount()).uniqueResult();
        session.close();
        return rowCount.intValue() > 0 ? true : false;
    }

    /**
     * Checks whether the given subscription is available in DB.
     */
    @Override
    public boolean isSubscribtionAvailable(final Subscription subscription, final int subsType) {
        Session session = sessionFactory.openSession();
        Criteria aseCriteria = session.createCriteria(AlertSubscriptionEnreplacedy.clreplaced);
        aseCriteria.createCriteria("environment", "e");
        aseCriteria.add(Restrictions.eq("subscriptionVal", subscription.getSubsciptionVal()));
        aseCriteria.add(Restrictions.isNull("component"));
        aseCriteria.add(Restrictions.eq("subscriptionType", subsType));
        aseCriteria.add(Restrictions.eq("globalComponentTypeId", subscription.getGlobalSubscriptionTypeId()));
        aseCriteria.add(Restrictions.eq("e.environmentId", subscription.getEnvironmentId()));
        Number rowCount = (Number) aseCriteria.setProjection(Projections.rowCount()).uniqueResult();
        session.close();
        return rowCount.intValue() > 0 ? true : false;
    }

    /**
     * Function to get all global subscriptions from the database
     */
    @Override
    public List<AlertSubscriptionEnreplacedy> getAllGlobalSubscriptions() {
        Session session = sessionFactory.openSession();
        Criteria aseCriteria = session.createCriteria(AlertSubscriptionEnreplacedy.clreplaced);
        aseCriteria.add(Restrictions.isNull("component"));
        @SuppressWarnings("unchecked")
        List<AlertSubscriptionEnreplacedy> alertSubscriptionList = (List<AlertSubscriptionEnreplacedy>) aseCriteria.list();
        session.close();
        return alertSubscriptionList;
    }

    /**
     * Function to delete global subscription from the database.
     */
    @Override
    public void deleteGlobalSubscription(int subscriptionId) {
        if (subscriptionId == 0) {
            throw new IllegalArgumentException("Invalid subscription Id");
        }
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        AlertSubscriptionEnreplacedy ase = session.load(AlertSubscriptionEnreplacedy.clreplaced, subscriptionId);
        session.delete(ase);
        tx.commit();
        session.close();
    }
}

19 Source : HibernateUtil.java
with Apache License 2.0
from thefreebit

clreplaced HibernateUtil {

    private static SessionFactory sessionFactory;

    static {
        try {
            sessionFactory = createSessionFactory();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    private static SessionFactory createSessionFactory() throws Exception {
        Configuration configuration;
        try {
            configuration = new Configuration().configure();
        } catch (MappingException e) {
            // hibernate prior to 3.6.0
            Clreplaced<?> cfgClreplaced = Clreplaced.forName("org.hibernate.cfg.AnnotationConfiguration");
            configuration = ((Configuration) cfgClreplaced.newInstance()).configure();
        }
        return configuration.buildSessionFactory();
    }
}

19 Source : DrugsDAOImpl.java
with GNU General Public License v2.0
from taktik

public void openDataStoreSession() {
    SessionFactory factory = getSessionFactory();
    if (factory != null) {
        factory.getCurrentSession().beginTransaction();
    }
}

19 Source : EmpDaoImpl.java
with GNU General Public License v3.0
from srecon

/**
 * Created by shamim on 24/06/16.
 */
public clreplaced EmpDaoImpl implements EmpDao {

    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public List<Employee> getAllEmployees() {
        Session session = sessionFactory.openSession();
        Query query = session.createQuery("from Employee e");
        List<Employee> employees = query.list();
        session.close();
        if (employees != null && !employees.isEmpty()) {
            return employees;
        }
        return Collections.emptyList();
    }

    public void create(Integer empno, String ename, String job, Integer mgr) {
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        Employee emp = new Employee();
        emp.setEmpno(empno);
        emp.setEname(ename);
        emp.setJob(job);
        emp.setMgr(mgr);
        emp.setSal(1111);
        emp.setDeptno(10);
        emp.setDate(new Date(System.currentTimeMillis()));
        emp.setComm(111);
        session.save(emp);
        session.getTransaction().commit();
        session.close();
    }

    public List<Employee> getEmpByName(String ename) {
        Session session = sessionFactory.openSession();
        Query query = session.createQuery("from Employee e where e.ename=:ename");
        query.setParameter("ename", ename);
        query.setCacheable(true);
        List<Employee> employees = query.list();
        session.close();
        return employees;
    }

    @Override
    @Cacheable(value = "exchangeRate")
    public String getExchangeRateByRegion(String region) {
        Session session = sessionFactory.openSession();
        // in real life, it should be current date time
        SQLQuery query = session.createSQLQuery("select * from exchangerate e where e.ratedate = TO_DATE('2015-05-02','YYYY-MM-DD') and e.region=:region");
        query.setParameter("region", region);
        query.addEnreplacedy(ExchangeRate.clreplaced);
        ExchangeRate res = (ExchangeRate) query.uniqueResult();
        session.close();
        return String.valueOf(res.getUsdollar());
    }

    @Override
    @CacheEvict(value = "exchangeRate", key = "#e.region")
    public void updateExchange(ExchangeRate e) {
        Session session = sessionFactory.openSession();
        session.getTransaction().begin();
        SQLQuery query = session.createSQLQuery("update exchangerate \n" + " set usdollar = :usdollar" + " where region = :region and ratedate = TO_DATE('2015-05-02','YYYY-MM-DD')");
        query.setParameter("region", e.getRegion());
        query.setParameter("usdollar", e.getUsdollar());
        query.addEnreplacedy(ExchangeRate.clreplaced);
        query.executeUpdate();
        session.getTransaction().commit();
        session.close();
    }
}

19 Source : HibernateNativeEntityManagerFactoryIntegrationTests.java
with Apache License 2.0
from SourceHot

/**
 * Hibernate-specific JPA tests with native SessionFactory setup and getCurrentSession interaction.
 *
 * @author Juergen Hoeller
 * @since 5.1
 */
public clreplaced HibernateNativeEnreplacedyManagerFactoryIntegrationTests extends AbstractContainerEnreplacedyManagerFactoryIntegrationTests {

    @Autowired
    private SessionFactory sessionFactory;

    @Autowired
    private ApplicationContext applicationContext;

    @Override
    protected String[] getConfigLocations() {
        return new String[] { "/org/springframework/orm/jpa/hibernate/hibernate-manager-native.xml", "/org/springframework/orm/jpa/memdb.xml", "/org/springframework/orm/jpa/inject.xml" };
    }

    @Override
    @Test
    public void testEnreplacedyManagerFactoryImplementsEnreplacedyManagerFactoryInfo() {
        boolean condition = enreplacedyManagerFactory instanceof EnreplacedyManagerFactoryInfo;
        replacedertThat(condition).as("Must not have introduced config interface").isFalse();
    }

    @Test
    @SuppressWarnings("unchecked")
    public void testEnreplacedyListener() {
        String firstName = "Tony";
        insertPerson(firstName);
        List<Person> people = sharedEnreplacedyManager.createQuery("select p from Person as p").getResultList();
        replacedertThat(people.size()).isEqualTo(1);
        replacedertThat(people.get(0).getFirstName()).isEqualTo(firstName);
        replacedertThat(people.get(0).postLoaded).isSameAs(applicationContext);
    }

    @Test
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public void testCurrentSession() {
        String firstName = "Tony";
        insertPerson(firstName);
        Query q = sessionFactory.getCurrentSession().createQuery("select p from Person as p");
        List<Person> people = q.getResultList();
        replacedertThat(people.size()).isEqualTo(1);
        replacedertThat(people.get(0).getFirstName()).isEqualTo(firstName);
        replacedertThat(people.get(0).postLoaded).isSameAs(applicationContext);
    }

    // SPR-16956
    @Test
    public void testReadOnly() {
        replacedertThat(sessionFactory.getCurrentSession().getHibernateFlushMode()).isSameAs(FlushMode.AUTO);
        replacedertThat(sessionFactory.getCurrentSession().isDefaultReadOnly()).isFalse();
        endTransaction();
        this.transactionDefinition.setReadOnly(true);
        startNewTransaction();
        replacedertThat(sessionFactory.getCurrentSession().getHibernateFlushMode()).isSameAs(FlushMode.MANUAL);
        replacedertThat(sessionFactory.getCurrentSession().isDefaultReadOnly()).isTrue();
    }
}

19 Source : HibernateConfiguration.java
with Apache License 2.0
from skogaby

@Bean
public UserSongRecordDao userSongRecordDao(final SessionFactory sessionFactory) {
    return new UserSongRecordDao(sessionFactory);
}

19 Source : HibernateConfiguration.java
with Apache License 2.0
from skogaby

@Bean
public GlobalEventDao globalEventDao(final SessionFactory sessionFactory) {
    return new GlobalEventDao(sessionFactory);
}

19 Source : HibernateConfiguration.java
with Apache License 2.0
from skogaby

@Bean
public PcbEventLogDao pcbEventLogDao(final SessionFactory sessionFactory) {
    return new PcbEventLogDao(sessionFactory);
}

19 Source : HibernateConfiguration.java
with Apache License 2.0
from skogaby

@Bean
public ButterflyUserDao butterflyUserDao(final SessionFactory sessionFactory) {
    return new ButterflyUserDao(sessionFactory);
}

See More Examples