diff options
Diffstat (limited to 'ONAP-PDP/src')
15 files changed, 970 insertions, 973 deletions
diff --git a/ONAP-PDP/src/main/java/org/onap/policy/xacml/action/FindAction.java b/ONAP-PDP/src/main/java/org/onap/policy/xacml/action/FindAction.java index 5fde0adf3..c256626e6 100644 --- a/ONAP-PDP/src/main/java/org/onap/policy/xacml/action/FindAction.java +++ b/ONAP-PDP/src/main/java/org/onap/policy/xacml/action/FindAction.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PDP * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -17,8 +17,27 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.xacml.action; +import com.att.research.xacml.api.Advice; +import com.att.research.xacml.api.Attribute; +import com.att.research.xacml.api.AttributeAssignment; +import com.att.research.xacml.api.AttributeValue; +import com.att.research.xacml.api.Identifier; +import com.att.research.xacml.api.Obligation; +import com.att.research.xacml.api.Request; +import com.att.research.xacml.api.RequestAttributes; +import com.att.research.xacml.api.Result; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacml.std.StdAdvice; +import com.att.research.xacml.std.StdAttributeAssignment; +import com.att.research.xacml.std.StdAttributeValue; +import com.att.research.xacml.std.StdMutableResponse; +import com.att.research.xacml.std.StdMutableResult; +import com.att.research.xacml.std.StdObligation; +import com.att.research.xacml.util.XACMLProperties; + import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; @@ -43,329 +62,313 @@ import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.rest.XACMLRestProperties; -import com.att.research.xacml.api.Advice; -import com.att.research.xacml.api.Attribute; -import com.att.research.xacml.api.AttributeAssignment; -import com.att.research.xacml.api.AttributeValue; -import com.att.research.xacml.api.Identifier; -import com.att.research.xacml.api.Obligation; -import com.att.research.xacml.api.Request; -import com.att.research.xacml.api.RequestAttributes; -import com.att.research.xacml.api.Result; -import com.att.research.xacml.std.IdentifierImpl; -import com.att.research.xacml.std.StdAdvice; -import com.att.research.xacml.std.StdAttributeAssignment; -import com.att.research.xacml.std.StdAttributeValue; -import com.att.research.xacml.std.StdMutableResponse; -import com.att.research.xacml.std.StdMutableResult; -import com.att.research.xacml.std.StdObligation; -import com.att.research.xacml.util.XACMLProperties; - @SuppressWarnings("deprecation") public class FindAction { - private Logger LOGGER = FlexLogger.getLogger(this.getClass()); - private Boolean changeIt = false; - private String configURL = null; - private StdMutableResponse newResponse = new StdMutableResponse(); - private StdMutableResult addResult = new StdMutableResult(); + private Logger logger = FlexLogger.getLogger(this.getClass()); + private Boolean changeIt = false; + private String configUrl = null; + private StdMutableResponse newResponse = new StdMutableResponse(); + private StdMutableResult addResult = new StdMutableResult(); - public StdMutableResponse run(StdMutableResponse stdResponse, Request pepRequest) { - int count = 0; - boolean config = false; - boolean decide = false; - Collection<RequestAttributes> requestAttributes = pepRequest.getRequestAttributes(); - for(RequestAttributes requestAttribute : requestAttributes){ - Collection<Attribute> attributes = requestAttribute.getAttributes(); - for(Attribute attribute : attributes){ - if(attribute.getAttributeId().stringValue().equals("urn:oasis:names:tc:xacml:1.0:action:action-id")){ - for(AttributeValue<?> attributeValue : attribute.getValues()){ - if(attributeValue.getValue().toString().equalsIgnoreCase("ACCESS")){ - count++; - } - if(attributeValue.getValue().toString().equalsIgnoreCase("DECIDE")){ - decide = true; - } - } - } - if(attribute.getAttributeId().stringValue().equals("urn:oasis:names:tc:xacml:1.0:resource:resource-id")){ - for(AttributeValue<?> attributeValue : attribute.getValues()){ - if(attributeValue.getValue().toString().equalsIgnoreCase("Config")){ - count++; - } - } - } - } - } - if(count==2){ - config = true; - } - if(!config){ - search(stdResponse); - } - addResults(stdResponse, config , decide); - LOGGER.info("Original Result is " + stdResponse.toString()); - LOGGER.info("Generated Result is " + addResult.toString()); - return newResponse; - } + /** + * Generate {@link StdMutableResponse} based on input request. + * + * @param stdResponse the response + * @param pepRequest the request + * @return {@link StdMutableResponse} + */ + public StdMutableResponse run(final StdMutableResponse stdResponse, final Request pepRequest) { + int count = 0; + boolean config = false; + boolean decide = false; + final Collection<RequestAttributes> requestAttributes = pepRequest.getRequestAttributes(); + for (final RequestAttributes requestAttribute : requestAttributes) { + final Collection<Attribute> attributes = requestAttribute.getAttributes(); + for (final Attribute attribute : attributes) { + if (attribute.getAttributeId().stringValue().equals("urn:oasis:names:tc:xacml:1.0:action:action-id")) { + for (final AttributeValue<?> attributeValue : attribute.getValues()) { + if (attributeValue.getValue().toString().equalsIgnoreCase("ACCESS")) { + count++; + } + if (attributeValue.getValue().toString().equalsIgnoreCase("DECIDE")) { + decide = true; + } + } + } + if (attribute.getAttributeId().stringValue() + .equals("urn:oasis:names:tc:xacml:1.0:resource:resource-id")) { + for (final AttributeValue<?> attributeValue : attribute.getValues()) { + if (attributeValue.getValue().toString().equalsIgnoreCase("Config")) { + count++; + } + } + } + } + } + if (count == 2) { + config = true; + } + if (!config) { + search(stdResponse); + } + addResults(stdResponse, config, decide); + logger.info("Original Result is " + stdResponse.toString()); + logger.info("Generated Result is " + addResult.toString()); + return newResponse; + } - private Collection<Obligation> obligations = new ArrayList<>(); - private Map<String, String> matchValues = new HashMap<>(); - private Map<String, String> headers = new HashMap<>(); - private boolean header = false; + private Collection<Obligation> obligations = new ArrayList<>(); + private Map<String, String> matchValues = new HashMap<>(); + private Map<String, String> headers = new HashMap<>(); + private boolean header = false; - private void search(StdMutableResponse stdResponse) { - for (Result result : stdResponse.getResults()) { - if (!result.getObligations().isEmpty()) { - System.out.println("Obligation Received"); - // Is there any action that PDP needs to take - for (Obligation obligation : result.getObligations()) { - int count = 0, uri = 0, PEP = 0; - header = false; - changeIt = false; - Collection<AttributeAssignment> afterRemoveAssignments = new ArrayList<>(); - Identifier oblId = new IdentifierImpl(obligation.getId().stringValue()); - StdAttributeAssignment attributeURI = null; - for (AttributeAssignment attribute : obligation.getAttributeAssignments()) { - matchValues.put(attribute.getAttributeId().stringValue(), attribute.getAttributeValue().getValue().toString()); - if (attribute.getAttributeId().stringValue().equalsIgnoreCase("performer")) { - if (attribute.getAttributeValue().getValue().toString().equalsIgnoreCase("PEPACTION")) { - PEP++; - } else if (attribute.getAttributeValue().getValue().toString().equalsIgnoreCase("PDPACTION")) { - count++; - } - } else if (attribute.getAttributeId().stringValue().equalsIgnoreCase("URL")) { - uri++; - if (uri == 1) { - configURL = attribute.getAttributeValue().getValue().toString(); - attributeURI = new StdAttributeAssignment(attribute); - } - } else if (attribute.getAttributeId().stringValue().startsWith("headers")) { - LOGGER.info("Headers are : "+ attribute.getAttributeValue().getValue().toString()); - header = true; - headers.put(attribute.getAttributeId().stringValue().replaceFirst("(headers).", ""), - attribute.getAttributeValue().getValue().toString()); - afterRemoveAssignments.add(attribute); - } else if (attribute.getAttributeId().stringValue().equalsIgnoreCase("body")) { - String papPath = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); - papPath= papPath.replace("/pap", ""); - matchValues.put("body",attribute.getAttributeValue().getValue().toString().replace("$URL", papPath)); - }else { - StdAttributeAssignment attributeObligation = new StdAttributeAssignment(attribute); - afterRemoveAssignments.add(attributeObligation); - } - } - if (count == 1 && uri == 1 && PEP == 0) { - // Remove Obligation and add Advice - changeIt = true; - takeAction(stdResponse, oblId, afterRemoveAssignments); - } else if (PEP == 1 && count == 0) { - // Strip the PEPACTION if available - if (uri == 1) { - afterRemoveAssignments.add(attributeURI); - } - Obligation afterRemoveObligation = new StdObligation( - oblId, afterRemoveAssignments); - obligations.add(afterRemoveObligation); - } else { - obligations.add(obligation); - } - } - } - } - } + private void search(final StdMutableResponse stdResponse) { + for (final Result result : stdResponse.getResults()) { + if (!result.getObligations().isEmpty()) { + System.out.println("Obligation Received"); + // Is there any action that PDP needs to take + for (final Obligation obligation : result.getObligations()) { + int count = 0; + int uri = 0; + int pep = 0; + header = false; + changeIt = false; + final Collection<AttributeAssignment> afterRemoveAssignments = new ArrayList<>(); + final Identifier oblId = new IdentifierImpl(obligation.getId().stringValue()); + StdAttributeAssignment attributeUri = null; + for (final AttributeAssignment attribute : obligation.getAttributeAssignments()) { + matchValues.put(attribute.getAttributeId().stringValue(), + attribute.getAttributeValue().getValue().toString()); + if (attribute.getAttributeId().stringValue().equalsIgnoreCase("performer")) { + if (attribute.getAttributeValue().getValue().toString().equalsIgnoreCase("PEPACTION")) { + pep++; + } else if (attribute.getAttributeValue().getValue().toString() + .equalsIgnoreCase("PDPACTION")) { + count++; + } + } else if (attribute.getAttributeId().stringValue().equalsIgnoreCase("URL")) { + uri++; + if (uri == 1) { + configUrl = attribute.getAttributeValue().getValue().toString(); + attributeUri = new StdAttributeAssignment(attribute); + } + } else if (attribute.getAttributeId().stringValue().startsWith("headers")) { + logger.info("Headers are : " + attribute.getAttributeValue().getValue().toString()); + header = true; + headers.put(attribute.getAttributeId().stringValue().replaceFirst("(headers).", ""), + attribute.getAttributeValue().getValue().toString()); + afterRemoveAssignments.add(attribute); + } else if (attribute.getAttributeId().stringValue().equalsIgnoreCase("body")) { + String papPath = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); + papPath = papPath.replace("/pap", ""); + matchValues.put("body", + attribute.getAttributeValue().getValue().toString().replace("$URL", papPath)); + } else { + final StdAttributeAssignment attributeObligation = new StdAttributeAssignment(attribute); + afterRemoveAssignments.add(attributeObligation); + } + } + if (count == 1 && uri == 1 && pep == 0) { + // Remove Obligation and add Advice + changeIt = true; + takeAction(stdResponse, oblId, afterRemoveAssignments); + } else if (pep == 1 && count == 0) { + // Strip the PEPACTION if available + if (uri == 1) { + afterRemoveAssignments.add(attributeUri); + } + final Obligation afterRemoveObligation = new StdObligation(oblId, afterRemoveAssignments); + obligations.add(afterRemoveObligation); + } else { + obligations.add(obligation); + } + } + } + } + } - private void takeAction(StdMutableResponse stdResponse, Identifier advId, - Collection<AttributeAssignment> afterRemoveAssignments) { - if (changeIt) { - LOGGER.info("the URL is :" + configURL); - // Calling Rest URL.. - callRest(); - // Including the Results in an Advice - Identifier id = new IdentifierImpl( - "org.onap.policy:pdp:reply"); - Identifier statId = new IdentifierImpl( - "org:onap:onap:policy:pdp:reply:status"); - Identifier statCategory = new IdentifierImpl( - "urn:oasis:names:tc:xacml:1.0:subject-category:recipient-subject"); - Identifier strId = new IdentifierImpl( - "http://www.w3.org/2001/XMLSchema#string"); - Identifier resId = new IdentifierImpl( - "org:onap:onap:policy:pdp:reply:resource"); - Identifier resCategory = new IdentifierImpl( - "urn:oasis:names:tc:xacml:3.0:attribute-category:resource"); - Identifier urlId = new IdentifierImpl( - "http://www.w3.org/2001/XMLSchema#anyURI"); - AttributeValue<String> attributeStatusValue = new StdAttributeValue<>( - strId, status + response); - AttributeValue<String> attributeResourceValue = new StdAttributeValue<>( - urlId, configURL); - StdAttributeAssignment attributeStatus = new StdAttributeAssignment( - statCategory, statId, "PDP", attributeStatusValue); - StdAttributeAssignment attributeResouce = new StdAttributeAssignment( - resCategory, resId, "PDP", attributeResourceValue); - afterRemoveAssignments.add(attributeStatus); - afterRemoveAssignments.add(attributeResouce); - Advice advice = new StdAdvice(id, afterRemoveAssignments); - addResult.addAdvice(advice); - } - } + private void takeAction(final StdMutableResponse stdResponse, final Identifier advId, + final Collection<AttributeAssignment> afterRemoveAssignments) { + if (changeIt) { + logger.info("the URL is :" + configUrl); + // Calling Rest URL.. + callRest(); + // Including the Results in an Advice + final Identifier id = new IdentifierImpl("org.onap.policy:pdp:reply"); + final Identifier statId = new IdentifierImpl("org:onap:onap:policy:pdp:reply:status"); + final Identifier statCategory = + new IdentifierImpl("urn:oasis:names:tc:xacml:1.0:subject-category:recipient-subject"); + final Identifier strId = new IdentifierImpl("http://www.w3.org/2001/XMLSchema#string"); + final Identifier resId = new IdentifierImpl("org:onap:onap:policy:pdp:reply:resource"); + final Identifier resCategory = + new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource"); + final Identifier urlId = new IdentifierImpl("http://www.w3.org/2001/XMLSchema#anyURI"); + final AttributeValue<String> attributeStatusValue = new StdAttributeValue<>(strId, status + response); + final AttributeValue<String> attributeResourceValue = new StdAttributeValue<>(urlId, configUrl); + final StdAttributeAssignment attributeStatus = + new StdAttributeAssignment(statCategory, statId, "PDP", attributeStatusValue); + final StdAttributeAssignment attributeResouce = + new StdAttributeAssignment(resCategory, resId, "PDP", attributeResourceValue); + afterRemoveAssignments.add(attributeStatus); + afterRemoveAssignments.add(attributeResouce); + final Advice advice = new StdAdvice(id, afterRemoveAssignments); + addResult.addAdvice(advice); + } + } - private void addResults(StdMutableResponse stdResponse, boolean config, boolean decide) { - if(decide){ - newResponse = stdResponse; - return; - } - for (Result result : stdResponse.getResults()) { - if(config){ - addResult.addAdvice(result.getAssociatedAdvice()); - } - addResult.addAttributeCategories(result.getAttributes()); - addResult.addPolicyIdentifiers(result.getPolicyIdentifiers()); - addResult.addPolicySetIdentifiers(result.getPolicySetIdentifiers()); - addResult.setStatus(result.getStatus()); - addResult.setDecision(result.getDecision()); - if(!config){ - addResult.addObligations(obligations); - } - } - newResponse.add(addResult); - } + private void addResults(final StdMutableResponse stdResponse, final boolean config, final boolean decide) { + if (decide) { + newResponse = stdResponse; + return; + } + for (final Result result : stdResponse.getResults()) { + if (config) { + addResult.addAdvice(result.getAssociatedAdvice()); + } + addResult.addAttributeCategories(result.getAttributes()); + addResult.addPolicyIdentifiers(result.getPolicyIdentifiers()); + addResult.addPolicySetIdentifiers(result.getPolicySetIdentifiers()); + addResult.setStatus(result.getStatus()); + addResult.setDecision(result.getDecision()); + if (!config) { + addResult.addObligations(obligations); + } + } + newResponse.add(addResult); + } - private int status; - private String response; - private DefaultHttpClient httpClient; + private int status; + private String response; + private DefaultHttpClient httpClient; - private void callRest() { - // Finding the Macros in the URL.. - Pattern pattern = Pattern.compile("\\$([a-zA-Z0-9.:]*)"); - Matcher match = pattern.matcher(configURL); - StringBuffer sb = new StringBuffer(); - JsonReader jsonReader = null; - while (match.find()) { - LOGGER.info("Found Macro : " + match.group(1)); - String replaceValue = matchValues.get(match.group(1)); - LOGGER.info("Replacing with :" + replaceValue); - match.appendReplacement(sb, replaceValue); - } - match.appendTail(sb); - LOGGER.info("URL is : " + sb.toString()); - configURL = sb.toString(); - // Calling the Requested service. - if (matchValues.get("method").equalsIgnoreCase("GET")) { - httpClient = new DefaultHttpClient(); - try { - HttpGet getRequest = new HttpGet(configURL); - // Adding Headers here - if (header) { - for (String key : headers.keySet()) { - getRequest.addHeader(key, headers.get(key)); - } - } - HttpResponse result = httpClient.execute(getRequest); - status = result.getStatusLine().getStatusCode(); - BufferedReader br = new BufferedReader(new InputStreamReader( - (result.getEntity().getContent()))); - String output = " "; - String out; - while ((out = br.readLine()) != null) { - output = output + out; - } - response = output; - } catch (Exception e) { - LOGGER.error(e.getMessage()+e); - response = e.getMessage(); - } finally { - httpClient.getConnectionManager().shutdown(); - } - } else if(matchValues.get("method").equalsIgnoreCase("POST")) { - httpClient = new DefaultHttpClient(); - try { - HttpPost postRequest = new HttpPost(configURL); - // Adding Headers here - if (header) { - for (String key : headers.keySet()) { - postRequest.addHeader(key, headers.get(key)); - } - } - // Adding the Body. - URL configURL = new URL(matchValues.get("body")); - URLConnection connection = null; - connection = configURL.openConnection(); - // InputStream in = connection.getInputStrem(); - // LOGGER.info("The Body Content is : " + IOUtils.toString(in)); - jsonReader = Json.createReader(connection.getInputStream()); - StringEntity input = new StringEntity(jsonReader.readObject().toString()); - input.setContentType("application/json"); - postRequest.setEntity(input); - // Executing the Request. - HttpResponse result = httpClient.execute(postRequest); - LOGGER.info("Result Headers are : " + result.getAllHeaders()); - status = result.getStatusLine().getStatusCode(); - BufferedReader br = new BufferedReader(new InputStreamReader( - (result.getEntity().getContent()))); - String output = " "; - String out; - while ((out = br.readLine()) != null) { - output = output + out; - } - response = output; - }catch (Exception e) { - LOGGER.error(e.getMessage() +e); - response = e.getMessage(); - } finally { - if(jsonReader != null) { - try { - jsonReader.close(); - } catch (Exception e) { - LOGGER.error("Exception Occured while closing the JsonReader"+e); - } - } - httpClient.getConnectionManager().shutdown(); - } - } else if(matchValues.get("method").equalsIgnoreCase("PUT")) { - httpClient = new DefaultHttpClient(); - try { - HttpPut putRequest = new HttpPut(configURL); - // Adding Headers here - if (header) { - for (String key : headers.keySet()) { - putRequest.addHeader(key, headers.get(key)); - } - } - // Adding the Body. - URL configURL = new URL(matchValues.get("body")); - URLConnection connection = null; - connection = configURL.openConnection(); - //InputStream in = connection.getInputStream(); - //LOGGER.info("The Body Content is : " + IOUtils.toString(in)); - jsonReader = Json.createReader(connection.getInputStream()); - StringEntity input = new StringEntity(jsonReader.readObject().toString()); - input.setContentType("application/json"); - putRequest.setEntity(input); - // Executing the Request. - HttpResponse result = httpClient.execute(putRequest); - status = result.getStatusLine().getStatusCode(); - BufferedReader br = new BufferedReader(new InputStreamReader( - (result.getEntity().getContent()))); - String output = " "; - String out; - while ((out = br.readLine()) != null) { - output = output + out; - } - response = output; - } catch (Exception e) { - LOGGER.error(e.getMessage() +e); - response = e.getMessage(); - }finally { - if(jsonReader != null) { - try { - jsonReader.close(); - } catch (Exception e) { - LOGGER.error("Exception Occured while closing the JsonReader"+e); - } - } - httpClient.getConnectionManager().shutdown(); - } - } - } -}
\ No newline at end of file + private void callRest() { + // Finding the Macros in the URL.. + final Pattern pattern = Pattern.compile("\\$([a-zA-Z0-9.:]*)"); + final Matcher match = pattern.matcher(configUrl); + final StringBuffer sb = new StringBuffer(); + JsonReader jsonReader = null; + while (match.find()) { + logger.info("Found Macro : " + match.group(1)); + final String replaceValue = matchValues.get(match.group(1)); + logger.info("Replacing with :" + replaceValue); + match.appendReplacement(sb, replaceValue); + } + match.appendTail(sb); + logger.info("URL is : " + sb.toString()); + configUrl = sb.toString(); + // Calling the Requested service. + if (matchValues.get("method").equalsIgnoreCase("GET")) { + httpClient = new DefaultHttpClient(); + try { + final HttpGet getRequest = new HttpGet(configUrl); + // Adding Headers here + if (header) { + for (final String key : headers.keySet()) { + getRequest.addHeader(key, headers.get(key)); + } + } + final HttpResponse result = httpClient.execute(getRequest); + status = result.getStatusLine().getStatusCode(); + final BufferedReader br = new BufferedReader(new InputStreamReader((result.getEntity().getContent()))); + String output = " "; + String out; + while ((out = br.readLine()) != null) { + output = output + out; + } + response = output; + } catch (final Exception e) { + logger.error(e.getMessage() + e); + response = e.getMessage(); + } finally { + httpClient.getConnectionManager().shutdown(); + } + } else if (matchValues.get("method").equalsIgnoreCase("POST")) { + httpClient = new DefaultHttpClient(); + try { + final HttpPost postRequest = new HttpPost(configUrl); + // Adding Headers here + if (header) { + for (final String key : headers.keySet()) { + postRequest.addHeader(key, headers.get(key)); + } + } + // Adding the Body. + final URL configUrl = new URL(matchValues.get("body")); + URLConnection connection = null; + connection = configUrl.openConnection(); + // InputStream in = connection.getInputStrem(); + // LOGGER.info("The Body Content is : " + IOUtils.toString(in)); + jsonReader = Json.createReader(connection.getInputStream()); + final StringEntity input = new StringEntity(jsonReader.readObject().toString()); + input.setContentType("application/json"); + postRequest.setEntity(input); + // Executing the Request. + final HttpResponse result = httpClient.execute(postRequest); + logger.info("Result Headers are : " + result.getAllHeaders()); + status = result.getStatusLine().getStatusCode(); + final BufferedReader br = new BufferedReader(new InputStreamReader((result.getEntity().getContent()))); + String output = " "; + String out; + while ((out = br.readLine()) != null) { + output = output + out; + } + response = output; + } catch (final Exception e) { + logger.error(e.getMessage() + e); + response = e.getMessage(); + } finally { + if (jsonReader != null) { + try { + jsonReader.close(); + } catch (final Exception e) { + logger.error("Exception Occured while closing the JsonReader" + e); + } + } + httpClient.getConnectionManager().shutdown(); + } + } else if (matchValues.get("method").equalsIgnoreCase("PUT")) { + httpClient = new DefaultHttpClient(); + try { + final HttpPut putRequest = new HttpPut(configUrl); + // Adding Headers here + if (header) { + for (final String key : headers.keySet()) { + putRequest.addHeader(key, headers.get(key)); + } + } + // Adding the Body. + final URL configUrl = new URL(matchValues.get("body")); + URLConnection connection = null; + connection = configUrl.openConnection(); + // InputStream in = connection.getInputStream(); + // LOGGER.info("The Body Content is : " + IOUtils.toString(in)); + jsonReader = Json.createReader(connection.getInputStream()); + final StringEntity input = new StringEntity(jsonReader.readObject().toString()); + input.setContentType("application/json"); + putRequest.setEntity(input); + // Executing the Request. + final HttpResponse result = httpClient.execute(putRequest); + status = result.getStatusLine().getStatusCode(); + final BufferedReader br = new BufferedReader(new InputStreamReader((result.getEntity().getContent()))); + String output = " "; + String out; + while ((out = br.readLine()) != null) { + output = output + out; + } + response = output; + } catch (final Exception e) { + logger.error(e.getMessage() + e); + response = e.getMessage(); + } finally { + if (jsonReader != null) { + try { + jsonReader.close(); + } catch (final Exception e) { + logger.error("Exception Occured while closing the JsonReader" + e); + } + } + httpClient.getConnectionManager().shutdown(); + } + } + } +} diff --git a/ONAP-PDP/src/main/java/org/onap/policy/xacml/action/package-info.java b/ONAP-PDP/src/main/java/org/onap/policy/xacml/action/package-info.java index 82c6182b9..b4fd05075 100644 --- a/ONAP-PDP/src/main/java/org/onap/policy/xacml/action/package-info.java +++ b/ONAP-PDP/src/main/java/org/onap/policy/xacml/action/package-info.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PDP * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -21,10 +21,9 @@ package org.onap.policy.xacml.action; /** - * org.onap.policy.xacml.action contains the implementation of the PDP Actions. - * Changes: - * Now PDP supports actions based on PUT, GET, POST methods - * - * @version 0.2 - * + * org.onap.policy.xacml.action contains the implementation of the PDP Actions. Changes: Now PDP supports actions based + * on PUT, GET, POST methods + * + * @version 0.2 + * */ diff --git a/ONAP-PDP/src/main/java/org/onap/policy/xacml/custom/OnapFunctionDefinitionFactory.java b/ONAP-PDP/src/main/java/org/onap/policy/xacml/custom/OnapFunctionDefinitionFactory.java index ea4e90eda..35080d396 100644 --- a/ONAP-PDP/src/main/java/org/onap/policy/xacml/custom/OnapFunctionDefinitionFactory.java +++ b/ONAP-PDP/src/main/java/org/onap/policy/xacml/custom/OnapFunctionDefinitionFactory.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PDP * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -17,8 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.xacml.custom; +import com.att.research.xacml.api.Identifier; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacml.std.datatypes.DataTypes; +import com.att.research.xacmlatt.pdp.policy.FunctionDefinition; +import com.att.research.xacmlatt.pdp.policy.FunctionDefinitionFactory; +import com.att.research.xacmlatt.pdp.std.StdFunctions; + import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; @@ -28,60 +36,53 @@ import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.xacml.pdp.std.functions.FunctionDefinitionCustomRegexpMatch; -import com.att.research.xacml.api.Identifier; -import com.att.research.xacml.std.IdentifierImpl; -import com.att.research.xacml.std.datatypes.DataTypes; -import com.att.research.xacmlatt.pdp.policy.FunctionDefinition; -import com.att.research.xacmlatt.pdp.policy.FunctionDefinitionFactory; -import com.att.research.xacmlatt.pdp.std.StdFunctions; - public class OnapFunctionDefinitionFactory extends FunctionDefinitionFactory { - private static Logger logger = FlexLogger.getLogger(OnapFunctionDefinitionFactory.class); - private static Map<Identifier,FunctionDefinition> mapFunctionDefinitions = new HashMap<>(); - private static boolean needMapInit = true; + private static Logger logger = FlexLogger.getLogger(OnapFunctionDefinitionFactory.class); + private static Map<Identifier, FunctionDefinition> mapFunctionDefinitions = new HashMap<>(); + private static boolean needMapInit = true; + + public static final Identifier ID_FUNCTION_CUSTOM_REGEXP_MATCH = + new IdentifierImpl("org.onap.function.regex-match"); + + private static final FunctionDefinition FD_CUSTOM_REGEXP_MATCH = + new FunctionDefinitionCustomRegexpMatch<>(ID_FUNCTION_CUSTOM_REGEXP_MATCH, DataTypes.DT_STRING); + + private static void register(final FunctionDefinition functionDefinition) { + mapFunctionDefinitions.put(functionDefinition.getId(), functionDefinition); + } - public static final Identifier ID_FUNCTION_CUSTOM_REGEXP_MATCH = new IdentifierImpl("org.onap.function.regex-match"); - - private static final FunctionDefinition FD_CUSTOM_REGEXP_MATCH = new FunctionDefinitionCustomRegexpMatch<>(ID_FUNCTION_CUSTOM_REGEXP_MATCH, DataTypes.DT_STRING); + private static void initMap() { - private static void register(FunctionDefinition functionDefinition) { - mapFunctionDefinitions.put(functionDefinition.getId(), functionDefinition); - } - - private static void initMap() { + synchronized (mapFunctionDefinitions) { + if (needMapInit) { + needMapInit = false; + final Field[] declaredFields = StdFunctions.class.getDeclaredFields(); + for (final Field field : declaredFields) { + if (Modifier.isStatic(field.getModifiers()) && field.getName().startsWith(StdFunctions.FD_PREFIX) + && FunctionDefinition.class.isAssignableFrom(field.getType()) + && Modifier.isPublic(field.getModifiers())) { + try { + register((FunctionDefinition) (field.get(null))); + } catch (final IllegalAccessException ex) { + logger.error(ex.getMessage() + ex); + } + } + } + // + // Our custom function + // + // register(FunctionDefinitionCustomRegexpMatch); + register(FD_CUSTOM_REGEXP_MATCH); + } + } + } - synchronized(mapFunctionDefinitions) { - if (needMapInit) { - needMapInit = false; - Field[] declaredFields = StdFunctions.class.getDeclaredFields(); - for (Field field : declaredFields) { - if (Modifier.isStatic(field.getModifiers()) && - field.getName().startsWith(StdFunctions.FD_PREFIX) && - FunctionDefinition.class.isAssignableFrom(field.getType()) && - Modifier.isPublic(field.getModifiers()) - ) { - try { - register((FunctionDefinition)(field.get(null))); - } catch (IllegalAccessException ex) { - logger.error(ex.getMessage() +ex); - } - } - } - // - // Our custom function - // - //register(FunctionDefinitionCustomRegexpMatch); - register(FD_CUSTOM_REGEXP_MATCH); - } - } - } - - public OnapFunctionDefinitionFactory() { - initMap(); - } + public OnapFunctionDefinitionFactory() { + initMap(); + } - @Override - public FunctionDefinition getFunctionDefinition(Identifier functionId) { - return mapFunctionDefinitions.get(functionId); - } + @Override + public FunctionDefinition getFunctionDefinition(final Identifier functionId) { + return mapFunctionDefinitions.get(functionId); + } } diff --git a/ONAP-PDP/src/main/java/org/onap/policy/xacml/pdp/ONAPPDPEngineFactory.java b/ONAP-PDP/src/main/java/org/onap/policy/xacml/pdp/ONAPPDPEngineFactory.java deleted file mode 100644 index 2e796bf68..000000000 --- a/ONAP-PDP/src/main/java/org/onap/policy/xacml/pdp/ONAPPDPEngineFactory.java +++ /dev/null @@ -1,54 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP-PDP - * ================================================================================ - * 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.onap.policy.xacml.pdp; - -import java.util.Properties; - -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; -import com.att.research.xacml.api.pdp.PDPEngine; -import com.att.research.xacml.api.pdp.PDPEngineFactory; -import com.att.research.xacml.util.FactoryException; -import com.att.research.xacmlatt.pdp.eval.EvaluationContextFactory; - -public class ONAPPDPEngineFactory extends PDPEngineFactory { - private Logger logger = FlexLogger.getLogger(this.getClass()); - - @Override - public PDPEngine newEngine() throws FactoryException { - EvaluationContextFactory evaluationContextFactory = EvaluationContextFactory.newInstance(); - if (evaluationContextFactory == null) { - this.logger.error("Null EvaluationContextFactory"); - throw new FactoryException("Null EvaluationContextFactory"); - } - return new ONAPPDPEngine(evaluationContextFactory, this.getDefaultBehavior(), this.getScopeResolver()); - } - - @Override - public PDPEngine newEngine(Properties properties) throws FactoryException { - EvaluationContextFactory evaluationContextFactory = EvaluationContextFactory.newInstance(properties); - if (evaluationContextFactory == null) { - this.logger.error("Null EvaluationContextFactory"); - throw new FactoryException("Null EvaluationContextFactory"); - } - return new ONAPPDPEngine(evaluationContextFactory, this.getDefaultBehavior(), this.getScopeResolver(), properties); - } - -} diff --git a/ONAP-PDP/src/main/java/org/onap/policy/xacml/pdp/ONAPPDPEngine.java b/ONAP-PDP/src/main/java/org/onap/policy/xacml/pdp/OnapPdpEngine.java index fb90d0a2e..42ab7e415 100644 --- a/ONAP-PDP/src/main/java/org/onap/policy/xacml/pdp/ONAPPDPEngine.java +++ b/ONAP-PDP/src/main/java/org/onap/policy/xacml/pdp/OnapPdpEngine.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PDP * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -17,11 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.onap.policy.xacml.pdp; - -import java.util.Properties; -import org.onap.policy.xacml.action.FindAction; +package org.onap.policy.xacml.pdp; import com.att.research.xacml.api.Decision; import com.att.research.xacml.api.Request; @@ -32,29 +29,34 @@ import com.att.research.xacml.std.StdMutableResponse; import com.att.research.xacmlatt.pdp.ATTPDPEngine; import com.att.research.xacmlatt.pdp.eval.EvaluationContextFactory; -public class ONAPPDPEngine extends ATTPDPEngine { - - public ONAPPDPEngine(EvaluationContextFactory evaluationContextFactoryIn, Decision defaultDecisionIn, - ScopeResolver scopeResolverIn, Properties properties) { - super(evaluationContextFactoryIn, defaultDecisionIn, scopeResolverIn, properties); - } - - public ONAPPDPEngine(EvaluationContextFactory evaluationContextFactoryIn, Decision defaultDecisionIn, - ScopeResolver scopeResolverIn) { - super(evaluationContextFactoryIn, defaultDecisionIn, scopeResolverIn); - } - - public ONAPPDPEngine(EvaluationContextFactory evaluationContextFactoryIn, ScopeResolver scopeResolverIn) { - super(evaluationContextFactoryIn, scopeResolverIn); - } - - @Override - public Response decide(Request pepRequest) throws PDPException { - Response response = super.decide(pepRequest); - - FindAction findAction = new FindAction(); - return findAction.run((StdMutableResponse) response, pepRequest); - } +import java.util.Properties; + +import org.onap.policy.xacml.action.FindAction; + +public class OnapPdpEngine extends ATTPDPEngine { + + public OnapPdpEngine(final EvaluationContextFactory evaluationContextFactoryIn, final Decision defaultDecisionIn, + final ScopeResolver scopeResolverIn, final Properties properties) { + super(evaluationContextFactoryIn, defaultDecisionIn, scopeResolverIn, properties); + } + + public OnapPdpEngine(final EvaluationContextFactory evaluationContextFactoryIn, final Decision defaultDecisionIn, + final ScopeResolver scopeResolverIn) { + super(evaluationContextFactoryIn, defaultDecisionIn, scopeResolverIn); + } + + public OnapPdpEngine(final EvaluationContextFactory evaluationContextFactoryIn, + final ScopeResolver scopeResolverIn) { + super(evaluationContextFactoryIn, scopeResolverIn); + } + + @Override + public Response decide(final Request pepRequest) throws PDPException { + final Response response = super.decide(pepRequest); + + final FindAction findAction = new FindAction(); + return findAction.run((StdMutableResponse) response, pepRequest); + } } diff --git a/ONAP-PDP/src/main/java/org/onap/policy/xacml/pdp/OnapPdpEngineFactory.java b/ONAP-PDP/src/main/java/org/onap/policy/xacml/pdp/OnapPdpEngineFactory.java new file mode 100644 index 000000000..c19c4012a --- /dev/null +++ b/ONAP-PDP/src/main/java/org/onap/policy/xacml/pdp/OnapPdpEngineFactory.java @@ -0,0 +1,57 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * Copyright (C) 2017-2018 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.onap.policy.xacml.pdp; + +import com.att.research.xacml.api.pdp.PDPEngine; +import com.att.research.xacml.api.pdp.PDPEngineFactory; +import com.att.research.xacml.util.FactoryException; +import com.att.research.xacmlatt.pdp.eval.EvaluationContextFactory; + +import java.util.Properties; + +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + +public class OnapPdpEngineFactory extends PDPEngineFactory { + private Logger logger = FlexLogger.getLogger(this.getClass()); + + @Override + public PDPEngine newEngine() throws FactoryException { + final EvaluationContextFactory evaluationContextFactory = EvaluationContextFactory.newInstance(); + if (evaluationContextFactory == null) { + this.logger.error("Null EvaluationContextFactory"); + throw new FactoryException("Null EvaluationContextFactory"); + } + return new OnapPdpEngine(evaluationContextFactory, this.getDefaultBehavior(), this.getScopeResolver()); + } + + @Override + public PDPEngine newEngine(final Properties properties) throws FactoryException { + final EvaluationContextFactory evaluationContextFactory = EvaluationContextFactory.newInstance(properties); + if (evaluationContextFactory == null) { + this.logger.error("Null EvaluationContextFactory"); + throw new FactoryException("Null EvaluationContextFactory"); + } + return new OnapPdpEngine(evaluationContextFactory, this.getDefaultBehavior(), this.getScopeResolver(), + properties); + } + +} diff --git a/ONAP-PDP/src/main/java/org/onap/policy/xacml/pdp/std/functions/FunctionDefinitionCustomRegexpMatch.java b/ONAP-PDP/src/main/java/org/onap/policy/xacml/pdp/std/functions/FunctionDefinitionCustomRegexpMatch.java index 590d519cc..a8b0e9d15 100644 --- a/ONAP-PDP/src/main/java/org/onap/policy/xacml/pdp/std/functions/FunctionDefinitionCustomRegexpMatch.java +++ b/ONAP-PDP/src/main/java/org/onap/policy/xacml/pdp/std/functions/FunctionDefinitionCustomRegexpMatch.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PDP * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -17,13 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.onap.policy.xacml.pdp.std.functions; - - -import java.util.List; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; +package org.onap.policy.xacml.pdp.std.functions; import com.att.research.xacml.api.DataType; import com.att.research.xacml.api.DataTypeException; @@ -37,94 +32,104 @@ import com.att.research.xacmlatt.pdp.policy.FunctionArgument; import com.att.research.xacmlatt.pdp.std.functions.ConvertedArgument; import com.att.research.xacmlatt.pdp.std.functions.FunctionDefinitionBase; +import java.util.List; + +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + /** * FunctionDefinitionCustomRegexMatch implements {@link com.att.research.xacmlatt.pdp.policy.FunctionDefinition} to - * implement the custom 'type'-regex-match predicates as functions taking two arguments, the first of <code>String</code>, - * and the second of the type for that specific predicate as a regular expression, - * and returning a <code>Boolean</code> for whether the regular expression matches the string representation of the first argument. - * - * + * implement the custom 'type'-regex-match predicates as functions taking two arguments, the first of + * <code>String</code>, and the second of the type for that specific predicate as a regular expression, and returning a + * <code>Boolean</code> for whether the regular expression matches the string representation of the first argument. + * + * * @version $Revision: 0.2 $ - * + * * @param <I> the java class for the data type of the function Input arguments */ public class FunctionDefinitionCustomRegexpMatch<I> extends FunctionDefinitionBase<Boolean, I> { - private static Logger logger = FlexLogger.getLogger(FunctionDefinitionCustomRegexpMatch.class); - - /** - * Constructor - need dataTypeArgs input because of java Generic type-erasure during compilation. - * - * @param idIn - * @param dataTypeArgsIn - */ - public FunctionDefinitionCustomRegexpMatch(Identifier idIn, DataType<I> dataTypeArgsIn) { - super(idIn, DataTypes.DT_BOOLEAN, dataTypeArgsIn, false); - } - - - @Override - public ExpressionResult evaluate(EvaluationContext evaluationContext, List<FunctionArgument> arguments) { - - if (arguments == null || arguments.size() != 2) { - return ExpressionResult.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, this.getShortFunctionId() + " Expected 2 arguments, got " + - ((arguments == null) ? "null" : arguments.size()) )); - } - - // get the regular expression - FunctionArgument regexpArgument = arguments.get(0); - - ConvertedArgument<String> convertedArgument = new ConvertedArgument<>(regexpArgument, DataTypes.DT_STRING, false); - if ( ! convertedArgument.isOk()) { - return ExpressionResult.newError(getFunctionStatus(convertedArgument.getStatus())); - } - - // String regexpValue = (String)regexpArgument.getValue().getValue(); - String regexpValue = convertedArgument.getValue(); - - - // now get the element to match - FunctionArgument elementArgument = arguments.get(1); - - ConvertedArgument<I> convertedElement = new ConvertedArgument<>(elementArgument, this.getDataTypeArgs(), false); - if ( ! convertedElement.isOk()) { - return ExpressionResult.newError(getFunctionStatus(convertedElement.getStatus())); - } - - I elementValueObject = convertedElement.getValue(); - - String elementValueString; - try { - elementValueString = this.getDataTypeArgs().toStringValue(elementValueObject); - } catch (DataTypeException e) { - logger.error(e.getMessage() +e); - String message = e.getMessage(); - if (e.getCause() != null) { - message = e.getCause().getMessage(); - } - return ExpressionResult.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, this.getShortFunctionId() + " " + message)); - } - - // ConvertedArgument checks for null value, so do not need to do again here - - // Adding this code will Change the Functionality which allows to retrieve Multiple-policy using single request. - elementValueString = elementValueString + regexpValue ; - regexpValue = elementValueString.substring(0,(elementValueString.length()- regexpValue.length())); - elementValueString = elementValueString.substring(regexpValue.length(),(elementValueString.length())); - // - // Supporting multiple values in the element and be able to query them. - if(elementValueString.contains(",")){ - String[] elements = elementValueString.split(","); - for(int i=0; i<elements.length; i++){ - if(elements[i].trim().matches(regexpValue)) { - return ER_TRUE; - } - } - } - if (elementValueString.matches(regexpValue)) { - return ER_TRUE; - } else { - return ER_FALSE; - } - - } + private static Logger logger = FlexLogger.getLogger(FunctionDefinitionCustomRegexpMatch.class); + + /** + * Constructor - need dataTypeArgs input because of java Generic type-erasure during compilation. + * + * @param idIn the identifier + * @param dataTypeArgsIn the data type + */ + public FunctionDefinitionCustomRegexpMatch(final Identifier idIn, final DataType<I> dataTypeArgsIn) { + super(idIn, DataTypes.DT_BOOLEAN, dataTypeArgsIn, false); + } + + + @Override + public ExpressionResult evaluate(final EvaluationContext evaluationContext, + final List<FunctionArgument> arguments) { + + if (arguments == null || arguments.size() != 2) { + return ExpressionResult + .newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, this.getShortFunctionId() + + " Expected 2 arguments, got " + ((arguments == null) ? "null" : arguments.size()))); + } + + // get the regular expression + final FunctionArgument regexpArgument = arguments.get(0); + + final ConvertedArgument<String> convertedArgument = + new ConvertedArgument<>(regexpArgument, DataTypes.DT_STRING, false); + if (!convertedArgument.isOk()) { + return ExpressionResult.newError(getFunctionStatus(convertedArgument.getStatus())); + } + + // String regexpValue = (String)regexpArgument.getValue().getValue(); + String regexpValue = convertedArgument.getValue(); + + + // now get the element to match + final FunctionArgument elementArgument = arguments.get(1); + + final ConvertedArgument<I> convertedElement = + new ConvertedArgument<>(elementArgument, this.getDataTypeArgs(), false); + if (!convertedElement.isOk()) { + return ExpressionResult.newError(getFunctionStatus(convertedElement.getStatus())); + } + + final I elementValueObject = convertedElement.getValue(); + + String elementValueString; + try { + elementValueString = this.getDataTypeArgs().toStringValue(elementValueObject); + } catch (final DataTypeException e) { + logger.error(e.getMessage() + e); + String message = e.getMessage(); + if (e.getCause() != null) { + message = e.getCause().getMessage(); + } + return ExpressionResult.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, + this.getShortFunctionId() + " " + message)); + } + + // ConvertedArgument checks for null value, so do not need to do again here + + // Adding this code will Change the Functionality which allows to retrieve Multiple-policy using single request. + elementValueString = elementValueString + regexpValue; + regexpValue = elementValueString.substring(0, (elementValueString.length() - regexpValue.length())); + elementValueString = elementValueString.substring(regexpValue.length(), (elementValueString.length())); + // + // Supporting multiple values in the element and be able to query them. + if (elementValueString.contains(",")) { + final String[] elements = elementValueString.split(","); + for (int i = 0; i < elements.length; i++) { + if (elements[i].trim().matches(regexpValue)) { + return ER_TRUE; + } + } + } + if (elementValueString.matches(regexpValue)) { + return ER_TRUE; + } else { + return ER_FALSE; + } + + } } diff --git a/ONAP-PDP/src/main/java/org/onap/policy/xacml/pdp/std/functions/PolicyList.java b/ONAP-PDP/src/main/java/org/onap/policy/xacml/pdp/std/functions/PolicyList.java index 794276f6a..13b517dd6 100644 --- a/ONAP-PDP/src/main/java/org/onap/policy/xacml/pdp/std/functions/PolicyList.java +++ b/ONAP-PDP/src/main/java/org/onap/policy/xacml/pdp/std/functions/PolicyList.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PDP * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -17,33 +17,43 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.xacml.pdp.std.functions; import java.util.ArrayList; import java.util.List; + /** * Creates a list of policy ids. - * + * * @version $Revision: 1.3 $ */ public class PolicyList { - - private static List<String> policyList = new ArrayList<>(); - - - public static List<String> getpolicyList(){ - return policyList; - } - - public static void addPolicyID(String policyID){ - if (!policyList.contains(policyID)){ - policyList.add(policyID); - } - } - - public static void clearPolicyList(){ - if (!policyList.isEmpty()){ - policyList.clear(); - } - } + + private static List<String> policyList = new ArrayList<>(); + + + public static List<String> getpolicyList() { + return policyList; + } + + /** + * Add policy id in the policy list. + * + * @param policyId the policy id + */ + public static void addPolicyId(final String policyId) { + if (!policyList.contains(policyId)) { + policyList.add(policyId); + } + } + + /** + * Clear policy list. + */ + public static void clearPolicyList() { + if (!policyList.isEmpty()) { + policyList.clear(); + } + } } diff --git a/ONAP-PDP/src/test/java/org/onap/policy/xacml/action/DummyRest.java b/ONAP-PDP/src/test/java/org/onap/policy/xacml/action/DummyRest.java index 7a7fe548d..1a6866c91 100644 --- a/ONAP-PDP/src/test/java/org/onap/policy/xacml/action/DummyRest.java +++ b/ONAP-PDP/src/test/java/org/onap/policy/xacml/action/DummyRest.java @@ -7,9 +7,9 @@ * 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. @@ -25,13 +25,13 @@ import javax.ws.rs.Path; @Path("/") public class DummyRest { - - @GET - @Path("/foobar") - public String subscribe() { - return "{\"Foo\":\"bar\"}"; - } - + @GET + @Path("/foobar") + public String subscribe() { + + return "{\"Foo\":\"bar\"}"; + } + } diff --git a/ONAP-PDP/src/test/java/org/onap/policy/xacml/action/FindActionTest.java b/ONAP-PDP/src/test/java/org/onap/policy/xacml/action/FindActionTest.java index 2a36fa280..f8a5e4b4a 100644 --- a/ONAP-PDP/src/test/java/org/onap/policy/xacml/action/FindActionTest.java +++ b/ONAP-PDP/src/test/java/org/onap/policy/xacml/action/FindActionTest.java @@ -7,9 +7,9 @@ * 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. @@ -17,16 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.xacml.action; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.policy.xacml.custom.OnapFunctionDefinitionFactory; import com.att.research.xacml.api.Decision; import com.att.research.xacml.api.Request; import com.att.research.xacml.api.XACML3; @@ -45,229 +41,196 @@ import com.att.research.xacml.std.datatypes.DataTypes; import com.att.research.xacml.std.json.JSONRequest; import com.att.research.xacml.util.XACMLProperties; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; import org.onap.policy.drools.http.server.HttpServletServer; import org.onap.policy.drools.utils.NetworkUtil; +import org.onap.policy.xacml.custom.OnapFunctionDefinitionFactory; public class FindActionTest { - - - String xPathExampleFromSpec = "{ " + - "\"Request\" : { " + - "\"Resource\" : { " + - "\"Attribute\": [ " + - "{ " + - "\"Id\" : \"urn:oasis:names:tc:xacml:3.0:content-selector\", " + - "\"DataType\" : \"xpathExpression\", " + - "\"Value\" : { " + - "\"XPathCategory\" : \"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\", " + - "\"Namespaces\" : [{ " + - "\"Namespace\" : \"urn:oasis:names:tc:xacml:3.0:core:schema:wd-17\" " + - "}, " + - "{ " + - "\"Prefix\" : \"md\", " + - "\"Namespace\" : \"urn:example:med:schemas:record\" " + - "} " + - "], " + - "\"XPath\" : \"md:record/md:patient/md:patientDoB\" " + - "} " + - "} " + - "] " + - "} " + - "} " + - "} "; - - String jsonResponse; - Request request; - private static final int MOCK_SERVER_PORT = 6670; - - @BeforeClass - public static void setUpServer() { + + String xpathexamplefromspec = "{ " + "\"Request\" : { " + "\"Resource\" : { " + "\"Attribute\": [ " + "{ " + + "\"Id\" : \"urn:oasis:names:tc:xacml:3.0:content-selector\", " + "\"DataType\" : \"xpathExpression\", " + + "\"Value\" : { " + "\"XPathCategory\" : \"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\", " + + "\"Namespaces\" : [{ " + "\"Namespace\" : \"urn:oasis:names:tc:xacml:3.0:core:schema:wd-17\" " + "}, " + + "{ " + "\"Prefix\" : \"md\", " + "\"Namespace\" : \"urn:example:med:schemas:record\" " + "} " + "], " + + "\"XPath\" : \"md:record/md:patient/md:patientDoB\" " + "} " + "} " + "] " + "} " + "} " + "} "; + + String jsonResponse; + Request request; + private static final int MOCK_SERVER_PORT = 6670; + + /** + * Setup server before test class. + */ + @BeforeClass + public static void setUpServer() { try { - final HttpServletServer testServer = HttpServletServer.factory.build("dmaapSim", - "localhost", MOCK_SERVER_PORT, "/", false, true); - testServer.addServletClass("/*", DummyRest.class.getName()); - testServer.waitedStart(2000); - if (!NetworkUtil.isTcpPortOpen("localhost", testServer.getPort(), 5, 10000L)) - throw new IllegalStateException("cannot connect to port " + testServer.getPort()); + final HttpServletServer testServer = + HttpServletServer.factory.build("dmaapSim", "localhost", MOCK_SERVER_PORT, "/", false, true); + testServer.addServletClass("/*", DummyRest.class.getName()); + testServer.waitedStart(2000); + if (!NetworkUtil.isTcpPortOpen("localhost", testServer.getPort(), 5, 10000L)) { + throw new IllegalStateException("cannot connect to port " + testServer.getPort()); + } } catch (final Exception e) { - fail(e.getMessage()); + fail(e.getMessage()); } - - } - + + } + @AfterClass public static void tearDownSimulator() { HttpServletServer.factory.destroy(); } - - @Before - public void setUp() throws Exception { - new OnapFunctionDefinitionFactory(); - request = JSONRequest.load(xPathExampleFromSpec); - - try { - XACMLProperties.reloadProperties(); - System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/xacml.pdp.properties"); - XACMLProperties.getProperties(); - - assertTrue(true); - } catch (Exception e) { - fail(); - - } - } - - - @Test - public final void testRun() { - FindAction action = new FindAction(); - // fully-loaded multiple response - StdMutableResponse response = new StdMutableResponse(); - // create a Status object - StdMutableStatus status = new StdMutableStatus(StdStatusCode.STATUS_CODE_MISSING_ATTRIBUTE); - status.setStatusMessage("some status message"); - StdMutableStatusDetail statusDetailIn = new StdMutableStatusDetail(); - StdMutableMissingAttributeDetail mad = new StdMutableMissingAttributeDetail(); - mad.addAttributeValue(new StdAttributeValue<String>(DataTypes.DT_STRING.getId(), "PEPACTION")); - mad.addAttributeValue(new StdAttributeValue<String>(DataTypes.DT_INTEGER.getId(), "PDPACTION")); - mad.setAttributeId(XACML3.ID_ACTION_PURPOSE); - mad.setCategory(XACML3.ID_ATTRIBUTE_CATEGORY_ACTION); - mad.setDataTypeId(XACML3.ID_DATATYPE_STRING); - mad.setIssuer("an Issuer"); - statusDetailIn.addMissingAttributeDetail(mad); - status.setStatusDetail(statusDetailIn); - // create a single result object - StdMutableResult result = new StdMutableResult(status); - // set the decision - result.setDecision(Decision.INDETERMINATE); - // put the Result into the Response - response.add(result); - // create a new Result with a different Decision - status = new StdMutableStatus(StdStatusCode.STATUS_CODE_OK); - result = new StdMutableResult(status); - result.setDecision(Decision.DENY); - - StdMutableObligation obligation = new StdMutableObligation(); - obligation.setId(XACML3.ID_ACTION_IMPLIED_ACTION); - obligation.addAttributeAssignment(new StdMutableAttributeAssignment( - XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, - XACML3.ID_SUBJECT, - "obligation-issuer1", - new StdAttributeValue<String>(DataTypes.DT_STRING.getId(), "Test"))); - result.addObligation(obligation); - - StdMutableAdvice advice = new StdMutableAdvice(); - advice.setId(XACML3.ID_ACTION_IMPLIED_ACTION); - advice.addAttributeAssignment(new StdMutableAttributeAssignment( - XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, - XACML3.ID_SUBJECT, - "advice-issuer1", - new StdAttributeValue<String>(DataTypes.DT_STRING.getId(), "Test"))); - response.add(result); - - // The logic below exercises the callRest and takeAction methods in FindAction - // GET request - status = new StdMutableStatus(StdStatusCode.STATUS_CODE_OK); - result = new StdMutableResult(status); - result.setDecision(Decision.PERMIT); - - obligation = new StdMutableObligation(); - obligation.setId(XACML3.ID_ACTION_IMPLIED_ACTION); - obligation.addAttributeAssignment(new StdMutableAttributeAssignment( - XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, - new IdentifierImpl("performer"), - "obligation-issuer", - new StdAttributeValue<String>(DataTypes.DT_STRING.getId(), "PDPACTION"))); - - obligation.addAttributeAssignment(new StdMutableAttributeAssignment( - XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, - new IdentifierImpl("URL"), - "obligation-issuer", - new StdAttributeValue<String>(DataTypes.DT_STRING.getId(), "http://localhost:" + MOCK_SERVER_PORT))); - obligation.addAttributeAssignment(new StdMutableAttributeAssignment( - XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, - new IdentifierImpl("method"), - "obligation-issuer", - new StdAttributeValue<String>(DataTypes.DT_STRING.getId(), "GET"))); - obligation.addAttributeAssignment(new StdMutableAttributeAssignment( - XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, - new IdentifierImpl("headers"), - "obligation-issuer", - new StdAttributeValue<String>(DataTypes.DT_STRING.getId(), "foobar"))); - - - result.addObligation(obligation); - response.add(result); - - // POST request - status = new StdMutableStatus(StdStatusCode.STATUS_CODE_OK); - result = new StdMutableResult(status); - result.setDecision(Decision.PERMIT); - - obligation = new StdMutableObligation(); - obligation.setId(XACML3.ID_ACTION_IMPLIED_ACTION); - obligation.addAttributeAssignment(new StdMutableAttributeAssignment( - XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, - new IdentifierImpl("performer"), - "obligation-issuer", - new StdAttributeValue<String>(DataTypes.DT_STRING.getId(), "PDPACTION"))); - - obligation.addAttributeAssignment(new StdMutableAttributeAssignment( - XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, - new IdentifierImpl("URL"), - "obligation-issuer", - new StdAttributeValue<String>(DataTypes.DT_STRING.getId(), "http://localhost:" + MOCK_SERVER_PORT))); - obligation.addAttributeAssignment(new StdMutableAttributeAssignment( - XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, - new IdentifierImpl("method"), - "obligation-issuer", - new StdAttributeValue<String>(DataTypes.DT_STRING.getId(), "POST"))); - obligation.addAttributeAssignment(new StdMutableAttributeAssignment( - XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, - new IdentifierImpl("body"), - "obligation-issuer", - new StdAttributeValue<String>(DataTypes.DT_STRING.getId(), "http://localhost:" + MOCK_SERVER_PORT + "/foobar"))); - - result.addObligation(obligation); - response.add(result); - - //PUT request - status = new StdMutableStatus(StdStatusCode.STATUS_CODE_OK); - result = new StdMutableResult(status); - result.setDecision(Decision.PERMIT); - - obligation = new StdMutableObligation(); - obligation.setId(XACML3.ID_ACTION_IMPLIED_ACTION); - obligation.addAttributeAssignment(new StdMutableAttributeAssignment( - XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, - new IdentifierImpl("performer"), - "obligation-issuer", - new StdAttributeValue<String>(DataTypes.DT_STRING.getId(), "PDPACTION"))); - - obligation.addAttributeAssignment(new StdMutableAttributeAssignment( - XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, - new IdentifierImpl("URL"), - "obligation-issuer", - new StdAttributeValue<String>(DataTypes.DT_STRING.getId(), "http://localhost:" + MOCK_SERVER_PORT))); - obligation.addAttributeAssignment(new StdMutableAttributeAssignment( - XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, - new IdentifierImpl("method"), - "obligation-issuer", - new StdAttributeValue<String>(DataTypes.DT_STRING.getId(), "PUT"))); - obligation.addAttributeAssignment(new StdMutableAttributeAssignment( - XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, - new IdentifierImpl("body"), - "obligation-issuer", - new StdAttributeValue<String>(DataTypes.DT_STRING.getId(), "http://localhost:" + MOCK_SERVER_PORT + "/foobar"))); - - result.addObligation(obligation); - response.add(result); - - try { - assertTrue(action.run(response, request) != null); - } catch (Exception e) { - fail("operation failed, e="+e); - } - } + + /** + * Setup before test case execution. + * + * @throws Exception if any error occurs + */ + @Before + public void setUp() throws Exception { + new OnapFunctionDefinitionFactory(); + request = JSONRequest.load(xpathexamplefromspec); + + try { + XACMLProperties.reloadProperties(); + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/xacml.pdp.properties"); + XACMLProperties.getProperties(); + + assertTrue(true); + } catch (final Exception e) { + fail(); + + } + } + + + @Test + public final void testRun() { + final FindAction action = new FindAction(); + // fully-loaded multiple response + final StdMutableResponse response = new StdMutableResponse(); + // create a Status object + StdMutableStatus status = new StdMutableStatus(StdStatusCode.STATUS_CODE_MISSING_ATTRIBUTE); + status.setStatusMessage("some status message"); + final StdMutableStatusDetail statusDetailIn = new StdMutableStatusDetail(); + final StdMutableMissingAttributeDetail mad = new StdMutableMissingAttributeDetail(); + mad.addAttributeValue(new StdAttributeValue<String>(DataTypes.DT_STRING.getId(), "PEPACTION")); + mad.addAttributeValue(new StdAttributeValue<String>(DataTypes.DT_INTEGER.getId(), "PDPACTION")); + mad.setAttributeId(XACML3.ID_ACTION_PURPOSE); + mad.setCategory(XACML3.ID_ATTRIBUTE_CATEGORY_ACTION); + mad.setDataTypeId(XACML3.ID_DATATYPE_STRING); + mad.setIssuer("an Issuer"); + statusDetailIn.addMissingAttributeDetail(mad); + status.setStatusDetail(statusDetailIn); + // create a single result object + StdMutableResult result = new StdMutableResult(status); + // set the decision + result.setDecision(Decision.INDETERMINATE); + // put the Result into the Response + response.add(result); + // create a new Result with a different Decision + status = new StdMutableStatus(StdStatusCode.STATUS_CODE_OK); + result = new StdMutableResult(status); + result.setDecision(Decision.DENY); + + StdMutableObligation obligation = new StdMutableObligation(); + obligation.setId(XACML3.ID_ACTION_IMPLIED_ACTION); + obligation.addAttributeAssignment( + new StdMutableAttributeAssignment(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, XACML3.ID_SUBJECT, + "obligation-issuer1", new StdAttributeValue<String>(DataTypes.DT_STRING.getId(), "Test"))); + result.addObligation(obligation); + + final StdMutableAdvice advice = new StdMutableAdvice(); + advice.setId(XACML3.ID_ACTION_IMPLIED_ACTION); + advice.addAttributeAssignment( + new StdMutableAttributeAssignment(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, XACML3.ID_SUBJECT, + "advice-issuer1", new StdAttributeValue<String>(DataTypes.DT_STRING.getId(), "Test"))); + response.add(result); + + // The logic below exercises the callRest and takeAction methods in FindAction + // GET request + status = new StdMutableStatus(StdStatusCode.STATUS_CODE_OK); + result = new StdMutableResult(status); + result.setDecision(Decision.PERMIT); + + obligation = new StdMutableObligation(); + obligation.setId(XACML3.ID_ACTION_IMPLIED_ACTION); + obligation.addAttributeAssignment(new StdMutableAttributeAssignment(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, + new IdentifierImpl("performer"), "obligation-issuer", + new StdAttributeValue<String>(DataTypes.DT_STRING.getId(), "PDPACTION"))); + + obligation.addAttributeAssignment(new StdMutableAttributeAssignment(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, + new IdentifierImpl("URL"), "obligation-issuer", + new StdAttributeValue<String>(DataTypes.DT_STRING.getId(), "http://localhost:" + MOCK_SERVER_PORT))); + obligation.addAttributeAssignment( + new StdMutableAttributeAssignment(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, new IdentifierImpl("method"), + "obligation-issuer", new StdAttributeValue<String>(DataTypes.DT_STRING.getId(), "GET"))); + obligation.addAttributeAssignment( + new StdMutableAttributeAssignment(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, new IdentifierImpl("headers"), + "obligation-issuer", new StdAttributeValue<String>(DataTypes.DT_STRING.getId(), "foobar"))); + + + result.addObligation(obligation); + response.add(result); + + // POST request + status = new StdMutableStatus(StdStatusCode.STATUS_CODE_OK); + result = new StdMutableResult(status); + result.setDecision(Decision.PERMIT); + + obligation = new StdMutableObligation(); + obligation.setId(XACML3.ID_ACTION_IMPLIED_ACTION); + obligation.addAttributeAssignment(new StdMutableAttributeAssignment(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, + new IdentifierImpl("performer"), "obligation-issuer", + new StdAttributeValue<String>(DataTypes.DT_STRING.getId(), "PDPACTION"))); + + obligation.addAttributeAssignment(new StdMutableAttributeAssignment(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, + new IdentifierImpl("URL"), "obligation-issuer", + new StdAttributeValue<String>(DataTypes.DT_STRING.getId(), "http://localhost:" + MOCK_SERVER_PORT))); + obligation.addAttributeAssignment( + new StdMutableAttributeAssignment(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, new IdentifierImpl("method"), + "obligation-issuer", new StdAttributeValue<String>(DataTypes.DT_STRING.getId(), "POST"))); + obligation.addAttributeAssignment(new StdMutableAttributeAssignment(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, + new IdentifierImpl("body"), "obligation-issuer", new StdAttributeValue<String>( + DataTypes.DT_STRING.getId(), "http://localhost:" + MOCK_SERVER_PORT + "/foobar"))); + + result.addObligation(obligation); + response.add(result); + + // PUT request + status = new StdMutableStatus(StdStatusCode.STATUS_CODE_OK); + result = new StdMutableResult(status); + result.setDecision(Decision.PERMIT); + + obligation = new StdMutableObligation(); + obligation.setId(XACML3.ID_ACTION_IMPLIED_ACTION); + obligation.addAttributeAssignment(new StdMutableAttributeAssignment(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, + new IdentifierImpl("performer"), "obligation-issuer", + new StdAttributeValue<String>(DataTypes.DT_STRING.getId(), "PDPACTION"))); + + obligation.addAttributeAssignment(new StdMutableAttributeAssignment(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, + new IdentifierImpl("URL"), "obligation-issuer", + new StdAttributeValue<String>(DataTypes.DT_STRING.getId(), "http://localhost:" + MOCK_SERVER_PORT))); + obligation.addAttributeAssignment( + new StdMutableAttributeAssignment(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, new IdentifierImpl("method"), + "obligation-issuer", new StdAttributeValue<String>(DataTypes.DT_STRING.getId(), "PUT"))); + obligation.addAttributeAssignment(new StdMutableAttributeAssignment(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, + new IdentifierImpl("body"), "obligation-issuer", new StdAttributeValue<String>( + DataTypes.DT_STRING.getId(), "http://localhost:" + MOCK_SERVER_PORT + "/foobar"))); + + result.addObligation(obligation); + response.add(result); + + try { + assertTrue(action.run(response, request) != null); + } catch (final Exception e) { + fail("operation failed, e=" + e); + } + } } diff --git a/ONAP-PDP/src/test/java/org/onap/policy/xacml/pdp/ONAPPDPEngineFactoryTest.java b/ONAP-PDP/src/test/java/org/onap/policy/xacml/pdp/ONAPPDPEngineFactoryTest.java deleted file mode 100644 index 1bde7dd84..000000000 --- a/ONAP-PDP/src/test/java/org/onap/policy/xacml/pdp/ONAPPDPEngineFactoryTest.java +++ /dev/null @@ -1,86 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP-PDP - * ================================================================================ - * Copyright (C) 2017-2018 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.onap.policy.xacml.pdp; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import java.util.Properties; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import com.att.research.xacml.util.FactoryException; -import com.att.research.xacml.util.FactoryFinder; -import com.att.research.xacmlatt.pdp.eval.EvaluationContextFactory; - -@RunWith(PowerMockRunner.class) -public class ONAPPDPEngineFactoryTest { - @Test - public final void testNewEngine() { - ONAPPDPEngineFactory pdpEngine = new ONAPPDPEngineFactory(); - try { - assertTrue(pdpEngine.newEngine() != null); - } catch (Exception e) { - fail("operation failed, e=" + e); - } - } - - @Test - public final void testNewEngineProperties() { - ONAPPDPEngineFactory pdpEngine = new ONAPPDPEngineFactory(); - Properties properties = new Properties(); - try { - assertTrue(pdpEngine.newEngine(properties) != null); - } catch (Exception e) { - fail("operation failed, e=" + e); - } - } - - @PrepareForTest({EvaluationContextFactory.class, FactoryFinder.class}) - @Test(expected = FactoryException.class) - public void negTestEngine() throws FactoryException { - // Setup test data - PowerMockito.mockStatic(FactoryFinder.class); - PowerMockito.when(FactoryFinder.find(Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn(null); - - // Negative test factory - ONAPPDPEngineFactory factory = new ONAPPDPEngineFactory(); - factory.newEngine(); - fail("Expecting an exception."); - } - - @PrepareForTest({EvaluationContextFactory.class, FactoryFinder.class}) - @Test(expected = FactoryException.class) - public void negTestEngine2() throws FactoryException { - // Setup test data - PowerMockito.mockStatic(FactoryFinder.class); - PowerMockito.when(FactoryFinder.find(Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn(null); - - // Negative test factory - ONAPPDPEngineFactory factory = new ONAPPDPEngineFactory(); - Properties properties = new Properties(); - factory.newEngine(properties); - fail("Expecting an exception."); - } -} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/xacml/pdp/OnapPdpEngineFactoryTest.java b/ONAP-PDP/src/test/java/org/onap/policy/xacml/pdp/OnapPdpEngineFactoryTest.java new file mode 100644 index 000000000..d3ee544a5 --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/xacml/pdp/OnapPdpEngineFactoryTest.java @@ -0,0 +1,88 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * Copyright (C) 2017-2018 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.onap.policy.xacml.pdp; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import com.att.research.xacml.util.FactoryException; +import com.att.research.xacml.util.FactoryFinder; +import com.att.research.xacmlatt.pdp.eval.EvaluationContextFactory; + +import java.util.Properties; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +public class OnapPdpEngineFactoryTest { + @Test + public final void testNewEngine() { + final OnapPdpEngineFactory pdpEngine = new OnapPdpEngineFactory(); + try { + assertTrue(pdpEngine.newEngine() != null); + } catch (final Exception e) { + fail("operation failed, e=" + e); + } + } + + @Test + public final void testNewEngineProperties() { + final OnapPdpEngineFactory pdpEngine = new OnapPdpEngineFactory(); + final Properties properties = new Properties(); + try { + assertTrue(pdpEngine.newEngine(properties) != null); + } catch (final Exception e) { + fail("operation failed, e=" + e); + } + } + + @PrepareForTest({ EvaluationContextFactory.class, FactoryFinder.class }) + @Test(expected = FactoryException.class) + public void negTestEngine() throws FactoryException { + // Setup test data + PowerMockito.mockStatic(FactoryFinder.class); + PowerMockito.when(FactoryFinder.find(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(null); + + // Negative test factory + final OnapPdpEngineFactory factory = new OnapPdpEngineFactory(); + factory.newEngine(); + fail("Expecting an exception."); + } + + @PrepareForTest({ EvaluationContextFactory.class, FactoryFinder.class }) + @Test(expected = FactoryException.class) + public void negTestEngine2() throws FactoryException { + // Setup test data + PowerMockito.mockStatic(FactoryFinder.class); + PowerMockito.when(FactoryFinder.find(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(null); + + // Negative test factory + final OnapPdpEngineFactory factory = new OnapPdpEngineFactory(); + final Properties properties = new Properties(); + factory.newEngine(properties); + fail("Expecting an exception."); + } +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/xacml/pdp/ONAPPDPEngineTest.java b/ONAP-PDP/src/test/java/org/onap/policy/xacml/pdp/OnapPdpEngineTest.java index 6eb6e4cfc..08a84477e 100644 --- a/ONAP-PDP/src/test/java/org/onap/policy/xacml/pdp/ONAPPDPEngineTest.java +++ b/ONAP-PDP/src/test/java/org/onap/policy/xacml/pdp/OnapPdpEngineTest.java @@ -7,9 +7,9 @@ * 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. @@ -22,24 +22,26 @@ package org.onap.policy.xacml.pdp; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import org.junit.Test; -import org.mockito.Mockito; + import com.att.research.xacml.api.Request; import com.att.research.xacml.api.Response; import com.att.research.xacml.api.pdp.PDPException; import com.att.research.xacml.api.pdp.ScopeResolver; import com.att.research.xacmlatt.pdp.eval.EvaluationContextFactory; -public class ONAPPDPEngineTest { - @Test - public void testEngine() throws PDPException { - EvaluationContextFactory factory = Mockito.mock(EvaluationContextFactory.class); - ScopeResolver resolver = Mockito.mock(ScopeResolver.class); - ONAPPDPEngine engine = new ONAPPDPEngine(factory, resolver); - assertNotNull(engine); +import org.junit.Test; +import org.mockito.Mockito; + +public class OnapPdpEngineTest { + @Test + public void testEngine() throws PDPException { + final EvaluationContextFactory factory = Mockito.mock(EvaluationContextFactory.class); + final ScopeResolver resolver = Mockito.mock(ScopeResolver.class); + final OnapPdpEngine engine = new OnapPdpEngine(factory, resolver); + assertNotNull(engine); - Request pepRequest = Mockito.mock(Request.class); - Response response = engine.decide(pepRequest); - assertEquals(1, response.getResults().size()); - } + final Request pepRequest = Mockito.mock(Request.class); + final Response response = engine.decide(pepRequest); + assertEquals(1, response.getResults().size()); + } } diff --git a/ONAP-PDP/src/test/java/org/onap/policy/xacml/pdp/std/functions/FunctionDefinitionCustomRegexpMatchTest.java b/ONAP-PDP/src/test/java/org/onap/policy/xacml/pdp/std/functions/FunctionDefinitionCustomRegexpMatchTest.java index 5100dc7c5..da1759a22 100644 --- a/ONAP-PDP/src/test/java/org/onap/policy/xacml/pdp/std/functions/FunctionDefinitionCustomRegexpMatchTest.java +++ b/ONAP-PDP/src/test/java/org/onap/policy/xacml/pdp/std/functions/FunctionDefinitionCustomRegexpMatchTest.java @@ -7,9 +7,9 @@ * 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. @@ -17,12 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.xacml.pdp.std.functions; import static org.junit.Assert.assertEquals; -import java.util.ArrayList; -import java.util.List; -import org.junit.Test; + import com.att.research.xacml.api.Identifier; import com.att.research.xacml.api.XACML; import com.att.research.xacml.std.IdentifierImpl; @@ -32,23 +31,29 @@ import com.att.research.xacmlatt.pdp.policy.ExpressionResult; import com.att.research.xacmlatt.pdp.policy.FunctionArgument; import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + public class FunctionDefinitionCustomRegexpMatchTest { - @Test - public final void testRegexp() { - // Setup - String testVal = "testVal"; - String testId = "function:testId"; - IdentifierImpl testFnId = new IdentifierImpl(testId); - Identifier identifier = XACML.ID_DATATYPE_STRING; - StdAttributeValue<String> attValue = new StdAttributeValue<String>(identifier, testVal); - FunctionArgument fArg = new FunctionArgumentAttributeValue(attValue); - List<FunctionArgument> listFA = new ArrayList<FunctionArgument>(); - listFA.add(fArg); - listFA.add(fArg); - - // Try a match - FunctionDefinitionCustomRegexpMatch<String> regexpMatch = new FunctionDefinitionCustomRegexpMatch<String>(testFnId, DataTypes.DT_STRING); - ExpressionResult result = regexpMatch.evaluate(null, listFA); - assertEquals(result.getStatus().isOk(), true); - } + @Test + public final void testRegexp() { + // Setup + final String testVal = "testVal"; + final String testId = "function:testId"; + final IdentifierImpl testFnId = new IdentifierImpl(testId); + final Identifier identifier = XACML.ID_DATATYPE_STRING; + final StdAttributeValue<String> attValue = new StdAttributeValue<String>(identifier, testVal); + final FunctionArgument fArg = new FunctionArgumentAttributeValue(attValue); + final List<FunctionArgument> listFa = new ArrayList<FunctionArgument>(); + listFa.add(fArg); + listFa.add(fArg); + + // Try a match + final FunctionDefinitionCustomRegexpMatch<String> regexpMatch = + new FunctionDefinitionCustomRegexpMatch<String>(testFnId, DataTypes.DT_STRING); + final ExpressionResult result = regexpMatch.evaluate(null, listFa); + assertEquals(result.getStatus().isOk(), true); + } } diff --git a/ONAP-PDP/src/test/java/org/onap/policy/xacml/pdp/std/functions/PolicyListTest.java b/ONAP-PDP/src/test/java/org/onap/policy/xacml/pdp/std/functions/PolicyListTest.java index 17f509da4..ccab70418 100644 --- a/ONAP-PDP/src/test/java/org/onap/policy/xacml/pdp/std/functions/PolicyListTest.java +++ b/ONAP-PDP/src/test/java/org/onap/policy/xacml/pdp/std/functions/PolicyListTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PDP * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -17,47 +17,49 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.xacml.pdp.std.functions; -import static org.junit.Assert.*; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import org.junit.Before; import org.junit.Test; public class PolicyListTest { - @Before - public void setUp() throws Exception { - PolicyList.addPolicyID("Test"); - } - - @Test - public final void testGetpolicyList() { - try{ - assertTrue(PolicyList.getpolicyList().size() ==1); - }catch(Exception e){ - fail("operation failed, e="+e); - } - } - - @Test - public final void testAddPolicyID() { - try{ - PolicyList.addPolicyID("Test"); - assertTrue(PolicyList.getpolicyList().size() == 1); - }catch(Exception e){ - fail("operation failed, e="+e); - } - } - - @Test - public final void testClearPolicyList() { - try{ - PolicyList.clearPolicyList(); - assertTrue(PolicyList.getpolicyList().size() == 0); - }catch(Exception e){ - fail("operation failed, e="+e); - } - } + @Before + public void setUp() throws Exception { + PolicyList.addPolicyId("Test"); + } + + @Test + public final void testGetpolicyList() { + try { + assertTrue(PolicyList.getpolicyList().size() == 1); + } catch (final Exception e) { + fail("operation failed, e=" + e); + } + } + + @Test + public final void testAddPolicyId() { + try { + PolicyList.addPolicyId("Test"); + assertTrue(PolicyList.getpolicyList().size() == 1); + } catch (final Exception e) { + fail("operation failed, e=" + e); + } + } + + @Test + public final void testClearPolicyList() { + try { + PolicyList.clearPolicyList(); + assertTrue(PolicyList.getpolicyList().size() == 0); + } catch (final Exception e) { + fail("operation failed, e=" + e); + } + } } |