Policy TestSuite Enabled
[policy/engine.git] / ECOMP-PAP-REST / src / main / java / org / openecomp / policy / pap / xacml / rest / util / JPAUtils.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP-PAP-REST
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.policy.pap.xacml.rest.util;
22
23 import java.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.Map;
27
28 import javax.persistence.EntityManager;
29 import javax.persistence.EntityManagerFactory;
30 import javax.persistence.Query;
31 import javax.servlet.ServletException;
32
33 import org.openecomp.policy.rest.XacmlAdminAuthorization;
34 import org.openecomp.policy.rest.jpa.Attribute;
35 import org.openecomp.policy.rest.jpa.Datatype;
36 import org.openecomp.policy.rest.jpa.FunctionDefinition;
37 import org.openecomp.policy.rest.jpa.GlobalRoleSettings;
38
39 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
40 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeSelectorType;
41
42 import org.openecomp.policy.common.logging.flexlogger.FlexLogger; 
43 import org.openecomp.policy.common.logging.flexlogger.Logger;
44
45 public class JPAUtils {
46         private static Logger LOGGER    = FlexLogger.getLogger(JPAUtils.class);
47         
48         private EntityManagerFactory emf;
49         private static final Object mapAccess = new Object();
50         private static Map<Datatype, List<FunctionDefinition>> mapDatatype2Function = null;
51         private static Map<String, FunctionDefinition> mapID2Function = null;
52         private static JPAUtils currentInstance = null;
53         
54         
55         /**
56          * Get an instance of a JPAUtils. It creates one if it does not exist.
57          * Only one instance is allowed to be created per server.
58          * @param emf The EntityFactoryManager to be used for database connections
59          * @return The new instance of JPAUtils or throw exception if the given emf is null.
60          * @throws IllegalStateException if a JPAUtils has already been constructed. Call getJPAUtilsInstance() to get this.
61          */
62         public static JPAUtils getJPAUtilsInstance(EntityManagerFactory emf) throws Exception{
63                 LOGGER.debug("getJPAUtilsInstance(EntityManagerFactory emf) as getJPAUtilsInstance("+emf+") called");
64                 if(currentInstance == null){
65                         if(emf != null){
66                                 currentInstance = new JPAUtils(emf);
67                                 return currentInstance;
68                         }
69                         throw new IllegalStateException("The EntityManagerFactory is Null");
70                 }
71                 return currentInstance;
72         }
73         
74         private JPAUtils(EntityManagerFactory emf){
75                 LOGGER.debug("JPAUtils(EntityManagerFactory emf) as JPAUtils("+emf+") called");
76                 this.emf = emf; 
77         }
78         
79         /**
80          * Gets the current instance of JPAUtils. 
81          * @return The instance of JPAUtils or throws exception if the given instance is null.
82          * @throws IllegalStateException if a JPAUtils instance is null. Call getJPAUtilsInstance(EntityManagerFactory emf) to get this.
83          */
84         public static JPAUtils getJPAUtilsInstance() throws Exception{
85                 LOGGER.debug("getJPAUtilsInstance() as getJPAUtilsInstance() called");
86                 if(currentInstance != null){
87                         return currentInstance;
88                 }
89                 throw new IllegalStateException("The JPAUtils.currentInstance is Null.  Use getJPAUtilsInstance(EntityManagerFactory emf)");
90         }
91         
92         public static AttributeDesignatorType   createDesignator(Attribute attribute) {
93                 AttributeDesignatorType designator = new AttributeDesignatorType();
94                 designator.setAttributeId(attribute.getXacmlId());
95                 if (attribute.getCategoryBean() != null) {
96                         designator.setCategory(attribute.getCategoryBean().getXacmlId());
97                 } else {
98                         LOGGER.warn("No category bean");
99                 }
100                 if (attribute.getDatatypeBean() != null) {
101                         designator.setDataType(attribute.getDatatypeBean().getXacmlId());
102                 } else {
103                         LOGGER.warn("No datatype bean");
104                 }
105                 designator.setIssuer(attribute.getIssuer());
106                 designator.setMustBePresent(attribute.isMustBePresent());
107                 return designator;
108         }
109                 
110         public static AttributeSelectorType     createSelector(Attribute attribute) {
111                 AttributeSelectorType selector = new AttributeSelectorType();
112                 selector.setContextSelectorId(attribute.getXacmlId());
113                 selector.setPath(attribute.getSelectorPath());
114                 if (attribute.getCategoryBean() != null) {
115                         selector.setCategory(attribute.getCategoryBean().getXacmlId());
116                 } else {
117                         LOGGER.warn("No category bean");
118                 }
119                 if (attribute.getDatatypeBean() != null) {
120                         selector.setDataType(attribute.getDatatypeBean().getXacmlId());
121                 } else {
122                         LOGGER.warn("No datatype bean");
123                 }
124                 selector.setMustBePresent(attribute.isMustBePresent());
125                 return selector;
126         }
127         
128         /**
129          * Builds a map in memory of a functions return datatype to function definition. Useful in limiting the number
130          * of SQL calls to DB especially when we don't expect these to change much.
131          * 
132          * @return - A HashMap of Datatype JPA Container ID's to FunctionDefinition objects
133          */
134         public Map<Datatype, List<FunctionDefinition>>  getFunctionDatatypeMap() {              
135                 
136                 synchronized(mapAccess) {
137                         if (mapDatatype2Function == null||mapDatatype2Function.isEmpty()) {
138                                 try {
139                                         buildFunctionMaps();
140                                 } catch (ServletException e) {
141                                         LOGGER.error("Exception Occured"+e);
142                                 }
143                         }
144                 }
145                 return mapDatatype2Function;
146         }
147         
148         public Map<String, FunctionDefinition> getFunctionIDMap() {
149                 synchronized(mapAccess) {
150                         if (mapID2Function == null||mapID2Function.equals("{}")) {
151                                 try {
152                                         buildFunctionMaps();
153                                 } catch (ServletException e) {
154                                         LOGGER.error("Exception Occured"+e);
155                                 }
156                         }
157                 }
158                 return mapID2Function;
159         }
160         
161         private void buildFunctionMaps() throws ServletException {
162                 mapDatatype2Function = new HashMap<Datatype, List<FunctionDefinition>>();
163                 mapID2Function = new HashMap<String, FunctionDefinition>();
164
165                 EntityManager em = emf.createEntityManager();
166                 Query getFunctionDefinitions = em.createNamedQuery("FunctionDefinition.findAll");       
167                 List<?> functionList = getFunctionDefinitions.getResultList();  
168                 
169                 for (Object id : functionList) {
170                         FunctionDefinition value = (FunctionDefinition)id;
171                         mapID2Function.put(value.getXacmlid(), value);
172                         if (mapDatatype2Function.containsKey(value.getDatatypeBean()) == false) {
173                                 mapDatatype2Function.put(value.getDatatypeBean(), new ArrayList<FunctionDefinition>());
174                         }
175                         mapDatatype2Function.get(value.getDatatypeBean()).add(value);
176                 }
177
178                 em.close();
179                 
180         }
181         
182         /**
183          * Returns the lockdown value, in case of exception it is assumed that lockdown functionality
184          * is not supported and returns false.
185          * 
186          * 
187          * @throws ReadOnlyException
188          * @throws ConversionException
189          */
190         public boolean dbLockdownIgnoreErrors() {
191                 if (LOGGER.isTraceEnabled())
192                         LOGGER.trace("ENTER");
193                 
194                 boolean lockdown = false;
195                 try {
196                         lockdown = dbLockdown();
197                 } catch (Exception e) {
198                         LOGGER.warn("Cannot access DB lockdown value", e);
199                 }
200                 return lockdown;
201         }
202         
203         /**
204          * Returns the lockdown value from the database.
205          * 
206          * @throws ReadOnlyException
207          * @throws ConversionException
208          */
209         public boolean dbLockdown() 
210                         throws  IllegalAccessException {
211                 if (LOGGER.isTraceEnabled())
212                         LOGGER.trace("ENTER");
213                 
214                 EntityManager em = emf.createEntityManager();
215                 Query globalRoleSettingsJPA = em.createNamedQuery("GlobalRoleSettings.findAll");        
216                 
217                 GlobalRoleSettings globalRoleSettings = (GlobalRoleSettings) globalRoleSettingsJPA.getSingleResult();
218                 
219                 if (globalRoleSettings == null) {
220                         // this should not happen
221                         String msg = "NO GlobalSetttings for " + XacmlAdminAuthorization.Role.ROLE_SUPERADMIN.toString();
222                         if (LOGGER.isErrorEnabled())
223                                 LOGGER.error(msg);
224                         throw new IllegalAccessException(msg);
225                 }
226                 
227                 if (!globalRoleSettings.getRole().equals(XacmlAdminAuthorization.Role.ROLE_SUPERADMIN.toString())) {
228                         String msg = "NOT FOUND db data for " + XacmlAdminAuthorization.Role.ROLE_SUPERADMIN.toString();
229                         if (LOGGER.isErrorEnabled())
230                                 LOGGER.error(msg);
231                         throw new IllegalAccessException(msg);
232                 }
233                 
234                 return globalRoleSettings.isLockdown();
235         }
236         
237         
238
239 }