CHeckstyle and JUnit for base package in ONAP-REST
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / admin / CheckPdpProperties.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
6  * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
7  * Modifications Copyright (C) 2019 Bell Canada
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.admin;
24
25 import com.att.research.xacml.util.XACMLProperties;
26
27 import java.io.FileInputStream;
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.nio.charset.StandardCharsets;
31 import java.nio.file.Path;
32 import java.nio.file.Paths;
33 import java.util.ArrayList;
34 import java.util.Arrays;
35 import java.util.Base64;
36 import java.util.Collection;
37 import java.util.Collections;
38 import java.util.HashMap;
39 import java.util.List;
40 import java.util.Map;
41 import java.util.Properties;
42
43 import org.onap.policy.common.logging.flexlogger.FlexLogger;
44 import org.onap.policy.common.logging.flexlogger.Logger;
45 import org.onap.policy.rest.XacmlRestProperties;
46 import org.onap.policy.utils.PeCryptoUtils;
47 import org.onap.policy.xacml.api.XACMLErrorConstants;
48
49 /**
50  * What is not good about this class is that once a value has been set for pdpProperties path you cannot change it. That
51  * may be ok for a highly controlled production environment in which nothing changes, but not a very good
52  * implementation.
53  *
54  * <p>The reset() method has been added to assist with the above problem in order to acquire >80% JUnit code coverage.
55  *
56  * <p>This static class doesn't really check a PDP, it simply loads a properties file and tried to ensure
57  * that a valid URL exists for a PDP along with user/password.
58  */
59 public class CheckPdpProperties {
60
61     private static Path pdpPath = null;
62     private static Long oldModified = null;
63     private static HashMap<String, String> pdpMap = null;
64     private static final Logger LOGGER = FlexLogger.getLogger(CheckPdpProperties.class);
65
66     private CheckPdpProperties() {
67         // default constructor
68     }
69
70     public static Map<String, String> getPdpMap() {
71         return pdpMap;
72     }
73
74     private static void reset() {
75         pdpPath = null;
76         oldModified = null;
77         pdpMap = null;
78     }
79
80     /**
81      * validateId - validates that the ID is in the properties.
82      *
83      * @param id Input ID
84      * @return true it is in the properties
85      */
86     public static boolean validateId(String id) {
87         // ReadFile
88         try {
89             readFile();
90         } catch (Exception e) {
91             LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
92             return false;
93         }
94         if (pdpMap == null) {
95             return false;
96         }
97         // Check ID
98         return pdpMap.containsKey(id);
99     }
100
101     private static void readFile() {
102         String pdpFile;
103         try {
104             pdpFile = XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_IDFILE);
105         } catch (Exception e) {
106             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot read the PDP ID File" + e);
107             return;
108         }
109         if (pdpFile == null) {
110             LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PDP File name not Valid : " + pdpFile);
111         } else if (pdpPath == null) {
112             pdpPath = Paths.get(pdpFile);
113             if (!pdpPath.toString().endsWith(".properties") || !pdpPath.toFile().exists()) {
114                 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "File doesn't exist in the specified Path : "
115                         + pdpPath.toString());
116                 CheckPdpProperties.reset();
117                 return;
118             }
119             readProps();
120         } else { // Check if File is updated recently
121             Long newModified = pdpPath.toFile().lastModified();
122             if (!newModified.equals(oldModified)) {
123                 // File has been updated.
124                 readProps();
125             }
126         }
127     }
128
129     @SuppressWarnings({"unchecked", "rawtypes"})
130     private static void readProps() {
131         Properties pdpProp;
132         pdpProp = new Properties();
133         try (InputStream in = new FileInputStream(pdpPath.toFile())) {
134             oldModified = pdpPath.toFile().lastModified();
135             pdpProp.load(in);
136             // Read the Properties and Load the PDPs and encoding.
137             pdpMap = new HashMap<>();
138             // Check the Keys for PDP_URLs
139             Collection<Object> unsorted = pdpProp.keySet();
140             List<String> sorted = new ArrayList(unsorted);
141             Collections.sort(sorted);
142             for (String propKey : sorted) {
143                 loadPdpProperties(propKey, pdpProp);
144             }
145         } catch (IOException e) {
146             LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
147         }
148         if (pdpMap == null || pdpMap.isEmpty()) {
149             LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Proceed without PDP_URLs");
150             CheckPdpProperties.reset();
151         }
152     }
153
154     private static void loadPdpProperties(String propKey, Properties pdpProp) {
155         if (propKey.startsWith("PDP_URL")) {
156             String checkVal = pdpProp.getProperty(propKey);
157             if (checkVal == null) {
158                 LOGGER.error("Properties file doesn't have the PDP_URL parameter");
159             }
160             if (checkVal != null && checkVal.contains(";")) {
161                 List<String> pdpDefault = new ArrayList<>(Arrays.asList(checkVal.split("\\s*;\\s*")));
162                 int pdpCount = 0;
163                 while (pdpCount < pdpDefault.size()) {
164                     String pdpVal = pdpDefault.get(pdpCount);
165                     readPdpParam(pdpVal);
166                     pdpCount++;
167                 }
168             }
169         }
170     }
171
172     private static void readPdpParam(String pdpVal) {
173         if (pdpVal.contains(",")) {
174             List<String> pdpValues = new ArrayList<>(Arrays.asList(pdpVal.split("\\s*,\\s*")));
175             if (pdpValues.size() == 3) {
176                 // 1:2 will be UserID:Password
177                 String userID = pdpValues.get(1);
178                 String pass = PeCryptoUtils.decrypt(pdpValues.get(2));
179                 Base64.Encoder encoder = Base64.getEncoder();
180                 // 0 - PDPURL
181                 pdpMap.put(pdpValues.get(0),
182                         encoder.encodeToString((userID + ":" + pass).getBytes(StandardCharsets.UTF_8)));
183             } else {
184                 LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpValues);
185             }
186         } else {
187             LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpVal);
188         }
189     }
190
191     /**
192      * getEncoding reads in the PDP properties and returns an encoding
193      * for the given pdp.
194      *
195      * @param pdpID Input PDP Id
196      * @return String encoding
197      */
198     public static String getEncoding(String pdpID) {
199         try {
200             readFile();
201         } catch (Exception e) {
202             LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
203         }
204         String encoding = null;
205         if (pdpMap != null && (!pdpMap.isEmpty())) {
206             try {
207                 encoding = pdpMap.get(pdpID);
208             } catch (Exception e) {
209                 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
210             }
211             return encoding;
212         }
213         return null;
214     }
215 }