summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorKrishnajinka <kris.jinka@samsung.com>2018-07-24 14:23:06 +0900
committerKrishnajinka <kris.jinka@samsung.com>2018-07-25 10:20:34 +0900
commit4553d7ab7bde46adcca13ee00682b8d8591cbb94 (patch)
tree4885afbe72c13e57b728b47dc69e656baf0dc824
parent8cf5ed300190ab386d95758e6d4be6c38e67123d (diff)
Fix sonar issue about nested stmts
Refactor code to not nest more than 3 condition or loop stmts in policy PolicyEngineUtils. Rework based on review comments Issue-ID: POLICY-1003 Change-Id: I95fcfa0f99c517c02357c85ca39cd2f934e8da4d Signed-off-by: Krishnajinka <kris.jinka@samsung.com>
-rw-r--r--BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsPush.java198
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java48
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClientImpl.java341
3 files changed, 306 insertions, 281 deletions
diff --git a/BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsPush.java b/BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsPush.java
index 716b8ec53..b8706bb9b 100644
--- a/BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsPush.java
+++ b/BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsPush.java
@@ -3,6 +3,7 @@
* ONAP Policy Engine
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -424,27 +425,9 @@ public class BrmsPush {
}
// Check User Specific values.
if ("$controller:".equals(key)) {
- try {
- final PEDependency dependency = PolicyUtils.jsonStringToObject(value, PEDependency.class);
- userControllerName = key.replaceFirst("$controller:", "");
- LOGGER.info("addRule: userControllerName - " + userControllerName + ", dependency: - "
- + dependency);
- addToGroup(userControllerName, dependency);
- } catch (final Exception e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while resolving Controller: " + e);
- }
-
+ userControllerName = getUserControllerName(key, value);
} else if ("$dependency$".equals(key) && value.startsWith("[") && value.endsWith("]")) {
- value = value.substring(1, value.length() - 1).trim();
- final List<String> dependencyStrings = Arrays.asList(value.split(Pattern.quote("},{")));
- for (final String dependencyString : dependencyStrings) {
- try {
- userDependencies.add(PolicyUtils.jsonStringToObject(dependencyString, PEDependency.class));
- } catch (final Exception e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while resolving Dependencies: "
- + e);
- }
- }
+ updateUserDependencies(userDependencies, value);
}
}
if (userControllerName != null) {
@@ -479,6 +462,35 @@ public class BrmsPush {
}
}
+ private String getUserControllerName(String key, String value) {
+ String userControllerName = null;
+ // Check User Specific values.
+ try {
+ final PEDependency dependency = PolicyUtils.jsonStringToObject(value, PEDependency.class);
+ userControllerName = key.replaceFirst("$controller:", "");
+ LOGGER.info("addRule: userControllerName - " + userControllerName + ", dependency: - "
+ + dependency);
+ addToGroup(userControllerName, dependency);
+ } catch (final Exception e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while resolving Controller: " + e);
+ }
+ return userControllerName;
+ }
+
+ private void updateUserDependencies(ArrayList<PEDependency> userDependencies, String value) {
+ //update the user dependencies supplied as parameter to this method
+ value = value.substring(1, value.length() - 1).trim();
+ final List<String> dependencyStrings = Arrays.asList(value.split(Pattern.quote("},{")));
+ for (final String dependencyString : dependencyStrings) {
+ try {
+ userDependencies.add(PolicyUtils.jsonStringToObject(dependencyString, PEDependency.class));
+ } catch (final Exception e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while resolving Dependencies: "
+ + e);
+ }
+ }
+ }
+
private void syncGroupInfo() {
// Sync DB to JMemory.
final EntityTransaction et = em.getTransaction();
@@ -624,45 +636,49 @@ public class BrmsPush {
try (JarFile jar = new JarFile(jarFileName)) {
final Enumeration<?> enumEntries = jar.entries();
while (enumEntries.hasMoreElements()) {
- final JarEntry jarEntry = (JarEntry) enumEntries.nextElement();
- File file = null;
- final String fileName = jarEntry.getName().substring(jarEntry.getName().lastIndexOf("/") + 1);
- if (jarEntry.getName().endsWith(".drl")) {
- final String path = PROJECTSLOCATION + File.separator + artifactId + File.separator + "src"
- + File.separator + "main" + File.separator + RESOURCES + File.separator + RULES;
- new File(path).mkdirs();
- if (syncFlag && policyMap.containsKey(fileName.replace(".drl", ""))) {
- file = new File(path + File.separator + fileName);
- } else {
- file = new File(path + File.separator + fileName);
- }
- } else if (jarEntry.getName().endsWith(POM_XML_FILE)) {
- final String path = PROJECTSLOCATION + File.separator + artifactId;
- new File(path).mkdirs();
- file = new File(path + File.separator + fileName);
- } else if (jarEntry.getName().endsWith(KMODULE_XML_FILE)) {
- final String path = PROJECTSLOCATION + File.separator + artifactId + File.separator + "src"
- + File.separator + "main" + File.separator + RESOURCES + File.separator + META_INF;
- new File(path).mkdirs();
- file = new File(path + File.separator + fileName);
- }
- if (file != null) {
- try (InputStream is = jar.getInputStream(jarEntry);
- FileOutputStream fos = new FileOutputStream(file)) {
- while (is.available() > 0) {
- fos.write(is.read());
- }
- LOGGER.info(fileName + " Created..");
- } catch (final IOException e) {
- LOGGER.info("exception Occured" + e);
- }
- }
+ parseJarContents(artifactId, jar, enumEntries);
}
} catch (final IOException e) {
LOGGER.info("exception Occured" + e);
}
}
+ private void parseJarContents(String artifactId, JarFile jar, Enumeration<?> enumEntries) {
+ final JarEntry jarEntry = (JarEntry) enumEntries.nextElement();
+ File file = null;
+ final String fileName = jarEntry.getName().substring(jarEntry.getName().lastIndexOf("/") + 1);
+ if (jarEntry.getName().endsWith(".drl")) {
+ final String path = PROJECTSLOCATION + File.separator + artifactId + File.separator + "src"
+ + File.separator + "main" + File.separator + RESOURCES + File.separator + RULES;
+ new File(path).mkdirs();
+ if (syncFlag && policyMap.containsKey(fileName.replace(".drl", ""))) {
+ file = new File(path + File.separator + fileName);
+ } else {
+ file = new File(path + File.separator + fileName);
+ }
+ } else if (jarEntry.getName().endsWith(POM_XML_FILE)) {
+ final String path = PROJECTSLOCATION + File.separator + artifactId;
+ new File(path).mkdirs();
+ file = new File(path + File.separator + fileName);
+ } else if (jarEntry.getName().endsWith(KMODULE_XML_FILE)) {
+ final String path = PROJECTSLOCATION + File.separator + artifactId + File.separator + "src"
+ + File.separator + "main" + File.separator + RESOURCES + File.separator + META_INF;
+ new File(path).mkdirs();
+ file = new File(path + File.separator + fileName);
+ }
+ if (file != null) {
+ try (InputStream is = jar.getInputStream(jarEntry);
+ FileOutputStream fos = new FileOutputStream(file)) {
+ while (is.available() > 0) {
+ fos.write(is.read());
+ }
+ LOGGER.info(fileName + " Created..");
+ } catch (final IOException e) {
+ LOGGER.info("exception Occured" + e);
+ }
+ }
+ }
+
private NexusArtifact getLatestArtifactFromNexus(final String selectedName) {
final List<NexusArtifact> artifacts = getArtifactFromNexus(selectedName, null);
int bigNum = 0;
@@ -771,41 +787,8 @@ public class BrmsPush {
LOGGER.error("Error while starting Transaction " + e);
}
if (!modifiedGroups.isEmpty()) {
- Boolean flag = false;
- for (final Map.Entry<String, String> entry : modifiedGroups.entrySet()) {
- InvocationResult result = null;
- final String group = entry.getKey();
- try {
- LOGGER.info("PushRules: ModifiedGroups, Key: " + group + ", Value: " + entry.getValue());
- final InvocationRequest request = new DefaultInvocationRequest();
- setVersion(group);
- createPom(group);
- request.setPomFile(new File(
- PROJECTSLOCATION + File.separator + getArtifactId(group) + File.separator + POM_XML_FILE));
- request.setGoals(Arrays.asList(GOALS));
- final Invoker invoker = new DefaultInvoker();
- result = invoker.execute(request);
- if (result.getExecutionException() != null) {
- LOGGER.error(result.getExecutionException());
- } else if (result.getExitCode() != 0) {
- LOGGER.error("Maven Invocation failure..!");
- }
- } catch (final Exception e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation issue for "
- + getArtifactId(group) + e.getMessage(), e);
- }
- if (result != null && result.getExitCode() == 0) {
- LOGGER.info("Build Completed..!");
- if (createFlag) {
- addNotification(group, "create");
- } else {
- addNotification(group, entry.getValue());
- }
- flag = true;
- } else {
- throw new PolicyException(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation failure!");
- }
- }
+ Boolean flag;
+ flag = buildAndGenerateJarFile();
if (flag) {
sendNotification(controllers);
}
@@ -828,6 +811,45 @@ public class BrmsPush {
getNameAndSetRemove(controllerName, name);
}
+ private Boolean buildAndGenerateJarFile() throws PolicyException {
+ Boolean flag = false;
+ for (final Map.Entry<String, String> entry : modifiedGroups.entrySet()) {
+ InvocationResult result = null;
+ final String group = entry.getKey();
+ try {
+ LOGGER.info("PushRules: ModifiedGroups, Key: " + group + ", Value: " + entry.getValue());
+ final InvocationRequest request = new DefaultInvocationRequest();
+ setVersion(group);
+ createPom(group);
+ request.setPomFile(new File(
+ PROJECTSLOCATION + File.separator + getArtifactId(group) + File.separator + POM_XML_FILE));
+ request.setGoals(Arrays.asList(GOALS));
+ final Invoker invoker = new DefaultInvoker();
+ result = invoker.execute(request);
+ if (result.getExecutionException() != null) {
+ LOGGER.error(result.getExecutionException());
+ } else if (result.getExitCode() != 0) {
+ LOGGER.error("Maven Invocation failure..!");
+ }
+ } catch (final Exception e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation issue for "
+ + getArtifactId(group) + e.getMessage(), e);
+ }
+ if (result != null && result.getExitCode() == 0) {
+ LOGGER.info("Build Completed..!");
+ if (createFlag) {
+ addNotification(group, "create");
+ } else {
+ addNotification(group, entry.getValue());
+ }
+ flag = true;
+ } else {
+ throw new PolicyException(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation failure!");
+ }
+ }
+ return flag;
+ }
+
private String getGroupName(final String name) {
if (policyMap.containsKey(name)) {
return policyMap.get(name);
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java
index 6b980b98d..1b786ed6a 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java
@@ -424,30 +424,6 @@ public class PolicyDBDao {
return true;
}
- private void notifyOthers(long entityId,String entityType){
- notifyOthers(entityId,entityType,null);
- }
-
- private void notifyOthers(long entityId, String entityType, String newGroupId){
- logger.debug("notifyOthers(long entityId, String entityType, long newGroupId) as notifyOthers("+entityId+","+entityType+","+newGroupId+") called");
- LinkedList<Thread> notifyThreads = new LinkedList<>();
-
- //we're going to run notifications in parallel threads to speed things up
- for(Object obj : otherServers){
- Thread newNotifyThread = new Thread(new NotifyOtherThread(obj, entityId, entityType, newGroupId));
- newNotifyThread.start();
- notifyThreads.add(newNotifyThread);
- }
- //we want to wait for all notifications to complete or timeout before we unlock the interface and allow more changes
- for(Thread t : notifyThreads){
- try {
- t.join();
- } catch (Exception e) {
- logger.warn("Could not join a notifcation thread" + e);
- }
- }
- }
-
private class NotifyOtherThread implements Runnable {
public NotifyOtherThread(Object obj, long entityId, String entityType, String newGroupId){
this.obj = obj;
@@ -2645,6 +2621,30 @@ public class PolicyDBDao {
this.pdpId = pdp.getPdpKey();
}
}
+
+ private void notifyOthers(long entityId,String entityType){
+ notifyOthers(entityId,entityType,null);
+ }
+
+ private void notifyOthers(long entityId, String entityType, String newGroupId){
+ logger.debug("notifyOthers(long entityId, String entityType, long newGroupId) as notifyOthers("+entityId+","+entityType+","+newGroupId+") called");
+ LinkedList<Thread> notifyThreads = new LinkedList<>();
+
+ //we're going to run notifications in parallel threads to speed things up
+ for(Object obj : otherServers){
+ Thread newNotifyThread = new Thread(new NotifyOtherThread(obj, entityId, entityType, newGroupId));
+ newNotifyThread.start();
+ notifyThreads.add(newNotifyThread);
+ }
+ //we want to wait for all notifications to complete or timeout before we unlock the interface and allow more changes
+ for(Thread t : notifyThreads){
+ try {
+ t.join();
+ } catch (Exception e) {
+ logger.warn("Could not join a notifcation thread" + e);
+ }
+ }
+ }
}
private PolicyDBDao(){
diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClientImpl.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClientImpl.java
index 732183d47..5c46c76f7 100644
--- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClientImpl.java
+++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClientImpl.java
@@ -3,6 +3,7 @@
* PolicyEngineUtils
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -42,173 +43,175 @@ import org.onap.aaf.cadi.principal.UnAuthPrincipal;
*
*/
public class AAFPolicyClientImpl implements AAFPolicyClient{
- private static Logger logger = Logger.getLogger(AAFPolicyClientImpl.class.getName());
-
- private static final String ENVIRONMENT = "ENVIRONMENT";
-
- // Warning Please don't Change these Values. Confirm with AAF team.
- private static final String DEVL_AAF_URL = "";
- private static final String TEST_AAF_URL = "";
- private static final String PROD_AAF_URL = "";
- private static final String DEFAULT_AFT_LATITUDE = "32.780140";
- private static final String DEFAULT_AFT_LONGITUDE = "-96.800451";
- private static final String TEST_AFT_ENVIRONMENT = "AFTUAT";
- private static final String PROD_AFT_ENVIRONMENT = "AFTPRD";
- private static final String DEFAULT_AAF_USER_EXPIRES = Integer.toString(5*60000); // 5 minutes for found items to live in cache
- private static final String DEFAULT_AAF_HIGH_COUNT = Integer.toString(400); // Maximum number of items in Cache
-
- private static AAFPolicyClientImpl instance = null;
-
- private static Properties props = new Properties();
- private static AAFCon<?> aafCon = null;
- private static AAFLurPerm aafLurPerm = null;
- private static AAFAuthn<?> aafAuthn = null;
- private static PropAccess access = null;
-
- private AAFPolicyClientImpl(Properties properties) throws AAFPolicyException{
- setup(properties);
- }
-
- /**
- * Gets the instance of the AAFClient instance. Needs Proper properties with CLIENT_ID, CLIENT_KEY and ENVIRONMENT
- *
- * @param properties Properties with CLIENT_ID, CLIENT_KEY and ENVIRONMENT
- * @return AAFClient instance.
- * @throws AAFPolicyException Exceptions.
- */
- public static synchronized AAFPolicyClientImpl getInstance(Properties properties) throws AAFPolicyException{
- if(instance == null) {
- logger.info("Creating AAFClient Instance ");
- instance = new AAFPolicyClientImpl(properties);
- }
- return instance;
- }
-
- // To set Property values && Connections.
- private static void setup(Properties properties) throws AAFPolicyException {
- if(properties!=null && !properties.isEmpty()){
- props = System.getProperties();
- props.setProperty("AFT_LATITUDE", properties.getProperty("AFT_LATITUDE", DEFAULT_AFT_LATITUDE));
- props.setProperty("AFT_LONGITUDE", properties.getProperty("AFT_LONGITUDE", DEFAULT_AFT_LONGITUDE));
- String aftEnv = TEST_AFT_ENVIRONMENT;
- props.setProperty("aaf_id",properties.getProperty("aaf_id", "aafID"));
- props.setProperty("aaf_password", properties.getProperty("aaf_password", "aafPass"));
- if(properties.containsKey(Config.AAF_URL)){
- // if given a value in properties file.
- props.setProperty(Config.AAF_URL, properties.getProperty(Config.AAF_URL));
- }else{
- // Set Default values.
- if(properties.getProperty(ENVIRONMENT, "DEVL").equalsIgnoreCase(AAFEnvironment.TEST.toString())){
- props.setProperty(Config.AAF_URL, TEST_AAF_URL);
- }else if(properties.getProperty(ENVIRONMENT, "DEVL").equalsIgnoreCase(AAFEnvironment.PROD.toString())){
- props.setProperty(Config.AAF_URL, PROD_AAF_URL);
- aftEnv = PROD_AFT_ENVIRONMENT;
- }else{
- props.setProperty(Config.AAF_URL, DEVL_AAF_URL);
- }
- }
- props.setProperty("AFT_ENVIRONMENT", properties.getProperty("AFT_ENVIRONMENT", aftEnv));
- props.setProperty(Config.AAF_USER_EXPIRES, properties.getProperty(Config.AAF_USER_EXPIRES, DEFAULT_AAF_USER_EXPIRES));
- props.setProperty(Config.AAF_HIGH_COUNT, properties.getProperty(Config.AAF_HIGH_COUNT, DEFAULT_AAF_HIGH_COUNT));
- }else{
- logger.error("Required Property value is missing : " + ENVIRONMENT);
- throw new AAFPolicyException("Required Property value is missing : " + ENVIRONMENT);
- }
- access = new PolicyAccess(props, Level.valueOf(properties.getProperty("AAF_LOG_LEVEL", Level.ERROR.toString())));
- setUpAAF();
- }
-
- /**
- * Updates the Properties file in case if required.
- *
- * @param properties Properties with CLIENT_ID, CLIENT_KEY and ENVIRONMENT
- * @throws AAFPolicyException exceptions if any.
- */
- @Override
- public void updateProperties(Properties properties) throws AAFPolicyException{
- setup(properties);
- }
-
- /**
- * Checks the Authentication and Permissions for the given values.
- *
- * @param mechID MechID or ATT ID must be registered under the Name space.
- * @param pass Password pertaining to the MechID or ATTID.
- * @param type Permissions Type.
- * @param instance Permissions Instance.
- * @param action Permissions Action.
- * @return
- */
- @Override
- public boolean checkAuthPerm(String mechID, String pass, String type, String instance, String action){
- return checkAuth(mechID, pass) && checkPerm(mechID, pass, type, instance, action);
- }
-
- /**
- * Checks the Authentication of the UserName and Password Given.
- *
- * @param userName UserName or MechID
- * @param pass Password.
- * @return True or False.
- */
- @Override
- public boolean checkAuth(String userName, String pass){
- if(aafAuthn!=null){
- try {
- int i=0;
- do{
- if(aafAuthn.validate(userName, pass)==null){
- return true;
- }
- i++;
- }while(i<2);
- } catch (Exception e) {
- logger.error(e.getMessage() + e);
- }
- }
- return false;
- }
-
- /**
- * Checks Permissions for the given UserName, Password and Type, Instance Action.
- *
- * @param userName UserName or MechID
- * @param pass Password.
- * @param type Permissions Type.
- * @param instance Permissions Instance.
- * @param action Permissions Action.
- * @return True or False.
- */
- @Override
- public boolean checkPerm(String userName, String pass, String type, String instance, String action){
- int i =0;
- Boolean result= false;
- do{
- if(aafCon!=null && aafLurPerm !=null){
- try {
- aafCon.basicAuth(userName, pass);
- AAFPermission perm = new AAFPermission(type, instance, action);
- final Principal p = new UnAuthPrincipal(userName);
- result = aafLurPerm.fish(p, perm);
- } catch (CadiException e) {
- logger.error(e.getMessage() + e);
- aafLurPerm.destroy();
- }
- }
- i++;
- }while(i<2 && !result); // Try once more to check if this can be passed. AAF has some issues.
- return result;
- }
-
- private static boolean setUpAAF(){
- try {
- aafCon = new AAFConHttp(access,new PropertyLocator("https://aaf-onap-beijing-test.osaaf.org:8100"));
- aafLurPerm = aafCon.newLur();
- aafAuthn = aafCon.newAuthn(aafLurPerm);
- return true;
- } catch (Exception e) {
- logger.error("Error while setting up AAF Connection " + e.getMessage() + e);
- return false;
- }
- }
+ private static Logger logger = Logger.getLogger(AAFPolicyClientImpl.class.getName());
+
+ private static final String ENVIRONMENT = "ENVIRONMENT";
+
+ // Warning Please don't Change these Values. Confirm with AAF team.
+ private static final String DEVL_AAF_URL = "";
+ private static final String TEST_AAF_URL = "";
+ private static final String PROD_AAF_URL = "";
+ private static final String DEFAULT_AFT_LATITUDE = "32.780140";
+ private static final String DEFAULT_AFT_LONGITUDE = "-96.800451";
+ private static final String TEST_AFT_ENVIRONMENT = "AFTUAT";
+ private static final String PROD_AFT_ENVIRONMENT = "AFTPRD";
+ private static final String DEFAULT_AAF_USER_EXPIRES = Integer.toString(5*60000); // 5 minutes for found items to live in cache
+ private static final String DEFAULT_AAF_HIGH_COUNT = Integer.toString(400); // Maximum number of items in Cache
+
+ private static AAFPolicyClientImpl instance = null;
+
+ private static Properties props = new Properties();
+ private static AAFCon<?> aafCon = null;
+ private static AAFLurPerm aafLurPerm = null;
+ private static AAFAuthn<?> aafAuthn = null;
+ private static PropAccess access = null;
+
+ private AAFPolicyClientImpl(Properties properties) throws AAFPolicyException{
+ setup(properties);
+ }
+
+ /**
+ * Gets the instance of the AAFClient instance. Needs Proper properties with CLIENT_ID, CLIENT_KEY and ENVIRONMENT
+ *
+ * @param properties Properties with CLIENT_ID, CLIENT_KEY and ENVIRONMENT
+ * @return AAFClient instance.
+ * @throws AAFPolicyException Exceptions.
+ */
+ public static synchronized AAFPolicyClientImpl getInstance(Properties properties) throws AAFPolicyException{
+ if(instance == null) {
+ logger.info("Creating AAFClient Instance ");
+ instance = new AAFPolicyClientImpl(properties);
+ }
+ return instance;
+ }
+
+ // To set Property values && Connections.
+ private static void setup(Properties properties) throws AAFPolicyException {
+ if(properties!=null && !properties.isEmpty()){
+ props = System.getProperties();
+ props.setProperty("AFT_LATITUDE", properties.getProperty("AFT_LATITUDE", DEFAULT_AFT_LATITUDE));
+ props.setProperty("AFT_LONGITUDE", properties.getProperty("AFT_LONGITUDE", DEFAULT_AFT_LONGITUDE));
+ String aftEnv = TEST_AFT_ENVIRONMENT;
+ props.setProperty("aaf_id",properties.getProperty("aaf_id", "aafID"));
+ props.setProperty("aaf_password", properties.getProperty("aaf_password", "aafPass"));
+ if(properties.containsKey(Config.AAF_URL)){
+ // if given a value in properties file.
+ props.setProperty(Config.AAF_URL, properties.getProperty(Config.AAF_URL));
+ }else{
+ // Set Default values.
+ if(properties.getProperty(ENVIRONMENT, "DEVL").equalsIgnoreCase(AAFEnvironment.TEST.toString())){
+ props.setProperty(Config.AAF_URL, TEST_AAF_URL);
+ }else if(properties.getProperty(ENVIRONMENT, "DEVL").equalsIgnoreCase(AAFEnvironment.PROD.toString())){
+ props.setProperty(Config.AAF_URL, PROD_AAF_URL);
+ aftEnv = PROD_AFT_ENVIRONMENT;
+ }else{
+ props.setProperty(Config.AAF_URL, DEVL_AAF_URL);
+ }
+ }
+ props.setProperty("AFT_ENVIRONMENT", properties.getProperty("AFT_ENVIRONMENT", aftEnv));
+ props.setProperty(Config.AAF_USER_EXPIRES, properties.getProperty(Config.AAF_USER_EXPIRES, DEFAULT_AAF_USER_EXPIRES));
+ props.setProperty(Config.AAF_HIGH_COUNT, properties.getProperty(Config.AAF_HIGH_COUNT, DEFAULT_AAF_HIGH_COUNT));
+ }else{
+ logger.error("Required Property value is missing : " + ENVIRONMENT);
+ throw new AAFPolicyException("Required Property value is missing : " + ENVIRONMENT);
+ }
+ access = new PolicyAccess(props, Level.valueOf(properties.getProperty("AAF_LOG_LEVEL", Level.ERROR.toString())));
+ setUpAAF();
+ }
+
+ /**
+ * Updates the Properties file in case if required.
+ *
+ * @param properties Properties with CLIENT_ID, CLIENT_KEY and ENVIRONMENT
+ * @throws AAFPolicyException exceptions if any.
+ */
+ @Override
+ public void updateProperties(Properties properties) throws AAFPolicyException{
+ setup(properties);
+ }
+
+ /**
+ * Checks the Authentication and Permissions for the given values.
+ *
+ * @param mechID MechID or ATT ID must be registered under the Name space.
+ * @param pass Password pertaining to the MechID or ATTID.
+ * @param type Permissions Type.
+ * @param instance Permissions Instance.
+ * @param action Permissions Action.
+ * @return
+ */
+ @Override
+ public boolean checkAuthPerm(String mechID, String pass, String type, String instance, String action){
+ return checkAuth(mechID, pass) && checkPerm(mechID, pass, type, instance, action);
+ }
+
+ /**
+ * Checks the Authentication of the UserName and Password Given.
+ *
+ * @param userName UserName or MechID
+ * @param pass Password.
+ * @return True or False.
+ */
+ @Override
+ public boolean checkAuth(String userName, String pass){
+ if (aafAuthn == null) {
+ return false;
+ }
+ try {
+ int i=0;
+ do{
+ if(aafAuthn.validate(userName, pass)==null){
+ return true;
+ }
+ i++;
+ }while(i<2);
+ } catch (Exception e) {
+ logger.error(e.getMessage() + e);
+ }
+
+ return false;
+ }
+
+ /**
+ * Checks Permissions for the given UserName, Password and Type, Instance Action.
+ *
+ * @param userName UserName or MechID
+ * @param pass Password.
+ * @param type Permissions Type.
+ * @param instance Permissions Instance.
+ * @param action Permissions Action.
+ * @return True or False.
+ */
+ @Override
+ public boolean checkPerm(String userName, String pass, String type, String instance, String action){
+ int i =0;
+ Boolean result= false;
+ do{
+ if(aafCon!=null && aafLurPerm !=null){
+ try {
+ aafCon.basicAuth(userName, pass);
+ AAFPermission perm = new AAFPermission(type, instance, action);
+ final Principal p = new UnAuthPrincipal(userName);
+ result = aafLurPerm.fish(p, perm);
+ } catch (CadiException e) {
+ logger.error(e.getMessage() + e);
+ aafLurPerm.destroy();
+ }
+ }
+ i++;
+ }while(i<2 && !result); // Try once more to check if this can be passed. AAF has some issues.
+ return result;
+ }
+
+ private static boolean setUpAAF(){
+ try {
+ aafCon = new AAFConHttp(access,new PropertyLocator("https://aaf-onap-beijing-test.osaaf.org:8100"));
+ aafLurPerm = aafCon.newLur();
+ aafAuthn = aafCon.newAuthn(aafLurPerm);
+ return true;
+ } catch (Exception e) {
+ logger.error("Error while setting up AAF Connection " + e.getMessage() + e);
+ return false;
+ }
+ }
}