Initial OpenECOMP policy/engine commit
[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         //private static List<LockdownListener> lockdownListeners = new ArrayList<LockdownListener>();
55         
56         /**
57          * Get an instance of a JPAUtils. It creates one if it does not exist.
58          * Only one instance is allowed to be created per server.
59          * @param emf The EntityFactoryManager to be used for database connections
60          * @return The new instance of JPAUtils or throw exception if the given emf is null.
61          * @throws IllegalStateException if a JPAUtils has already been constructed. Call getJPAUtilsInstance() to get this.
62          */
63         public static JPAUtils getJPAUtilsInstance(EntityManagerFactory emf) throws Exception{
64                 logger.debug("getJPAUtilsInstance(EntityManagerFactory emf) as getJPAUtilsInstance("+emf+") called");
65                 if(currentInstance == null){
66                         if(emf != null){
67                                 currentInstance = new JPAUtils(emf);
68                                 return currentInstance;
69                         }
70                         throw new IllegalStateException("The EntityManagerFactory is Null");
71                 }
72                 return currentInstance;
73         }
74         
75         private JPAUtils(EntityManagerFactory emf){
76                 logger.debug("JPAUtils(EntityManagerFactory emf) as JPAUtils("+emf+") called");
77                 this.emf = emf; 
78         }
79         
80         /**
81          * Gets the current instance of JPAUtils. 
82          * @return The instance of JPAUtils or throws exception if the given instance is null.
83          * @throws IllegalStateException if a JPAUtils instance is null. Call getJPAUtilsInstance(EntityManagerFactory emf) to get this.
84          */
85         public static JPAUtils getJPAUtilsInstance() throws Exception{
86                 logger.debug("getJPAUtilsInstance() as getJPAUtilsInstance() called");
87                 if(currentInstance != null){
88                         return currentInstance;
89                 }
90                 throw new IllegalStateException("The JPAUtils.currentInstance is Null.  Use getJPAUtilsInstance(EntityManagerFactory emf)");
91         }
92         
93         public static AttributeDesignatorType   createDesignator(Attribute attribute) {
94                 AttributeDesignatorType designator = new AttributeDesignatorType();
95                 designator.setAttributeId(attribute.getXacmlId());
96                 if (attribute.getCategoryBean() != null) {
97                         designator.setCategory(attribute.getCategoryBean().getXacmlId());
98                 } else {
99                         logger.warn("No category bean");
100                 }
101                 if (attribute.getDatatypeBean() != null) {
102                         designator.setDataType(attribute.getDatatypeBean().getXacmlId());
103                 } else {
104                         logger.warn("No datatype bean");
105                 }
106                 designator.setIssuer(attribute.getIssuer());
107                 designator.setMustBePresent(attribute.isMustBePresent());
108                 return designator;
109         }
110                 
111         public static AttributeSelectorType     createSelector(Attribute attribute) {
112                 AttributeSelectorType selector = new AttributeSelectorType();
113                 selector.setContextSelectorId(attribute.getXacmlId());
114                 selector.setPath(attribute.getSelectorPath());
115                 if (attribute.getCategoryBean() != null) {
116                         selector.setCategory(attribute.getCategoryBean().getXacmlId());
117                 } else {
118                         logger.warn("No category bean");
119                 }
120                 if (attribute.getDatatypeBean() != null) {
121                         selector.setDataType(attribute.getDatatypeBean().getXacmlId());
122                 } else {
123                         logger.warn("No datatype bean");
124                 }
125                 selector.setMustBePresent(attribute.isMustBePresent());
126                 return selector;
127         }
128         
129         /**
130          * Builds a map in memory of a functions return datatype to function definition. Useful in limiting the number
131          * of SQL calls to DB especially when we don't expect these to change much.
132          * 
133          * @return - A HashMap of Datatype JPA Container ID's to FunctionDefinition objects
134          */
135         public Map<Datatype, List<FunctionDefinition>>  getFunctionDatatypeMap() {              
136                 
137                 synchronized(mapAccess) {
138                         if (mapDatatype2Function == null||mapDatatype2Function.isEmpty()) {
139                                 try {
140                                         buildFunctionMaps();
141                                 } catch (ServletException e) {
142                                         // TODO Auto-generated catch block
143                                         e.printStackTrace();
144                                 }
145                         }
146                 }
147                 return mapDatatype2Function;
148         }
149         
150         public Map<String, FunctionDefinition> getFunctionIDMap() {
151                 synchronized(mapAccess) {
152                         if (mapID2Function == null||mapID2Function.equals("{}")) {
153                                 try {
154                                         buildFunctionMaps();
155                                 } catch (ServletException e) {
156                                         // TODO Auto-generated catch block
157                                         e.printStackTrace();
158                                 }
159                         }
160                 }
161                 return mapID2Function;
162         }
163         
164         private void buildFunctionMaps() throws ServletException {
165                 mapDatatype2Function = new HashMap<Datatype, List<FunctionDefinition>>();
166                 mapID2Function = new HashMap<String, FunctionDefinition>();
167
168                 EntityManager em = emf.createEntityManager();
169                 Query getFunctionDefinitions = em.createNamedQuery("FunctionDefinition.findAll");       
170                 List<?> functionList = getFunctionDefinitions.getResultList();  
171                 
172                 for (Object id : functionList) {
173                         FunctionDefinition value = (FunctionDefinition)id;
174                         mapID2Function.put(value.getXacmlid(), value);
175                         if (mapDatatype2Function.containsKey(value.getDatatypeBean()) == false) {
176                                 mapDatatype2Function.put(value.getDatatypeBean(), new ArrayList<FunctionDefinition>());
177                         }
178                         mapDatatype2Function.get(value.getDatatypeBean()).add(value);
179                 }
180
181                 em.close();
182                 
183         }
184         
185         /**
186          * Returns the lockdown value, in case of exception it is assumed that lockdown functionality
187          * is not supported and returns false.
188          * 
189          * 
190          * @throws ReadOnlyException
191          * @throws ConversionException
192          */
193         public boolean dbLockdownIgnoreErrors() {
194                 if (logger.isTraceEnabled())
195                         logger.trace("ENTER");
196                 
197                 boolean lockdown = false;
198                 try {
199                         lockdown = dbLockdown();
200                 } catch (Exception e) {
201                         logger.warn("Cannot access DB lockdown value", e);
202                 }
203                 return lockdown;
204         }
205         
206         /**
207          * Returns the lockdown value from the database.
208          * 
209          * @throws ReadOnlyException
210          * @throws ConversionException
211          */
212         public boolean dbLockdown() 
213                         throws  IllegalAccessException {
214                 if (logger.isTraceEnabled())
215                         logger.trace("ENTER");
216                 
217                 EntityManager em = emf.createEntityManager();
218                 Query globalRoleSettingsJPA = em.createNamedQuery("GlobalRoleSettings.findAll");        
219                 
220                 GlobalRoleSettings globalRoleSettings = (GlobalRoleSettings) globalRoleSettingsJPA.getSingleResult();
221                 
222                 if (globalRoleSettings == null) {
223                         // this should not happen
224                         String msg = "NO GlobalSetttings for " + XacmlAdminAuthorization.Role.ROLE_SUPERADMIN.toString();
225                         if (logger.isErrorEnabled())
226                                 logger.error(msg);
227                         throw new IllegalAccessException(msg);
228                 }
229                 
230                 if (!globalRoleSettings.getRole().equals(XacmlAdminAuthorization.Role.ROLE_SUPERADMIN.toString())) {
231                         String msg = "NOT FOUND db data for " + XacmlAdminAuthorization.Role.ROLE_SUPERADMIN.toString();
232                         if (logger.isErrorEnabled())
233                                 logger.error(msg);
234                         throw new IllegalAccessException(msg);
235                 }
236                 
237                 return globalRoleSettings.isLockdown();
238         }
239         
240         
241
242 }