Adding code coverage reduce duplicate lines
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / admin / CheckPDP.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
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.onap.policy.admin;
22
23
24 import java.io.FileInputStream;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.nio.charset.StandardCharsets;
28 import java.nio.file.Path;
29 import java.nio.file.Paths;
30 import java.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.Base64;
33 import java.util.Collection;
34 import java.util.Collections;
35 import java.util.HashMap;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.Properties;
39
40 import org.onap.policy.common.logging.flexlogger.FlexLogger;
41 import org.onap.policy.common.logging.flexlogger.Logger;
42 import org.onap.policy.rest.XACMLRestProperties;
43 import org.onap.policy.xacml.api.XACMLErrorConstants;
44
45 import com.att.research.xacml.util.XACMLProperties;
46
47 /**
48  * What is not good about this class is that once a value has been set for pdpProperties path
49  * you cannot change it. That may be ok for a highly controlled production environment in which
50  * nothing changes, but not a very good implementation.
51  * 
52  * The reset() method has been added to assist with the above problem in order to 
53  * acquire >80% JUnit code coverage.
54  * 
55  * This static class doesn't really check a PDP, it simply loads a properties file and tried
56  * to ensure that a valid URL exists for a PDP along with user/password.
57  *
58  */
59 public class CheckPDP {
60         private static Path pdpPath = null;
61         private static Long oldModified = null;
62         private static HashMap<String, String> pdpMap = null;
63         private static final Logger LOGGER = FlexLogger.getLogger(CheckPDP.class);
64         
65         private CheckPDP(){
66                 //default constructor
67         }
68         
69         public static Map<String, String> getPdpMap() {
70                 return pdpMap;
71         }
72         
73         private static void reset() {
74                 pdpPath = null;
75                 oldModified = null;
76                 pdpMap = null;
77         }
78
79         public static boolean validateID(String id) {
80                 // ReadFile
81                 try {
82                         readFile();
83                 } catch (Exception e) {
84                         LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
85                         return false;
86                 }
87                 if (pdpMap == null) {
88                         return false;
89                 }
90                 // Check ID
91                 return pdpMap.containsKey(id);
92         }
93
94         private static void readFile(){
95                 String pdpFile = null;
96                 try{
97                         pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE);     
98                 }catch (Exception e){
99                         LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot read the PDP ID File" + e);
100                         return;
101                 }
102                 if (pdpFile == null) {
103                         LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PDP File name not Valid : " + pdpFile);
104                 }
105                 if (pdpPath == null) {
106                         pdpPath = Paths.get(pdpFile);
107                         if (!pdpPath.toString().endsWith(".properties") || !pdpPath.toFile().exists()) {
108                                 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "File doesn't exist in the specified Path : "     + pdpPath.toString());
109                                 CheckPDP.reset();
110                                 return;
111                         }
112                         readProps();
113                 }
114                 // Check if File is updated recently
115                 else {
116                         Long newModified = pdpPath.toFile().lastModified();
117                         if (!newModified.equals(oldModified)) {
118                                 // File has been updated.
119                                 readProps();
120                         }
121                 }
122         }
123
124         @SuppressWarnings({ "unchecked", "rawtypes" })
125         private static void readProps() {
126                 Properties pdpProp;
127                 pdpProp = new Properties();
128                 try {
129                         InputStream in = new FileInputStream(pdpPath.toFile());
130                         oldModified = pdpPath.toFile().lastModified();
131                         pdpProp.load(in);
132                         // Read the Properties and Load the PDPs and encoding.
133                         pdpMap = new HashMap<>();
134                         // Check the Keys for PDP_URLs
135                         Collection<Object> unsorted = pdpProp.keySet();
136                         List<String> sorted = new ArrayList(unsorted);
137                         Collections.sort(sorted);
138                         for (String propKey : sorted) {
139                                 loadPDPProperties(propKey, pdpProp);
140                         }
141                         in.close();
142                 } catch (IOException e) {
143                         LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
144                 }
145                 if (pdpMap == null || pdpMap.isEmpty()) {
146                         LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Proceed without PDP_URLs");
147                         CheckPDP.reset();
148                 }
149         }
150         
151         private static void loadPDPProperties(String propKey, Properties pdpProp){
152                 if (propKey.startsWith("PDP_URL")) {
153                         String checkVal = pdpProp.getProperty(propKey);
154                         if (checkVal == null) {
155                                 LOGGER.error("Properties file doesn't have the PDP_URL parameter");
156                         }
157                         if (checkVal != null && checkVal.contains(";")) {
158                                 List<String> pdpDefault = new ArrayList<>(Arrays.asList(checkVal.split("\\s*;\\s*")));
159                                 int pdpCount = 0;
160                                 while (pdpCount < pdpDefault.size()) {
161                                         String pdpVal = pdpDefault.get(pdpCount);
162                                         readPDPParam(pdpVal);
163                                         pdpCount++;
164                                 }
165                         }
166                 }
167         }
168
169         private static void readPDPParam(String pdpVal){
170                 if(pdpVal.contains(",")){
171                         List<String> pdpValues = new ArrayList<>(Arrays.asList(pdpVal.split("\\s*,\\s*")));
172                         if(pdpValues.size()==3){
173                                 // 1:2 will be UserID:Password
174                                 String userID = pdpValues.get(1);
175                                 String pass = pdpValues.get(2);
176                                 Base64.Encoder encoder = Base64.getEncoder();
177                                 // 0 - PDPURL
178                                 pdpMap.put(pdpValues.get(0), encoder.encodeToString((userID+":"+pass).getBytes(StandardCharsets.UTF_8)));
179                         }else{
180                                 LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpValues);
181                         }
182                 }else{
183                         LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpVal);
184                 }
185         }
186         
187         public static String getEncoding(String pdpID){
188                 try {
189                         readFile();
190                 } catch (Exception e) {
191                         LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
192                 }
193                 String encoding = null;
194                 if(pdpMap!=null && (!pdpMap.isEmpty())){
195                         try{
196                                 encoding = pdpMap.get(pdpID);
197                         } catch(Exception e){
198                                 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
199                         }
200                         return encoding;
201                 }else{
202                         return null;
203                 }
204         }
205 }