2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
20 package org.onap.policy.xacml.action;
22 import java.io.BufferedReader;
23 import java.io.InputStreamReader;
25 import java.net.URLConnection;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.HashMap;
30 import java.util.regex.Matcher;
31 import java.util.regex.Pattern;
33 import javax.json.Json;
34 import javax.json.JsonReader;
36 import org.apache.http.HttpResponse;
37 import org.apache.http.client.methods.HttpGet;
38 import org.apache.http.client.methods.HttpPost;
39 import org.apache.http.client.methods.HttpPut;
40 import org.apache.http.entity.StringEntity;
41 import org.apache.http.impl.client.DefaultHttpClient;
42 import org.onap.policy.common.logging.flexlogger.FlexLogger;
43 import org.onap.policy.common.logging.flexlogger.Logger;
44 import org.onap.policy.rest.XACMLRestProperties;
46 import com.att.research.xacml.api.Advice;
47 import com.att.research.xacml.api.Attribute;
48 import com.att.research.xacml.api.AttributeAssignment;
49 import com.att.research.xacml.api.AttributeValue;
50 import com.att.research.xacml.api.Identifier;
51 import com.att.research.xacml.api.Obligation;
52 import com.att.research.xacml.api.Request;
53 import com.att.research.xacml.api.RequestAttributes;
54 import com.att.research.xacml.api.Result;
55 import com.att.research.xacml.std.IdentifierImpl;
56 import com.att.research.xacml.std.StdAdvice;
57 import com.att.research.xacml.std.StdAttributeAssignment;
58 import com.att.research.xacml.std.StdAttributeValue;
59 import com.att.research.xacml.std.StdMutableResponse;
60 import com.att.research.xacml.std.StdMutableResult;
61 import com.att.research.xacml.std.StdObligation;
62 import com.att.research.xacml.util.XACMLProperties;
64 @SuppressWarnings("deprecation")
65 public class FindAction {
66 private Logger LOGGER = FlexLogger.getLogger(this.getClass());
67 private Boolean changeIt = false;
68 private String configURL = null;
69 private StdMutableResponse newResponse = new StdMutableResponse();
70 private StdMutableResult addResult = new StdMutableResult();
72 public StdMutableResponse run(StdMutableResponse stdResponse, Request pepRequest) {
74 boolean config = false;
75 boolean decide = false;
76 Collection<RequestAttributes> requestAttributes = pepRequest.getRequestAttributes();
77 for(RequestAttributes requestAttribute : requestAttributes){
78 Collection<Attribute> attributes = requestAttribute.getAttributes();
79 for(Attribute attribute : attributes){
80 if(attribute.getAttributeId().stringValue().equals("urn:oasis:names:tc:xacml:1.0:action:action-id")){
81 for(AttributeValue<?> attributeValue : attribute.getValues()){
82 if(attributeValue.getValue().toString().equalsIgnoreCase("ACCESS")){
85 if(attributeValue.getValue().toString().equalsIgnoreCase("DECIDE")){
90 if(attribute.getAttributeId().stringValue().equals("urn:oasis:names:tc:xacml:1.0:resource:resource-id")){
91 for(AttributeValue<?> attributeValue : attribute.getValues()){
92 if(attributeValue.getValue().toString().equalsIgnoreCase("Config")){
105 addResults(stdResponse, config , decide);
106 LOGGER.info("Original Result is " + stdResponse.toString());
107 LOGGER.info("Generated Result is " + addResult.toString());
111 private Collection<Obligation> obligations = new ArrayList<>();
112 private Map<String, String> matchValues = new HashMap<>();
113 private Map<String, String> headers = new HashMap<>();
114 private boolean header = false;
116 private void search(StdMutableResponse stdResponse) {
117 for (Result result : stdResponse.getResults()) {
118 if (!result.getObligations().isEmpty()) {
119 System.out.println("Obligation Received");
120 // Is there any action that PDP needs to take
121 for (Obligation obligation : result.getObligations()) {
122 int count = 0, uri = 0, PEP = 0;
125 Collection<AttributeAssignment> afterRemoveAssignments = new ArrayList<>();
126 Identifier oblId = new IdentifierImpl(obligation.getId().stringValue());
127 StdAttributeAssignment attributeURI = null;
128 for (AttributeAssignment attribute : obligation.getAttributeAssignments()) {
129 matchValues.put(attribute.getAttributeId().stringValue(), attribute.getAttributeValue().getValue().toString());
130 if (attribute.getAttributeId().stringValue().equalsIgnoreCase("performer")) {
131 if (attribute.getAttributeValue().getValue().toString().equalsIgnoreCase("PEPACTION")) {
133 } else if (attribute.getAttributeValue().getValue().toString().equalsIgnoreCase("PDPACTION")) {
136 } else if (attribute.getAttributeId().stringValue().equalsIgnoreCase("URL")) {
139 configURL = attribute.getAttributeValue().getValue().toString();
140 attributeURI = new StdAttributeAssignment(attribute);
142 } else if (attribute.getAttributeId().stringValue().startsWith("headers")) {
143 LOGGER.info("Headers are : "+ attribute.getAttributeValue().getValue().toString());
145 headers.put(attribute.getAttributeId().stringValue().replaceFirst("(headers).", ""),
146 attribute.getAttributeValue().getValue().toString());
147 afterRemoveAssignments.add(attribute);
148 } else if (attribute.getAttributeId().stringValue().equalsIgnoreCase("body")) {
149 String papPath = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
150 papPath= papPath.replace("/pap", "");
151 matchValues.put("body",attribute.getAttributeValue().getValue().toString().replace("$URL", papPath));
153 StdAttributeAssignment attributeObligation = new StdAttributeAssignment(attribute);
154 afterRemoveAssignments.add(attributeObligation);
157 if (count == 1 && uri == 1 && PEP == 0) {
158 // Remove Obligation and add Advice
160 takeAction(stdResponse, oblId, afterRemoveAssignments);
161 } else if (PEP == 1 && count == 0) {
162 // Strip the PEPACTION if available
164 afterRemoveAssignments.add(attributeURI);
166 Obligation afterRemoveObligation = new StdObligation(
167 oblId, afterRemoveAssignments);
168 obligations.add(afterRemoveObligation);
170 obligations.add(obligation);
177 private void takeAction(StdMutableResponse stdResponse, Identifier advId,
178 Collection<AttributeAssignment> afterRemoveAssignments) {
180 LOGGER.info("the URL is :" + configURL);
181 // Calling Rest URL..
183 // Including the Results in an Advice
184 Identifier id = new IdentifierImpl(
185 "org.onap.policy:pdp:reply");
186 Identifier statId = new IdentifierImpl(
187 "org:onap:onap:policy:pdp:reply:status");
188 Identifier statCategory = new IdentifierImpl(
189 "urn:oasis:names:tc:xacml:1.0:subject-category:recipient-subject");
190 Identifier strId = new IdentifierImpl(
191 "http://www.w3.org/2001/XMLSchema#string");
192 Identifier resId = new IdentifierImpl(
193 "org:onap:onap:policy:pdp:reply:resource");
194 Identifier resCategory = new IdentifierImpl(
195 "urn:oasis:names:tc:xacml:3.0:attribute-category:resource");
196 Identifier urlId = new IdentifierImpl(
197 "http://www.w3.org/2001/XMLSchema#anyURI");
198 AttributeValue<String> attributeStatusValue = new StdAttributeValue<>(
199 strId, status + response);
200 AttributeValue<String> attributeResourceValue = new StdAttributeValue<>(
202 StdAttributeAssignment attributeStatus = new StdAttributeAssignment(
203 statCategory, statId, "PDP", attributeStatusValue);
204 StdAttributeAssignment attributeResouce = new StdAttributeAssignment(
205 resCategory, resId, "PDP", attributeResourceValue);
206 afterRemoveAssignments.add(attributeStatus);
207 afterRemoveAssignments.add(attributeResouce);
208 Advice advice = new StdAdvice(id, afterRemoveAssignments);
209 addResult.addAdvice(advice);
213 private void addResults(StdMutableResponse stdResponse, boolean config, boolean decide) {
215 newResponse = stdResponse;
218 for (Result result : stdResponse.getResults()) {
220 addResult.addAdvice(result.getAssociatedAdvice());
222 addResult.addAttributeCategories(result.getAttributes());
223 addResult.addPolicyIdentifiers(result.getPolicyIdentifiers());
224 addResult.addPolicySetIdentifiers(result.getPolicySetIdentifiers());
225 addResult.setStatus(result.getStatus());
226 addResult.setDecision(result.getDecision());
228 addResult.addObligations(obligations);
231 newResponse.add(addResult);
235 private String response;
236 private DefaultHttpClient httpClient;
238 private void callRest() {
239 // Finding the Macros in the URL..
240 Pattern pattern = Pattern.compile("\\$([a-zA-Z0-9.:]*)");
241 Matcher match = pattern.matcher(configURL);
242 StringBuffer sb = new StringBuffer();
243 JsonReader jsonReader = null;
244 while (match.find()) {
245 LOGGER.info("Found Macro : " + match.group(1));
246 String replaceValue = matchValues.get(match.group(1));
247 LOGGER.info("Replacing with :" + replaceValue);
248 match.appendReplacement(sb, replaceValue);
250 match.appendTail(sb);
251 LOGGER.info("URL is : " + sb.toString());
252 configURL = sb.toString();
253 // Calling the Requested service.
254 if (matchValues.get("method").equalsIgnoreCase("GET")) {
255 httpClient = new DefaultHttpClient();
257 HttpGet getRequest = new HttpGet(configURL);
258 // Adding Headers here
260 for (String key : headers.keySet()) {
261 getRequest.addHeader(key, headers.get(key));
264 HttpResponse result = httpClient.execute(getRequest);
265 status = result.getStatusLine().getStatusCode();
266 BufferedReader br = new BufferedReader(new InputStreamReader(
267 (result.getEntity().getContent())));
270 while ((out = br.readLine()) != null) {
271 output = output + out;
274 } catch (Exception e) {
275 LOGGER.error(e.getMessage()+e);
276 response = e.getMessage();
278 httpClient.getConnectionManager().shutdown();
280 } else if(matchValues.get("method").equalsIgnoreCase("POST")) {
281 httpClient = new DefaultHttpClient();
283 HttpPost postRequest = new HttpPost(configURL);
284 // Adding Headers here
286 for (String key : headers.keySet()) {
287 postRequest.addHeader(key, headers.get(key));
291 URL configURL = new URL(matchValues.get("body"));
292 URLConnection connection = null;
293 connection = configURL.openConnection();
294 // InputStream in = connection.getInputStrem();
295 // LOGGER.info("The Body Content is : " + IOUtils.toString(in));
296 jsonReader = Json.createReader(connection.getInputStream());
297 StringEntity input = new StringEntity(jsonReader.readObject().toString());
298 input.setContentType("application/json");
299 postRequest.setEntity(input);
300 // Executing the Request.
301 HttpResponse result = httpClient.execute(postRequest);
302 LOGGER.info("Result Headers are : " + result.getAllHeaders());
303 status = result.getStatusLine().getStatusCode();
304 BufferedReader br = new BufferedReader(new InputStreamReader(
305 (result.getEntity().getContent())));
308 while ((out = br.readLine()) != null) {
309 output = output + out;
312 }catch (Exception e) {
313 LOGGER.error(e.getMessage() +e);
314 response = e.getMessage();
316 if(jsonReader != null) {
319 } catch (Exception e) {
320 LOGGER.error("Exception Occured while closing the JsonReader"+e);
323 httpClient.getConnectionManager().shutdown();
325 } else if(matchValues.get("method").equalsIgnoreCase("PUT")) {
326 httpClient = new DefaultHttpClient();
328 HttpPut putRequest = new HttpPut(configURL);
329 // Adding Headers here
331 for (String key : headers.keySet()) {
332 putRequest.addHeader(key, headers.get(key));
336 URL configURL = new URL(matchValues.get("body"));
337 URLConnection connection = null;
338 connection = configURL.openConnection();
339 //InputStream in = connection.getInputStream();
340 //LOGGER.info("The Body Content is : " + IOUtils.toString(in));
341 jsonReader = Json.createReader(connection.getInputStream());
342 StringEntity input = new StringEntity(jsonReader.readObject().toString());
343 input.setContentType("application/json");
344 putRequest.setEntity(input);
345 // Executing the Request.
346 HttpResponse result = httpClient.execute(putRequest);
347 status = result.getStatusLine().getStatusCode();
348 BufferedReader br = new BufferedReader(new InputStreamReader(
349 (result.getEntity().getContent())));
352 while ((out = br.readLine()) != null) {
353 output = output + out;
356 } catch (Exception e) {
357 LOGGER.error(e.getMessage() +e);
358 response = e.getMessage();
360 if(jsonReader != null) {
363 } catch (Exception e) {
364 LOGGER.error("Exception Occured while closing the JsonReader"+e);
367 httpClient.getConnectionManager().shutdown();