View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements. See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership. The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License. You may obtain a copy of the License at
9    *
10   * http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied. See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package com.tapas.evidence.repository.data;
20  
21  import java.io.Serializable;
22  import java.util.List;
23  
24  import javax.persistence.EntityManager;
25  import javax.persistence.EntityNotFoundException;
26  import javax.persistence.NonUniqueResultException;
27  import javax.persistence.Query;
28  
29  import org.slf4j.Logger;
30  import org.slf4j.LoggerFactory;
31  import org.springframework.security.core.context.SecurityContextHolder;
32  
33  import com.tapas.evidence.credential.EvidenceUserDetails;
34  import com.tapas.evidence.entity.TenantAware;
35  import com.tapas.evidence.entity.user.Tenant;
36  
37  /**
38   * @author Michal Bocek
39   * @since 1.0.0
40   */
41  public class CrudRepositoryImpl<T, ID extends Serializable> implements CrudRepository<T, ID> {
42  
43  	private static final Logger log = LoggerFactory.getLogger(CrudRepositoryImpl.class);
44  	
45  	private final EntityManager entityManager;
46  
47  	private final Class<T> entityClass;
48  	
49  	public CrudRepositoryImpl(Class<T> entityClass, EntityManager entityManager) {
50  		this.entityClass = entityClass;
51  		this.entityManager = entityManager;
52  	}
53  	
54  	@Override
55  	public void create(T entity) {
56  		if (log.isTraceEnabled()) {
57  			log.trace("Creating entity: " + entity.getClass());
58  			log.trace("  With contents: " + entity); 
59  		}
60  		if (entity instanceof TenantAware) {
61  			Long tenantId = ((EvidenceUserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getTenantId();
62  			Tenant tenant = this.entityManager.find(Tenant.class, tenantId);
63  			((TenantAware)entity).setTenant(tenant);
64  		}
65  		entityManager.persist(entity);
66  	}
67  
68  	@Override
69  	public T read(ID id) {
70  		if (log.isTraceEnabled()) {
71  			log.trace("Reading entity for id: " + id);
72  		}
73  		final T entry ;
74  		if (entityClass.isInstance(TenantAware.class)) {
75  			entry = readTenantAware(id);
76  		} else {
77  			entry = this.entityManager.find(this.entityClass, id);
78  		}	
79  		if (entry == null) {
80  			throw new EntityNotFoundException("Entity for class " + this.entityClass + " with id " + id
81  					+ " can not be found!");
82  		} 
83  		return entry;
84  	}
85  
86  	@SuppressWarnings({ "rawtypes", "unchecked" })
87  	private T readTenantAware(ID id) {
88  		final T entry;
89  		final Long tenantId = ((EvidenceUserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getTenantId();
90  		final Query query = this.entityManager.createQuery("from " + this.entityClass.getName() + " where tenant.id = :tenantId");
91  		query.setParameter("tenantId", tenantId);
92  		final List resultList = query.getResultList();
93  		if (resultList.size() == 1) {
94  			entry = (T)resultList.get(0);
95  		} else if (resultList.size() > 1) {
96  			throw new NonUniqueResultException("Non unique entity for class " + this.entityClass + " with id " + id
97  				+ "!");
98  		} else {
99  			entry = null;
100 		}
101 		return entry;
102 	}
103 
104 	@Override
105 	public T update(T entity) {
106 		if (log.isTraceEnabled()) {
107 			log.trace("Updating entity: " + entity.getClass());
108 			log.trace("  With contents: " + entity); 
109 		}
110 		return entityManager.merge(entity);
111 	}
112 
113 	@Override
114 	public void delete(T entity) {
115 		if (log.isTraceEnabled()) {
116 			log.trace("Deleting entity: " + entity.getClass());
117 			log.trace("  With contents: " + entity); 
118 		}
119 		entityManager.remove(entity);
120 	}
121 
122 	@Override
123 	public T findById(ID id) {
124 		final T result;
125 		if (entityClass.isInstance(TenantAware.class)) {
126 			result = readTenantAware(id);
127 		} else {
128 			result = this.entityManager.find(entityClass, id);
129 		}
130 		return result;
131 	}
132 
133 	@Override
134 	@SuppressWarnings("unchecked")
135 	public List<T> findAll() {
136 		if (log.isTraceEnabled()) {
137 			log.trace("Reading all entities");
138 		}
139 		final Query query;
140 		if (entityClass.isInstance(TenantAware.class)) {
141 			final Long tenantId = ((EvidenceUserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getTenantId();
142 			final String queryString = "from " + this.entityClass.getName() + "where tenant.id = :tenantId";
143 			query = this.entityManager.createQuery(queryString);
144 			query.setParameter("tenantId", tenantId);
145 		} else {
146 			final String queryString = "from " + this.entityClass.getName();
147 			query = this.entityManager.createQuery(queryString);
148 		}
149 		return query.getResultList();
150 	}
151 
152 }