1 package com.trendmicro.grid.acl.ds.jpa;
2
3 import com.trendmicro.grid.acl.ds.SourceDomainRepository;
4 import com.trendmicro.grid.acl.ds.datatypes.SharedSourceDomain;
5 import com.trendmicro.grid.acl.ds.datatypes.SharedSourceDomainListPage;
6 import com.trendmicro.grid.acl.ds.jpa.entities.JpaSourceDomain;
7 import com.trendmicro.grid.acl.l0.datatypes.SourceDomain;
8 import org.slf4j.Logger;
9 import org.slf4j.LoggerFactory;
10 import org.springframework.stereotype.Repository;
11 import org.springframework.transaction.annotation.Transactional;
12
13 import javax.persistence.EntityManager;
14 import javax.persistence.PersistenceContext;
15 import javax.persistence.TypedQuery;
16 import java.util.List;
17
18
19
20
21
22
23
24 @Repository
25 @Transactional(readOnly = true)
26 public class JpaSourceDomainRepository implements SourceDomainRepository {
27
28 private static final Logger log = LoggerFactory.getLogger(JpaSourceDomainRepository.class);
29 private static int pageSize = 25;
30
31 public static int getPageSize() {
32 return pageSize;
33 }
34
35 public static void setPageSize(int pageSize) {
36 JpaSourceDomainRepository.pageSize = pageSize;
37 }
38
39 @PersistenceContext(unitName = "CoreDB")
40 EntityManager em;
41
42 @Override
43 public SharedSourceDomainListPage getAllPaged(int pageNumber) {
44 final TypedQuery<SharedSourceDomain> q = em.createNamedQuery("SourceDomain.SelectAll", SharedSourceDomain.class);
45
46 q.setFirstResult(pageNumber * pageSize).setMaxResults(pageSize + 1);
47 List<SharedSourceDomain> domains = q.getResultList();
48
49 boolean hasMore = domains.size() > pageSize;
50
51 if (hasMore) {
52 if (log.isTraceEnabled()) log.trace("Removing the indicator row that created the hasMore=true result.");
53 domains.remove(domains.size() - 1);
54 }
55
56 return new SharedSourceDomainListPage(pageNumber, !hasMore, domains);
57 }
58
59 @Override
60 public SharedSourceDomain getByName(String domainName) {
61 List<SharedSourceDomain> result = em.createNamedQuery("SourceDomain.SelectDomainByName", SharedSourceDomain.class).
62 setParameter("name", domainName).getResultList();
63
64 return result.isEmpty() ? null : result.get(0);
65 }
66
67 @Override
68 @Transactional(readOnly = false)
69 public SharedSourceDomain getOrCreate(String domainName) {
70 SharedSourceDomain domain = getByName(domainName);
71
72 if (domain == null) {
73 domain = new JpaSourceDomain(domainName);
74 em.persist(domain);
75 }
76
77 return domain;
78 }
79
80 @Override
81 @Transactional(readOnly = false)
82 public void createOrUpdate(SourceDomain domain) {
83 JpaSourceDomain jpaDomain = new JpaSourceDomain(domain);
84
85 if (jpaDomain.getPrimaryKey() == 0) {
86 final List<Integer> result = em.createNamedQuery("SourceDomain.SelectIdByName", Integer.class).
87 setParameter("name", domain.getName()).getResultList();
88
89 if (result.isEmpty())
90 em.persist(jpaDomain);
91 else
92 jpaDomain.setPrimaryKey(result.get(0));
93 }
94
95 em.merge(jpaDomain);
96 }
97 }