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.openecomp.policy.xacml.action;
22 import java.io.BufferedReader;
23 import java.io.IOException;
24 import java.io.InputStreamReader;
26 import java.net.URLConnection;
27 import java.util.ArrayList;
28 import java.util.Collection;
29 import java.util.HashMap;
31 import java.util.regex.Matcher;
32 import java.util.regex.Pattern;
34 import javax.json.Json;
35 import javax.json.JsonReader;
37 import org.apache.http.HttpResponse;
38 import org.apache.http.client.ClientProtocolException;
39 import org.apache.http.client.methods.HttpGet;
40 import org.apache.http.client.methods.HttpPost;
41 import org.apache.http.client.methods.HttpPut;
42 import org.apache.http.entity.StringEntity;
43 import org.apache.http.impl.client.DefaultHttpClient;
44 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
45 import org.openecomp.policy.common.logging.flexlogger.Logger;
46 import org.openecomp.policy.rest.XACMLRestProperties;
48 import com.att.research.xacml.api.Advice;
49 import com.att.research.xacml.api.Attribute;
50 import com.att.research.xacml.api.AttributeAssignment;
51 import com.att.research.xacml.api.AttributeValue;
52 import com.att.research.xacml.api.Identifier;
53 import com.att.research.xacml.api.Obligation;
54 import com.att.research.xacml.api.Request;
55 import com.att.research.xacml.api.RequestAttributes;
56 import com.att.research.xacml.api.Result;
57 import com.att.research.xacml.std.IdentifierImpl;
58 import com.att.research.xacml.std.StdAdvice;
59 import com.att.research.xacml.std.StdAttributeAssignment;
60 import com.att.research.xacml.std.StdAttributeValue;
61 import com.att.research.xacml.std.StdMutableResponse;
62 import com.att.research.xacml.std.StdMutableResult;
63 import com.att.research.xacml.std.StdObligation;
64 import com.att.research.xacml.util.XACMLProperties;
66 @SuppressWarnings("deprecation")
67 public class FindAction {
68 private Logger LOGGER = FlexLogger.getLogger(this.getClass());
69 private Boolean changeIt = false;
70 private String configURL = null;
71 private StdMutableResponse newResponse = new StdMutableResponse();
72 private StdMutableResult addResult = new StdMutableResult();
74 public StdMutableResponse run(StdMutableResponse stdResponse, Request pepRequest) {
76 boolean config = false;
77 boolean decide = false;
78 Collection<RequestAttributes> requestAttributes = pepRequest.getRequestAttributes();
79 for(RequestAttributes requestAttribute : requestAttributes){
80 Collection<Attribute> attributes = requestAttribute.getAttributes();
81 for(Attribute attribute : attributes){
82 if(attribute.getAttributeId().stringValue().equals("urn:oasis:names:tc:xacml:1.0:action:action-id")){
83 for(AttributeValue<?> attributeValue : attribute.getValues()){
84 if(attributeValue.getValue().toString().equalsIgnoreCase("ACCESS")){
87 if(attributeValue.getValue().toString().equalsIgnoreCase("DECIDE")){
92 if(attribute.getAttributeId().stringValue().equals("urn:oasis:names:tc:xacml:1.0:resource:resource-id")){
93 for(AttributeValue<?> attributeValue : attribute.getValues()){
94 if(attributeValue.getValue().toString().equalsIgnoreCase("Config")){
107 addResults(stdResponse, config , decide);
108 LOGGER.info("Original Result is " + stdResponse.toString());
109 LOGGER.info("Generated Result is " + addResult.toString());
113 private Collection<Obligation> obligations = new ArrayList<Obligation>();
114 private Map<String, String> matchValues = new HashMap<String, String>();
115 private Map<String, String> headers = new HashMap<String, String>();
116 private boolean header = false;
118 private void search(StdMutableResponse stdResponse) {
119 for (Result result : stdResponse.getResults()) {
120 if (!result.getObligations().isEmpty()) {
121 System.out.println("Obligation Received");
122 // Is there any action that PDP needs to take
123 for (Obligation obligation : result.getObligations()) {
124 int count = 0, uri = 0, PEP = 0;
127 Collection<AttributeAssignment> afterRemoveAssignments = new ArrayList<AttributeAssignment>();
128 Identifier oblId = new IdentifierImpl(obligation.getId().stringValue());
129 StdAttributeAssignment attributeURI = null;
130 for (AttributeAssignment attribute : obligation.getAttributeAssignments()) {
131 matchValues.put(attribute.getAttributeId().stringValue(), attribute.getAttributeValue().getValue().toString());
132 if (attribute.getAttributeId().stringValue().equalsIgnoreCase("performer")) {
133 if (attribute.getAttributeValue().getValue().toString().equalsIgnoreCase("PEPACTION")) {
135 } else if (attribute.getAttributeValue().getValue().toString().equalsIgnoreCase("PDPACTION")) {
138 } else if (attribute.getAttributeId().stringValue().equalsIgnoreCase("URL")) {
141 configURL = attribute.getAttributeValue().getValue().toString();
142 attributeURI = new StdAttributeAssignment(attribute);
144 } else if (attribute.getAttributeId().stringValue().startsWith("headers")) {
145 LOGGER.info("Headers are : "+ attribute.getAttributeValue().getValue().toString());
147 headers.put(attribute.getAttributeId().stringValue().replaceFirst("(headers).", ""),
148 attribute.getAttributeValue().getValue().toString());
149 afterRemoveAssignments.add(attribute);
150 } else if (attribute.getAttributeId().stringValue().equalsIgnoreCase("body")) {
151 String papPath = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
152 papPath= papPath.replace("/pap", "");
153 matchValues.put("body",attribute.getAttributeValue().getValue().toString().replace("$URL", papPath));
155 * else if (attribute.getAttributeId().stringValue().
156 * equalsIgnoreCase("type")){ requestAction.put("Type",
157 * attribute.getAttributeValue().getValue().toString());
158 * afterRemoveAssignments.add(attribute); } else
160 * .getAttributeId().stringValue().equalsIgnoreCase
161 * ("method")) { requestAction.put("Method",
162 * attribute.getAttributeValue().getValue().toString());
163 * afterRemoveAssignments.add(attribute); } else
165 * .getAttributeId().stringValue().equalsIgnoreCase
166 * ("body")) { requestAction.put("Body",
167 * attribute.getAttributeValue().getValue().toString());
168 * afterRemoveAssignments.add(attribute); }
170 StdAttributeAssignment attributeObligation = new StdAttributeAssignment(attribute);
171 afterRemoveAssignments.add(attributeObligation);
174 if (count == 1 && uri == 1 && PEP == 0) {
175 // Remove Obligation and add Advice
177 TakeAction(stdResponse, oblId, afterRemoveAssignments);
178 } else if (PEP == 1 && count == 0) {
179 // Strip the PEPACTION if available
181 afterRemoveAssignments.add(attributeURI);
183 Obligation afterRemoveObligation = new StdObligation(
184 oblId, afterRemoveAssignments);
185 obligations.add(afterRemoveObligation);
187 obligations.add(obligation);
194 private void TakeAction(StdMutableResponse stdResponse, Identifier advId,
195 Collection<AttributeAssignment> afterRemoveAssignments) {
197 LOGGER.info("the URL is :" + configURL);
198 // Calling Rest URL..
200 // Including the Results in an Advice
201 Identifier id = new IdentifierImpl(
202 "com:att:labs:ecomp:policy:pdp:reply");
203 Identifier statId = new IdentifierImpl(
204 "com:att:labs:ecomp:policy:pdp:reply:status");
205 Identifier statCategory = new IdentifierImpl(
206 "urn:oasis:names:tc:xacml:1.0:subject-category:recipient-subject");
207 Identifier strId = new IdentifierImpl(
208 "http://www.w3.org/2001/XMLSchema#string");
209 Identifier resId = new IdentifierImpl(
210 "com:att:labs:ecomp:policy:pdp:reply:resource");
211 Identifier resCategory = new IdentifierImpl(
212 "urn:oasis:names:tc:xacml:3.0:attribute-category:resource");
213 Identifier urlId = new IdentifierImpl(
214 "http://www.w3.org/2001/XMLSchema#anyURI");
215 // Collection<AttributeAssignment> attributes = new
216 // ArrayList<AttributeAssignment>();
217 AttributeValue<String> attributeStatusValue = new StdAttributeValue<String>(
218 strId, status + response);
219 AttributeValue<String> attributeResourceValue = new StdAttributeValue<String>(
221 StdAttributeAssignment attributeStatus = new StdAttributeAssignment(
222 statCategory, statId, "PDP", attributeStatusValue);
223 StdAttributeAssignment attributeResouce = new StdAttributeAssignment(
224 resCategory, resId, "PDP", attributeResourceValue);
225 afterRemoveAssignments.add(attributeStatus);
226 afterRemoveAssignments.add(attributeResouce);
227 Advice advice = new StdAdvice(id, afterRemoveAssignments);
228 addResult.addAdvice(advice);
232 private void addResults(StdMutableResponse stdResponse, boolean config, boolean decide) {
234 newResponse = stdResponse;
237 for (Result result : stdResponse.getResults()) {
239 addResult.addAdvice(result.getAssociatedAdvice());
241 addResult.addAttributeCategories(result.getAttributes());
242 addResult.addPolicyIdentifiers(result.getPolicyIdentifiers());
243 addResult.addPolicySetIdentifiers(result.getPolicySetIdentifiers());
244 addResult.setStatus(result.getStatus());
245 addResult.setDecision(result.getDecision());
247 addResult.addObligations(obligations);
250 newResponse.add(addResult);
254 private String response;
255 private DefaultHttpClient httpClient;
257 private void callRest() {
258 // Finding the Macros in the URL..
259 Pattern pattern = Pattern.compile("\\$([a-zA-Z0-9.:]*)");
260 Matcher match = pattern.matcher(configURL);
261 StringBuffer sb = new StringBuffer();
262 while (match.find()) {
263 LOGGER.info("Found Macro : " + match.group(1));
264 String replaceValue = matchValues.get(match.group(1));
265 LOGGER.info("Replacing with :" + replaceValue);
266 match.appendReplacement(sb, replaceValue);
268 match.appendTail(sb);
269 LOGGER.info("URL is : " + sb.toString());
270 configURL = sb.toString();
271 // Calling the Requested service.
272 if (matchValues.get("method").equalsIgnoreCase("GET")) {
273 httpClient = new DefaultHttpClient();
275 HttpGet getRequest = new HttpGet(configURL);
276 // Adding Headers here
278 for (String key : headers.keySet()) {
279 getRequest.addHeader(key, headers.get(key));
282 HttpResponse result = httpClient.execute(getRequest);
283 status = result.getStatusLine().getStatusCode();
284 BufferedReader br = new BufferedReader(new InputStreamReader(
285 (result.getEntity().getContent())));
288 while ((out = br.readLine()) != null) {
289 output = output + out;
292 } catch (ClientProtocolException e) {
293 LOGGER.error(e.getMessage());
294 response = e.getMessage();
295 } catch (IOException e) {
296 LOGGER.error(e.getMessage());
297 response = e.getMessage();
299 httpClient.getConnectionManager().shutdown();
301 } else if(matchValues.get("method").equalsIgnoreCase("POST")) {
302 httpClient = new DefaultHttpClient();
304 HttpPost postRequest = new HttpPost(configURL);
305 // Adding Headers here
307 for (String key : headers.keySet()) {
308 postRequest.addHeader(key, headers.get(key));
312 URL configURL = new URL(matchValues.get("body"));
313 URLConnection connection = null;
314 connection = configURL.openConnection();
315 // InputStream in = connection.getInputStrem();
316 // LOGGER.info("The Body Content is : " + IOUtils.toString(in));
317 JsonReader jsonReader = Json.createReader(connection.getInputStream());
318 StringEntity input = new StringEntity(jsonReader.readObject().toString());
319 input.setContentType("application/json");
320 postRequest.setEntity(input);
321 // Executing the Request.
322 HttpResponse result = httpClient.execute(postRequest);
323 LOGGER.info("Result Headers are : " + result.getAllHeaders());
324 status = result.getStatusLine().getStatusCode();
325 BufferedReader br = new BufferedReader(new InputStreamReader(
326 (result.getEntity().getContent())));
329 while ((out = br.readLine()) != null) {
330 output = output + out;
333 } catch (ClientProtocolException e) {
334 LOGGER.error(e.getMessage());
335 response = e.getMessage();
336 } catch (IOException e) {
337 LOGGER.error(e.getMessage());
338 response = e.getMessage();
340 httpClient.getConnectionManager().shutdown();
342 } else if(matchValues.get("method").equalsIgnoreCase("PUT")) {
343 httpClient = new DefaultHttpClient();
345 HttpPut putRequest = new HttpPut(configURL);
346 // Adding Headers here
348 for (String key : headers.keySet()) {
349 putRequest.addHeader(key, headers.get(key));
353 URL configURL = new URL(matchValues.get("body"));
354 URLConnection connection = null;
355 connection = configURL.openConnection();
356 //InputStream in = connection.getInputStream();
357 //LOGGER.info("The Body Content is : " + IOUtils.toString(in));
358 JsonReader jsonReader = Json.createReader(connection.getInputStream());
359 StringEntity input = new StringEntity(jsonReader.readObject().toString());
360 input.setContentType("application/json");
361 putRequest.setEntity(input);
362 // Executing the Request.
363 HttpResponse result = httpClient.execute(putRequest);
364 status = result.getStatusLine().getStatusCode();
365 BufferedReader br = new BufferedReader(new InputStreamReader(
366 (result.getEntity().getContent())));
369 while ((out = br.readLine()) != null) {
370 output = output + out;
373 } catch (ClientProtocolException e) {
374 LOGGER.error(e.getMessage());
375 response = e.getMessage();
376 } catch (IOException e) {
377 LOGGER.error(e.getMessage());
378 response = e.getMessage();
380 httpClient.getConnectionManager().shutdown();