aboutsummaryrefslogtreecommitdiffstats
path: root/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/util/JPAUtils.java
blob: 5326cb2c7262b44f9ed016b2c883ad798be04319 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
/*-
 * ============LICENSE_START=======================================================
 * ECOMP-PAP-REST
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.openecomp.policy.pap.xacml.rest.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.servlet.ServletException;

import org.openecomp.policy.rest.XacmlAdminAuthorization;
import org.openecomp.policy.rest.jpa.Attribute;
import org.openecomp.policy.rest.jpa.Datatype;
import org.openecomp.policy.rest.jpa.FunctionDefinition;
import org.openecomp.policy.rest.jpa.GlobalRoleSettings;

import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeSelectorType;

import org.openecomp.policy.common.logging.flexlogger.FlexLogger; 
import org.openecomp.policy.common.logging.flexlogger.Logger;

public class JPAUtils {
	private static Logger logger	= FlexLogger.getLogger(JPAUtils.class);
	
	private EntityManagerFactory emf;
	private static final Object mapAccess = new Object();
	private static Map<Datatype, List<FunctionDefinition>> mapDatatype2Function = null;
	private static Map<String, FunctionDefinition> mapID2Function = null;
	private static JPAUtils currentInstance = null;
	
	//private static List<LockdownListener> lockdownListeners = new ArrayList<LockdownListener>();
	
	/**
	 * Get an instance of a JPAUtils. It creates one if it does not exist.
	 * Only one instance is allowed to be created per server.
	 * @param emf The EntityFactoryManager to be used for database connections
	 * @return The new instance of JPAUtils or throw exception if the given emf is null.
	 * @throws IllegalStateException if a JPAUtils has already been constructed. Call getJPAUtilsInstance() to get this.
	 */
	public static JPAUtils getJPAUtilsInstance(EntityManagerFactory emf) throws Exception{
		logger.debug("getJPAUtilsInstance(EntityManagerFactory emf) as getJPAUtilsInstance("+emf+") called");
		if(currentInstance == null){
			if(emf != null){
				currentInstance = new JPAUtils(emf);
				return currentInstance;
			}
			throw new IllegalStateException("The EntityManagerFactory is Null");
		}
		return currentInstance;
	}
	
	private JPAUtils(EntityManagerFactory emf){
		logger.debug("JPAUtils(EntityManagerFactory emf) as JPAUtils("+emf+") called");
		this.emf = emf;	
	}
	
	/**
	 * Gets the current instance of JPAUtils. 
	 * @return The instance of JPAUtils or throws exception if the given instance is null.
	 * @throws IllegalStateException if a JPAUtils instance is null. Call getJPAUtilsInstance(EntityManagerFactory emf) to get this.
	 */
	public static JPAUtils getJPAUtilsInstance() throws Exception{
		logger.debug("getJPAUtilsInstance() as getJPAUtilsInstance() called");
		if(currentInstance != null){
			return currentInstance;
		}
		throw new IllegalStateException("The JPAUtils.currentInstance is Null.  Use getJPAUtilsInstance(EntityManagerFactory emf)");
	}
	
	public static AttributeDesignatorType	createDesignator(Attribute attribute) {
		AttributeDesignatorType designator = new AttributeDesignatorType();
		designator.setAttributeId(attribute.getXacmlId());
		if (attribute.getCategoryBean() != null) {
			designator.setCategory(attribute.getCategoryBean().getXacmlId());
		} else {
			logger.warn("No category bean");
		}
		if (attribute.getDatatypeBean() != null) {
			designator.setDataType(attribute.getDatatypeBean().getXacmlId());
		} else {
			logger.warn("No datatype bean");
		}
		designator.setIssuer(attribute.getIssuer());
		designator.setMustBePresent(attribute.isMustBePresent());
		return designator;
	}
		
	public static AttributeSelectorType	createSelector(Attribute attribute) {
		AttributeSelectorType selector = new AttributeSelectorType();
		selector.setContextSelectorId(attribute.getXacmlId());
		selector.setPath(attribute.getSelectorPath());
		if (attribute.getCategoryBean() != null) {
			selector.setCategory(attribute.getCategoryBean().getXacmlId());
		} else {
			logger.warn("No category bean");
		}
		if (attribute.getDatatypeBean() != null) {
			selector.setDataType(attribute.getDatatypeBean().getXacmlId());
		} else {
			logger.warn("No datatype bean");
		}
		selector.setMustBePresent(attribute.isMustBePresent());
		return selector;
	}
	
	/**
	 * Builds a map in memory of a functions return datatype to function definition. Useful in limiting the number
	 * of SQL calls to DB especially when we don't expect these to change much.
	 * 
	 * @return - A HashMap of Datatype JPA Container ID's to FunctionDefinition objects
	 */
	public Map<Datatype, List<FunctionDefinition>>	getFunctionDatatypeMap() {		
		
		synchronized(mapAccess) {
			if (mapDatatype2Function == null||mapDatatype2Function.isEmpty()) {
				try {
					buildFunctionMaps();
				} catch (ServletException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return mapDatatype2Function;
	}
	
	public Map<String, FunctionDefinition> getFunctionIDMap() {
		synchronized(mapAccess) {
			if (mapID2Function == null||mapID2Function.equals("{}")) {
				try {
					buildFunctionMaps();
				} catch (ServletException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return mapID2Function;
	}
	
	private void buildFunctionMaps() throws ServletException {
		mapDatatype2Function = new HashMap<Datatype, List<FunctionDefinition>>();
		mapID2Function = new HashMap<String, FunctionDefinition>();

		EntityManager em = emf.createEntityManager();
		Query getFunctionDefinitions = em.createNamedQuery("FunctionDefinition.findAll");	
		List<?> functionList = getFunctionDefinitions.getResultList(); 	
		
		for (Object id : functionList) {
			FunctionDefinition value = (FunctionDefinition)id;
			mapID2Function.put(value.getXacmlid(), value);
			if (mapDatatype2Function.containsKey(value.getDatatypeBean()) == false) {
				mapDatatype2Function.put(value.getDatatypeBean(), new ArrayList<FunctionDefinition>());
			}
			mapDatatype2Function.get(value.getDatatypeBean()).add(value);
		}

		em.close();
		
	}
	
	/**
	 * Returns the lockdown value, in case of exception it is assumed that lockdown functionality
	 * is not supported and returns false.
	 * 
	 * 
	 * @throws ReadOnlyException
	 * @throws ConversionException
	 */
	public boolean dbLockdownIgnoreErrors() {
		if (logger.isTraceEnabled())
			logger.trace("ENTER");
		
		boolean lockdown = false;
		try {
			lockdown = dbLockdown();
		} catch (Exception e) {
			logger.warn("Cannot access DB lockdown value", e);
		}
		return lockdown;
	}
	
	/**
	 * Returns the lockdown value from the database.
	 * 
	 * @throws ReadOnlyException
	 * @throws ConversionException
	 */
	public boolean dbLockdown() 
			throws  IllegalAccessException {
		if (logger.isTraceEnabled())
			logger.trace("ENTER");
		
		EntityManager em = emf.createEntityManager();
		Query globalRoleSettingsJPA = em.createNamedQuery("GlobalRoleSettings.findAll");	
		
		GlobalRoleSettings globalRoleSettings = (GlobalRoleSettings) globalRoleSettingsJPA.getSingleResult();
		
		if (globalRoleSettings == null) {
			// this should not happen
			String msg = "NO GlobalSetttings for " + XacmlAdminAuthorization.Role.ROLE_SUPERADMIN.toString();
			if (logger.isErrorEnabled())
				logger.error(msg);
			throw new IllegalAccessException(msg);
		}
		
		if (!globalRoleSettings.getRole().equals(XacmlAdminAuthorization.Role.ROLE_SUPERADMIN.toString())) {
			String msg = "NOT FOUND db data for " + XacmlAdminAuthorization.Role.ROLE_SUPERADMIN.toString();
			if (logger.isErrorEnabled())
				logger.error(msg);
			throw new IllegalAccessException(msg);
		}
		
		return globalRoleSettings.isLockdown();
	}
	
	

}