diff options
Diffstat (limited to 'PolicyEngineUtils/src/main/java/org/onap/policy/utils')
13 files changed, 577 insertions, 578 deletions
diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFEnvironment.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFEnvironment.java index 1fccabcbd..e1849f06b 100644 --- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFEnvironment.java +++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFEnvironment.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * PolicyEngineUtils * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.utils; public enum AAFEnvironment { - /* - * Enumeration for the Resource Node Naming. Add here if required. - */ - DEVL, - TEST, - PROD + /* + * Enumeration for the Resource Node Naming. Add here if required. + */ + DEVL, TEST, PROD } diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClient.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClient.java index e560d0ecc..236f01eff 100644 --- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClient.java +++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClient.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * PolicyEngineUtils * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.utils; import java.lang.reflect.Method; @@ -24,17 +25,29 @@ import java.util.Properties; public interface AAFPolicyClient { - public boolean checkAuth(String userName, String pass); - public void updateProperties(Properties properties) throws AAFPolicyException; - public boolean checkAuthPerm(String mechID, String pass, String type, String instance, String action); - public boolean checkPerm(String userName, String pass, String type, String instance, String action); - public static AAFPolicyClient getInstance(Properties properties) throws AAFPolicyException{ - try { - Class<?> aafPolicyClient = Class.forName(properties.getProperty("aafClient.impl.className", AAFPolicyClientImpl.class.getName())); - Method method = aafPolicyClient.getMethod("getInstance", Properties.class); - return (AAFPolicyClient) method.invoke(null, properties); - } catch (Exception e) { - throw new AAFPolicyException(e); - } - } + public boolean checkAuth(String userName, String pass); + + public void updateProperties(Properties properties) throws AAFPolicyException; + + public boolean checkAuthPerm(String mechID, String pass, String type, String instance, String action); + + public boolean checkPerm(String userName, String pass, String type, String instance, String action); + + /** + * getInstance. + * + * @param properties Properties + * @return AAFPolicyClient + * @throws AAFPolicyException AAFPolicyException + */ + public static AAFPolicyClient getInstance(Properties properties) throws AAFPolicyException { + try { + Class<?> aafPolicyClient = Class + .forName(properties.getProperty("aafClient.impl.className", AAFPolicyClientImpl.class.getName())); + Method method = aafPolicyClient.getMethod("getInstance", Properties.class); + return (AAFPolicyClient) method.invoke(null, properties); + } catch (Exception e) { + throw new AAFPolicyException(e); + } + } } 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 1513507ca..fcdc7e9f8 100644 --- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClientImpl.java +++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClientImpl.java @@ -2,15 +2,15 @@ * ============LICENSE_START======================================================= * PolicyEngineUtils * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. * 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. @@ -18,6 +18,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.utils; import java.security.Principal; @@ -38,7 +39,7 @@ import org.onap.aaf.cadi.principal.UnAuthPrincipal; /** * AAF Client: Generic AAF Client implementation to connect to AAF Resources to * validate permissions and authorization. - * + * */ public class AAFPolicyClientImpl implements AAFPolicyClient { private static Logger logger = Logger.getLogger(AAFPolicyClientImpl.class.getName()); @@ -60,10 +61,10 @@ public class AAFPolicyClientImpl implements AAFPolicyClient { * CLIENT_ID, CLIENT_KEY and ENVIRONMENT * * @param properties - * Properties with CLIENT_ID, CLIENT_KEY and ENVIRONMENT + * Properties with CLIENT_ID, CLIENT_KEY and ENVIRONMENT * @return AAFClient instance. * @throws AAFPolicyException - * Exceptions. + * Exceptions. */ public static synchronized AAFPolicyClientImpl getInstance(Properties properties) throws AAFPolicyException { if (instance == null) { @@ -83,16 +84,16 @@ public class AAFPolicyClientImpl implements AAFPolicyClient { logger.error("Required Property value is missing : " + ENVIRONMENT); throw new AAFPolicyException("Required Property value is missing : " + ENVIRONMENT); } - setUpAAF(); + setUpAaf(); } /** * Updates the Properties file in case if required. * * @param properties - * Properties with CLIENT_ID, CLIENT_KEY and ENVIRONMENT + * Properties with CLIENT_ID, CLIENT_KEY and ENVIRONMENT * @throws AAFPolicyException - * exceptions if any. + * exceptions if any. */ @Override public void updateProperties(Properties properties) throws AAFPolicyException { @@ -103,15 +104,15 @@ public class AAFPolicyClientImpl implements AAFPolicyClient { * Checks the Authentication and Permissions for the given values. * * @param userName - * Username must be registered under the Name space. + * Username must be registered under the Name space. * @param pass - * Password pertaining to the Username. + * Password pertaining to the Username. * @param type - * Permissions Type. + * Permissions Type. * @param instance - * Permissions Instance. + * Permissions Instance. * @param action - * Permissions Action. + * Permissions Action. * @return */ @Override @@ -123,9 +124,9 @@ public class AAFPolicyClientImpl implements AAFPolicyClient { * Checks the Authentication of the UserName and Password Given. * * @param userName - * UserName + * UserName * @param pass - * Password. + * Password. * @return True or False. */ @Override @@ -134,17 +135,18 @@ public class AAFPolicyClientImpl implements AAFPolicyClient { return false; } try { - int i = 0; + int index = 0; do { String aafAuthResponse = aafAuthn.validate(userName, pass); - if (aafAuthResponse==null) { + if (aafAuthResponse == null) { return true; } else { - logger.warn("User, " + userName + ", failed to authenticate with AAF. \n" - + "AAF Response is " + aafAuthResponse); + logger.warn("User, " + userName + ", failed to authenticate with AAF. \n" + "AAF Response is " + + aafAuthResponse); } - i++; - } while (i < 2); + index++; + } + while (index < 2); } catch (Exception e) { logger.error(e.getMessage() + e); } @@ -157,27 +159,27 @@ public class AAFPolicyClientImpl implements AAFPolicyClient { * Action. * * @param userName - * UserName + * UserName * @param pass - * Password. + * Password. * @param type - * Permissions Type. + * Permissions Type. * @param instance - * Permissions Instance. + * Permissions Instance. * @param action - * Permissions Action. + * Permissions Action. * @return True or False. */ @Override public boolean checkPerm(String userName, String pass, String type, String instance, String action) { - int i = 0; + int index = 0; Boolean result = false; do { if (aafCon != null && aafLurPerm != null) { try { aafCon.basicAuth(userName, pass); - AAFPermission perm = new AAFPermission(cadiprops.getProperty("policy.aaf.namespace"), type, - instance, action); + AAFPermission perm = + new AAFPermission(cadiprops.getProperty("policy.aaf.namespace"), type, instance, action); final Principal p = new UnAuthPrincipal(userName); result = aafLurPerm.fish(p, perm); } catch (CadiException e) { @@ -185,12 +187,13 @@ public class AAFPolicyClientImpl implements AAFPolicyClient { aafLurPerm.destroy(); } } - i++; - } while (i < 2 && !result); // Try once more to check if this can be passed. AAF has some issues. + index++; + } + while (index < 2 && !result); // Try once more to check if this can be passed. AAF has some issues. return result; } - private static boolean setUpAAF() { + private static boolean setUpAaf() { try { aafCon = new AAFConHttp(access, new PropertyLocator("https://" + cadiprops.getProperty("aaf_fqdn") + ":8100")); diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyException.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyException.java index b67b02243..c64c3c4d2 100644 --- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyException.java +++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyException.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * PolicyEngineUtils * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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,30 +21,30 @@ package org.onap.policy.utils; /** - * AAFPolicyException to show exception messages. - * + * AAFPolicyException to show exception messages. + * */ public class AAFPolicyException extends Exception { - private static final long serialVersionUID = 1910606668038621L; - - public AAFPolicyException() { - // Empty constructor. - // Nothing needs to be initialized in this exception class. - } - - public AAFPolicyException(String message) { - super(message); - } - - public AAFPolicyException(Throwable cause){ - super(cause); - } - - public AAFPolicyException(String message, Throwable cause) { - super(message, cause); - } - - public AAFPolicyException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } + private static final long serialVersionUID = 1910606668038621L; + + public AAFPolicyException() { + // Empty constructor. + // Nothing needs to be initialized in this exception class. + } + + public AAFPolicyException(String message) { + super(message); + } + + public AAFPolicyException(Throwable cause) { + super(cause); + } + + public AAFPolicyException(String message, Throwable cause) { + super(message, cause); + } + + public AAFPolicyException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } } diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpHandler.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpHandler.java index 4dfc64c39..09cfe7832 100644 --- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpHandler.java +++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpHandler.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * PolicyEngineUtils * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -23,20 +23,24 @@ package org.onap.policy.utils; import org.onap.policy.api.NotificationHandler; import org.onap.policy.api.PDPNotification; -public interface BackUpHandler extends NotificationHandler{ - - /** - * <code>notificationReceived</code> method will be triggered automatically whenever a Notification is received by the PEP. - * - * @param notification <code>PDPNotification</code> of {@link org.onap.policy.api.PDPNotification} is the object that has information of the notification. - */ - @Override - public void notificationReceived(PDPNotification notification); - - /** - * <code>runOnNotification</code> method will be triggered automatically whenever a Notification is received by the PEP This needs to be the main implementation. - * - * @param notification <code>PDPNotification</code> of {@link org.onap.policy.api.PDPNotification} is the object that has information of the notification. - */ - public void runOnNotification(PDPNotification notification); +public interface BackUpHandler extends NotificationHandler { + + /** + * <code>notificationReceived</code> method will be triggered automatically whenever a Notification is received by + * the PEP. + * + * @param notification <code>PDPNotification</code> of {@link org.onap.policy.api.PDPNotification} is the object + * that has information of the notification. + */ + @Override + public void notificationReceived(PDPNotification notification); + + /** + * <code>runOnNotification</code> method will be triggered automatically whenever a Notification is received by the + * PEP This needs to be the main implementation. + * + * @param notification <code>PDPNotification</code> of {@link org.onap.policy.api.PDPNotification} is the object + * that has information of the notification. + */ + public void runOnNotification(PDPNotification notification); } diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpMonitor.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpMonitor.java index 4f8a82100..c82e6968f 100644 --- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpMonitor.java +++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpMonitor.java @@ -2,15 +2,15 @@ * ============LICENSE_START======================================================= * PolicyEngineUtils * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. * 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,6 +21,13 @@ package org.onap.policy.utils; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.github.fge.jackson.JsonLoader; +import com.github.fge.jsonpatch.JsonPatch; +import com.github.fge.jsonpatch.JsonPatchException; +import com.github.fge.jsonpatch.diff.JsonDiff; + import java.io.IOException; import java.util.ArrayList; import java.util.Date; @@ -41,16 +48,9 @@ import org.onap.policy.jpa.BackUpMonitorEntity; import org.onap.policy.std.NotificationStore; import org.onap.policy.std.StdPDPNotification; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.github.fge.jackson.JsonLoader; -import com.github.fge.jsonpatch.JsonPatch; -import com.github.fge.jsonpatch.JsonPatchException; -import com.github.fge.jsonpatch.diff.JsonDiff; - /** * BackUp Monitor checks Backup Status with the Database and maintains Redundancy for Gateway Applications. - * + * */ public class BackUpMonitor { private static final Logger LOGGER = Logger.getLogger(BackUpMonitor.class.getName()); @@ -58,7 +58,7 @@ public class BackUpMonitor { private static final String PING_INTERVAL = "ping_interval"; private static final String MASTER = "MASTER"; private static final String SLAVE = "SLAVE"; - + private static BackUpMonitor instance = null; private static String resourceName = null; private static String resourceNodeName = null; @@ -85,7 +85,7 @@ public class BackUpMonitor { throws BackUpMonitorException { init(resourceName, resourceNodeName, handler); // Create Persistence Entity - if(!properties.containsKey(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML)){ + if (!properties.containsKey(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML)) { properties.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, "META-INF/persistencePU.xml"); } emf = Persistence.createEntityManagerFactory("PolicyEngineUtils", properties); @@ -100,15 +100,20 @@ public class BackUpMonitor { // Start thread. startThread(new BMonitor()); } - - private static void startThread(BMonitor bMonitor) { - t = new Thread(bMonitor); + + private static void startThread(BMonitor monitor) { + t = new Thread(monitor); t.start(); } - public static void stop() throws InterruptedException{ + /** + * Stop. + * + * @throws InterruptedException InterruptedException + */ + public static void stop() throws InterruptedException { stopFlag = true; - if(t!=null){ + if (t != null) { t.interrupt(); t.join(); } @@ -124,13 +129,13 @@ public class BackUpMonitor { /** * Gets the BackUpMonitor Instance if given proper resourceName and properties. Else returns null. - * + * * @param resourceNodeName - * String format of the Resource Node to which the resource Belongs to. + * String format of the Resource Node to which the resource Belongs to. * @param resourceName - * String format of the ResourceName. This needs to be Unique. + * String format of the ResourceName. This needs to be Unique. * @param properties - * Properties format of the properties file. + * Properties format of the properties file. * @return BackUpMonitor instance. */ public static synchronized BackUpMonitor getInstance(String resourceNodeName, String resourceName, @@ -164,8 +169,7 @@ public class BackUpMonitor { LOGGER.error("javax.persistence.jdbc.user property is empty"); return false; } - if (properties.getProperty(PING_INTERVAL) == null - || "".equals(properties.getProperty(PING_INTERVAL).trim())) { + if (properties.getProperty(PING_INTERVAL) == null || "".equals(properties.getProperty(PING_INTERVAL).trim())) { LOGGER.info("ping_interval property not specified. Taking default value"); } else { try { @@ -186,8 +190,8 @@ public class BackUpMonitor { } /** - * Gets the Boolean value of Master(True) or Slave mode (False) - * + * Gets the Boolean value of Master(True) or Slave mode (False). + * * @return Boolean flag which if True means that the operation needs to be performed(Master mode) or if false the * operation is in slave mode. */ @@ -214,17 +218,17 @@ public class BackUpMonitor { } // Set Master - private static BackUpMonitorEntity setMaster(BackUpMonitorEntity bMEntity) { - bMEntity.setFlag(MASTER); + private static BackUpMonitorEntity setMaster(BackUpMonitorEntity entity) { + entity.setFlag(MASTER); setFlag(true); - return bMEntity; + return entity; } // Set Slave - private static BackUpMonitorEntity setSlave(BackUpMonitorEntity bMEntity) { - bMEntity.setFlag(SLAVE); + private static BackUpMonitorEntity setSlave(BackUpMonitorEntity entity) { + entity.setFlag(SLAVE); setFlag(false); - return bMEntity; + return entity; } // Check Database and set the Flag. @@ -244,45 +248,45 @@ public class BackUpMonitor { } else if (resourceNodeName.equals(ResourceNode.BRMS.toString())) { query.setParameter("nn", ResourceNode.BRMS.toString()); } - List<?> bMList = query.getResultList(); - if (bMList.isEmpty()) { + List<?> entityList = query.getResultList(); + if (entityList.isEmpty()) { // This is New. create an entry as Master. LOGGER.info("Adding resource " + resourceName + " to Database"); - BackUpMonitorEntity bMEntity = new BackUpMonitorEntity(); - bMEntity.setResourceNodeName(resourceNodeName); - bMEntity.setResourceName(resourceName); - bMEntity = setMaster(bMEntity); - bMEntity.setTimeStamp(new Date()); - em.persist(bMEntity); + BackUpMonitorEntity entity = new BackUpMonitorEntity(); + entity.setResourceNodeName(resourceNodeName); + entity.setResourceName(resourceName); + entity = setMaster(entity); + entity.setTimeStamp(new Date()); + em.persist(entity); em.flush(); } else { - checkOtherMaster(bMList); + checkOtherMaster(entityList); } et.commit(); } catch (Exception e) { LOGGER.error("failed Database Operation " + e.getMessage(), e); - if (et!=null && et.isActive()) { + if (et != null && et.isActive()) { et.rollback(); } throw new BackUpMonitorException(e); } } - private void checkOtherMaster(List<?> bMList) { + private void checkOtherMaster(List<?> entityList) { // Check for other Master(s) ArrayList<BackUpMonitorEntity> masterEntities = new ArrayList<>(); // Check for self. BackUpMonitorEntity selfEntity = null; // Check backup monitor entities. - for (int i = 0; i < bMList.size(); i++) { - BackUpMonitorEntity bMEntity = (BackUpMonitorEntity) bMList.get(i); + for (Object entity : entityList) { + BackUpMonitorEntity backupEntity = (BackUpMonitorEntity) entity; LOGGER.info("Refreshing Entity. "); - em.refresh(bMEntity); - if (bMEntity.getFlag().equalsIgnoreCase(MASTER)) { - masterEntities.add(bMEntity); + em.refresh(backupEntity); + if (backupEntity.getFlag().equalsIgnoreCase(MASTER)) { + masterEntities.add(backupEntity); } - if (bMEntity.getResourceName().equals(resourceName)) { - selfEntity = bMEntity; + if (backupEntity.getResourceName().equals(resourceName)) { + selfEntity = backupEntity; } } if (selfEntity != null) { @@ -338,8 +342,7 @@ public class BackUpMonitor { if (masterEntities.size() == 1) { singleMasterEntity(masterEntities, selfEntity); } else { - LOGGER.error( - "Backup Monitor Issue, Masters out of sync, This will be fixed in next interval."); + LOGGER.error("Backup Monitor Issue, Masters out of sync, This will be fixed in next interval."); } } } @@ -365,7 +368,6 @@ public class BackUpMonitor { em.persist(masterEntity); em.flush(); // Lets Become Master. - selfEntity = setMaster(selfEntity); LOGGER.info("Changing " + resourceName + " from slave to Master Mode"); selfEntity.setTimeStamp(new Date()); selfEntity.setNotificationRecord(notificationRecord); @@ -383,8 +385,7 @@ public class BackUpMonitor { if (currentEntity.getFlag().equalsIgnoreCase(MASTER)) { if (masterEntity == null) { masterEntity = currentEntity; - } else if (currentEntity.getTimeStamp().getTime() > masterEntity.getTimeStamp() - .getTime()) { + } else if (currentEntity.getTimeStamp().getTime() > masterEntity.getTimeStamp().getTime()) { // False Master, Update master to slave and take currentMaster as Master. masterEntity.setFlag(SLAVE); masterEntity.setTimeStamp(new Date()); @@ -441,10 +442,8 @@ public class BackUpMonitor { /** * Updates Notification in the Database while Performing the health check. - * - * @param notification - * String format of notification record to store in the Database. - * @throws Exception + * + * @throws BackUpMonitorException BackUpMonitorException */ public synchronized void updateNotification() throws BackUpMonitorException { checkDataBase(); @@ -454,8 +453,8 @@ public class BackUpMonitor { private static void callHandler(String notification) { if (handler != null) { try { - PDPNotification notificationObject = PolicyUtils.jsonStringToObject(notification, - StdPDPNotification.class); + PDPNotification notificationObject = + PolicyUtils.jsonStringToObject(notification, StdPDPNotification.class); if (notificationObject.getNotificationType() != null) { LOGGER.info("Performing Patched notification "); performPatchNotification(notificationObject); diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpMonitorException.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpMonitorException.java index 4f7883800..60dd5e569 100644 --- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpMonitorException.java +++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpMonitorException.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * PolicyEngineUtils * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -20,27 +20,28 @@ package org.onap.policy.utils; -public class BackUpMonitorException extends Exception{ +public class BackUpMonitorException extends Exception { private static final long serialVersionUID = 6778134503685443473L; - + public BackUpMonitorException() { - // Nothing for this constructor to initialize - // in an exception class. + // Nothing for this constructor to initialize + // in an exception class. } - + public BackUpMonitorException(String message) { super(message); } - - public BackUpMonitorException(Throwable cause){ + + public BackUpMonitorException(Throwable cause) { super(cause); } - + public BackUpMonitorException(String message, Throwable cause) { super(message, cause); } - - public BackUpMonitorException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + + public BackUpMonitorException(String message, Throwable cause, boolean enableSuppression, + boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } } diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusConsumer.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusConsumer.java index 0d4c86b3d..b64d6143e 100644 --- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusConsumer.java +++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusConsumer.java @@ -2,14 +2,15 @@ * ============LICENSE_START======================================================= * PolicyEngineUtils * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved. + * Modifications copyright (c) 2019 Nokia * ================================================================================ * 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. @@ -23,103 +24,100 @@ package org.onap.policy.utils; import java.net.MalformedURLException; import java.util.List; import java.util.Properties; + import org.onap.dmaap.mr.client.MRClient.MRApiException; import org.onap.dmaap.mr.client.impl.MRConsumerImpl; import org.onap.dmaap.mr.test.clients.ProtocolTypeConstants; public interface BusConsumer { - - /** - * fetch messages - * - * @return list of messages - * @throws MRApiException when error encountered by underlying libraries - */ - public Iterable<String> fetch() throws MRApiException; - - /** - * close underlying library consumer - */ - public void close(); - - /** - * MR based consumer - */ - public static class DmaapConsumerWrapper implements BusConsumer { - - /** - * MR Consumer - */ - protected MRConsumerImpl consumer; - - /** - * MR Consumer Wrapper - * - * @param servers messaging bus hosts - * @param topic topic - * @param apiKey API Key - * @param apiSecret API Secret - * @param aafLogin AAF Login - * @param aafPassword AAF Password - * @param consumerGroup Consumer Group - * @param consumerInstance Consumer Instance - * @param fetchTimeout Fetch Timeout - * @param fetchLimit Fetch Limit - */ - public DmaapConsumerWrapper(List<String> servers, String topic, - String aafLogin, String aafPassword, - String consumerGroup, String consumerInstance, - int fetchTimeout, int fetchLimit) throws MalformedURLException{ - - this.consumer = new MRConsumerImpl(servers, topic, - consumerGroup, consumerInstance, - fetchTimeout, fetchLimit, - null, aafLogin, aafPassword); - - this.consumer.setUsername(aafLogin); - this.consumer.setPassword(aafPassword); - - this.consumer.setProtocolFlag(ProtocolTypeConstants.AAF_AUTH.getValue()); - - Properties props = new Properties(); - props.setProperty("Protocol", "http"); - this.consumer.setProps(props); - this.consumer.setHost(servers.get(0) + ":3904"); - } - - /** - * {@inheritDoc} - */ - @Override - public Iterable<String> fetch() throws MRApiException { - try { - return this.consumer.fetch(); + + /** + * fetch messages. + * + * @return list of messages + * @throws MRApiException when error encountered by underlying libraries + */ + Iterable<String> fetch() throws MRApiException; + + /** + * close underlying library consumer. + */ + void close(); + + /** + * MR based consumer. + */ + class DmaapConsumerWrapper implements BusConsumer { + + /** + * MR Consumer. + */ + protected MRConsumerImpl consumer; + + /** + * MR Consumer Wrapper. + * + * @param servers messaging bus hosts + * @param topic topic + * @param apiKey API Key + * @param apiSecret API Secret + * @param aafLogin AAF Login + * @param aafPassword AAF Password + * @param consumerGroup Consumer Group + * @param consumerInstance Consumer Instance + * @param fetchTimeout Fetch Timeout + * @param fetchLimit Fetch Limit + */ + public DmaapConsumerWrapper(List<String> servers, String topic, String aafLogin, String aafPassword, + String consumerGroup, String consumerInstance, int fetchTimeout, int fetchLimit) + throws MalformedURLException { + + this(new MRConsumerImpl(servers, topic, consumerGroup, consumerInstance, fetchTimeout, fetchLimit, null, + aafLogin, aafPassword), aafLogin, aafPassword, servers.get(0)); + + } + + DmaapConsumerWrapper(MRConsumerImpl consumer, String aafLogin, String aafPassword, String host) { + this.consumer = consumer; + this.consumer.setUsername(aafLogin); + this.consumer.setPassword(aafPassword); + this.consumer.setProtocolFlag(ProtocolTypeConstants.AAF_AUTH.getValue()); + this.consumer.setHost(host + ":3904"); + + Properties props = new Properties(); + props.setProperty("Protocol", "http"); + this.consumer.setProps(props); + } + + /** + * {@inheritDoc} + */ + @Override + public Iterable<String> fetch() throws MRApiException { + try { + return consumer.fetch(); } catch (Exception e) { - throw new MRApiException("Error during MR consumer Fetch ",e); + throw new MRApiException("Error during MR consumer Fetch ", e); } - } - - /** - * {@inheritDoc} - */ - @Override - public void close() { - this.consumer.close(); - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder. - append("DmaapConsumerWrapper ["). - append("consumer.getAuthDate()=").append(consumer.getAuthDate()). - append(", consumer.getAuthKey()=").append(consumer.getAuthKey()). - append(", consumer.getHost()=").append(consumer.getHost()). - append(", consumer.getProtocolFlag()=").append(consumer.getProtocolFlag()). - append(", consumer.getUsername()=").append(consumer.getUsername()). - append("]"); - return builder.toString(); - } - } + } + + /** + * {@inheritDoc} + */ + @Override + public void close() { + this.consumer.close(); + } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("DmaapConsumerWrapper [").append("consumer.getAuthDate()=").append(consumer.getAuthDate()) + .append(", consumer.getAuthKey()=").append(consumer.getAuthKey()).append(", consumer.getHost()=") + .append(consumer.getHost()).append(", consumer.getProtocolFlag()=") + .append(consumer.getProtocolFlag()).append(", consumer.getUsername()=") + .append(consumer.getUsername()).append("]"); + return builder.toString(); + } + } } diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusPublisher.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusPublisher.java index 745213529..f5c792caf 100644 --- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusPublisher.java +++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusPublisher.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * PolicyEngineUtils * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -24,6 +24,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.concurrent.TimeUnit; + import org.onap.dmaap.mr.client.impl.MRSimplerBatchPublisher; import org.onap.dmaap.mr.test.clients.ProtocolTypeConstants; import org.onap.policy.common.logging.eelf.PolicyLogger; @@ -31,109 +32,109 @@ import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; public interface BusPublisher { - - /** - * sends a message - * - * @param partition id - * @param message the message - * @return true if success, false otherwise - * @throws IllegalArgumentException if no message provided - */ - public boolean send(String partitionId, String message); - - /** - * closes the publisher - */ - public void close(); - - /** - * DmaapClient library wrapper - */ - public static class DmaapPublisherWrapper implements BusPublisher { - private static Logger logger = FlexLogger.getLogger(DmaapPublisherWrapper.class); - /** - * MR based Publisher - */ - protected MRSimplerBatchPublisher publisher; - - public DmaapPublisherWrapper(List<String> servers, String topic, - String aafLogin, - String aafPassword) { - - ArrayList<String> dmaapServers = new ArrayList<>(); - for (String server: servers) { - dmaapServers.add(server + ":3904"); - } - - this.publisher = - new MRSimplerBatchPublisher.Builder(). - againstUrls(dmaapServers). - onTopic(topic). - build(); - - this.publisher.setProtocolFlag(ProtocolTypeConstants.AAF_AUTH.getValue()); - - this.publisher.setUsername(aafLogin); - this.publisher.setPassword(aafPassword); - - Properties props = new Properties(); - props.setProperty("Protocol", "http"); - props.setProperty("contenttype", "application/json"); - - this.publisher.setProps(props); - - this.publisher.setHost(servers.get(0)); - - if (PolicyLogger.isInfoEnabled()) - PolicyLogger.info(DmaapPublisherWrapper.class.getName(), - "CREATION: " + this); - } - - /** - * {@inheritDoc} - */ - @Override - public void close() { - if (logger.isInfoEnabled()) - logger.info(DmaapPublisherWrapper.class.getName()+ - "CREATION: " + this); - - try { - this.publisher.close(1, TimeUnit.SECONDS); - } catch (Exception e) { - logger.warn(DmaapPublisherWrapper.class.getName()+ - "CLOSE: " + this + " because of " + - e.getMessage(), e); - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean send(String partitionId, String message){ - if (message == null) - throw new IllegalArgumentException("No message provided"); - - this.publisher.send(partitionId, message); - return true; - - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("DmaapPublisherWrapper ["). - append("publisher.getAuthDate()=").append(publisher.getAuthDate()). - append(", publisher.getAuthKey()=").append(publisher.getAuthKey()). - append(", publisher.getHost()=").append(publisher.getHost()). - append(", publisher.getProtocolFlag()=").append(publisher.getProtocolFlag()). - append(", publisher.getUsername()=").append(publisher.getUsername()). - append(", publisher.getPendingMessageCount()=").append(publisher.getPendingMessageCount()). - append("]"); - return builder.toString(); - } - } + + /** + * sends a message + * . + * @param partitionId id + * @param message the message + * @return true if success, false otherwise + * @throws IllegalArgumentException if no message provided + */ + public boolean send(String partitionId, String message); + + /** + * closes the publisher. + */ + public void close(); + + /** + * DmaapClient library wrapper. + */ + public static class DmaapPublisherWrapper implements BusPublisher { + private static Logger logger = FlexLogger.getLogger(DmaapPublisherWrapper.class); + /** + * MR based Publisher. + */ + protected MRSimplerBatchPublisher publisher; + + /** + * DmaapPublisherWrapper constructor. + * + * @param servers list of servers + * @param topic topic + * @param aafLogin login + * @param aafPassword password + */ + public DmaapPublisherWrapper(List<String> servers, String topic, String aafLogin, String aafPassword) { + + ArrayList<String> dmaapServers = new ArrayList<>(); + for (String server : servers) { + dmaapServers.add(server + ":3904"); + } + + this.publisher = new MRSimplerBatchPublisher.Builder().againstUrls(dmaapServers).onTopic(topic).build(); + + this.publisher.setProtocolFlag(ProtocolTypeConstants.AAF_AUTH.getValue()); + + this.publisher.setUsername(aafLogin); + this.publisher.setPassword(aafPassword); + + Properties props = new Properties(); + props.setProperty("Protocol", "http"); + props.setProperty("contenttype", "application/json"); + + this.publisher.setProps(props); + + this.publisher.setHost(servers.get(0)); + + if (PolicyLogger.isInfoEnabled()) { + PolicyLogger.info(DmaapPublisherWrapper.class.getName(), "CREATION: " + this); + } + } + + /** + * {@inheritDoc} + */ + @Override + public void close() { + if (logger.isInfoEnabled()) { + logger.info(DmaapPublisherWrapper.class.getName() + "CREATION: " + this); + } + + try { + this.publisher.close(1, TimeUnit.SECONDS); + } catch (Exception e) { + logger.warn(DmaapPublisherWrapper.class.getName() + "CLOSE: " + this + " because of " + e.getMessage(), + e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean send(String partitionId, String message) { + if (message == null) { + throw new IllegalArgumentException("No message provided"); + } + + this.publisher.send(partitionId, message); + return true; + + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("DmaapPublisherWrapper [").append("publisher.getAuthDate()=").append(publisher.getAuthDate()) + .append(", publisher.getAuthKey()=").append(publisher.getAuthKey()).append(", publisher.getHost()=") + .append(publisher.getHost()).append(", publisher.getProtocolFlag()=") + .append(publisher.getProtocolFlag()).append(", publisher.getUsername()=") + .append(publisher.getUsername()).append(", publisher.getPendingMessageCount()=") + .append(publisher.getPendingMessageCount()).append("]"); + return builder.toString(); + } + } } diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PeCryptoUtils.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PeCryptoUtils.java index 9863f03ad..2ffdae159 100644 --- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PeCryptoUtils.java +++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PeCryptoUtils.java @@ -20,25 +20,22 @@ package org.onap.policy.utils; -import java.security.GeneralSecurityException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; + import org.apache.commons.lang3.StringUtils; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.common.utils.security.CryptoUtils; public class PeCryptoUtils { - private static Logger logger = FlexLogger.getLogger(PeCryptoUtils.class); private static final String PROP_AES_KEY = "org.onap.policy.encryption.aes.key"; private static CryptoUtils cryptoUtils = null; private static String secretKey = System.getenv("AES_ENCRYPTION_KEY"); private static final Map<String, String> decryptCache = new ConcurrentHashMap<>(); private static final Map<String, String> encryptCache = new ConcurrentHashMap<>(); - - private PeCryptoUtils() {} + private PeCryptoUtils() { + } /** * Inits the aes key. @@ -65,19 +62,10 @@ public class PeCryptoUtils { * @return The encrypted String */ public static String encrypt(String value) { - if (cryptoUtils == null || StringUtils.isBlank(value)) { return value; } - - return encryptCache.computeIfAbsent(value, k -> { - try { - return cryptoUtils.encrypt(k); - } catch (GeneralSecurityException e) { - logger.error("Could not decrypt value - exception: ", e); - return value; - } - }); + return encryptCache.computeIfAbsent(value, cryptoUtils::encrypt); } /** @@ -90,13 +78,6 @@ public class PeCryptoUtils { if (cryptoUtils == null || StringUtils.isBlank(value)) { return value; } - return decryptCache.computeIfAbsent(value, k -> { - try { - return cryptoUtils.decrypt(k); - } catch (GeneralSecurityException e) { - logger.error("Could not decrypt value - exception: ", e); - return value; - } - }); + return decryptCache.computeIfAbsent(value, cryptoUtils::decrypt); } } diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyAccess.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyAccess.java index 1994578e6..950103c86 100644 --- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyAccess.java +++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyAccess.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * PolicyEngineUtils * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -24,14 +24,13 @@ import java.util.Properties; import org.onap.aaf.cadi.PropAccess; - /** - * PolicyAccess used by AAF for logging purposes. - * + * PolicyAccess used by AAF for logging purposes. + * */ public class PolicyAccess extends PropAccess { - public PolicyAccess (Properties props, Level level) { - super(props); - this.setLogLevel(level); - } + public PolicyAccess(Properties props, Level level) { + super(props); + this.setLogLevel(level); + } } diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyUtils.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyUtils.java index 67210c814..7d70da2f7 100644 --- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyUtils.java +++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyUtils.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * PolicyEngineUtils * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -20,6 +20,12 @@ package org.onap.policy.utils; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.CharMatcher; +import com.google.gson.JsonParser; +import com.google.gson.JsonSyntaxException; + import java.io.IOException; import java.io.StringReader; import java.io.UnsupportedEncodingException; @@ -38,7 +44,6 @@ import javax.xml.parsers.SAXParserFactory; import org.drools.core.io.impl.ReaderResource; import org.drools.verifier.Verifier; import org.drools.verifier.VerifierError; -import org.drools.verifier.builder.VerifierBuilder; import org.drools.verifier.builder.VerifierBuilderFactory; import org.kie.api.io.ResourceType; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -46,295 +51,291 @@ import org.onap.policy.common.logging.flexlogger.Logger; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.base.CharMatcher; -import com.google.gson.JsonParser; -import com.google.gson.JsonSyntaxException; - public class PolicyUtils { private static final Logger LOGGER = FlexLogger.getLogger(PolicyUtils.class); - public static final String CATCH_EXCEPTION = "PE500: An exception was caught."; - public static final String EMAIL_PATTERN = - "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" - + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; private static final String PACKAGE_ERROR = "mismatched input '{' expecting one of the following tokens: '[package"; + + public static final String CATCH_EXCEPTION = "PE500: An exception was caught."; + public static final String EMAIL_PATTERN = + "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; public static final String SUCCESS = "success"; - - private PolicyUtils(){ + public static final String CHARACTER_ENCODING = "UTF-8"; + public static final String APPLICATION_JSON = "application/json"; + + private PolicyUtils() { // Private Constructor } - + /** - * Converts an Object to JSON String - * - * @param o Object - * @return String format of Object JSON. - * @throws JsonProcessingException + * Converts an Object to JSON String. + * + * @param object Object + * @return String format of Object JSON. + * @throws JsonProcessingException JsonProcessingException */ - public static String objectToJsonString(Object o) throws JsonProcessingException{ - ObjectMapper mapper = new ObjectMapper(); - return mapper.writeValueAsString(o); + public static String objectToJsonString(Object object) throws JsonProcessingException { + return new ObjectMapper().writeValueAsString(object); } - + /** - * Converts JSON string into Object - * - * @param jsonString - * @param className equivalent Class of the given JSON string - * @return T instance of the class given. - * @throws IOException + * Converts JSON string into Object. + * + * @param jsonString Input JSON String + * @param className equivalent Class of the given JSON string + * @return T instance of the class given. + * @throws IOException IOException */ - public static <T> T jsonStringToObject(String jsonString, Class<T> className) throws IOException{ + public static <T> T jsonStringToObject(String jsonString, Class<T> className) throws IOException { ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(jsonString, className); } - + /** - * Decode a base64 string - * - * @param encodedString + * Decode a base64 string. + * + * @param encodedString String to encode * @return String - * @throws UnsupportedEncodingException + * @throws UnsupportedEncodingException UnsupportedEncodingException */ - public static String decode(String encodedString) throws UnsupportedEncodingException { - if(encodedString!=null && !encodedString.isEmpty()){ - return new String(Base64.getDecoder().decode(encodedString) ,"UTF-8"); - }else{ - return null; - } + public static String decode(String encodedString) throws UnsupportedEncodingException { + if (encodedString != null && !encodedString.isEmpty()) { + return new String(Base64.getDecoder().decode(encodedString), "UTF-8"); + } else { + return null; + } } - + /** - * Decodes Basic Authentication - * - * @param encodedValue - * @return - * @throws UnsupportedEncodingException + * Decodes Basic Authentication. + * + * @param encodedValue value to encode + * @return list of String + * @throws UnsupportedEncodingException UnsupportedEncodingException */ public static String[] decodeBasicEncoding(String encodedValue) throws UnsupportedEncodingException { - if(encodedValue!=null && encodedValue.contains("Basic ")){ - String encodedUserPassword = encodedValue.replaceFirst("Basic" + " ", ""); + if (encodedValue != null && encodedValue.contains("Basic ")) { + String encodedUserPassword = encodedValue.replaceFirst("Basic" + " ", ""); String usernameAndPassword; byte[] decodedBytes = Base64.getDecoder().decode(encodedUserPassword); usernameAndPassword = new String(decodedBytes, "UTF-8"); StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":"); String username = tokenizer.nextToken(); String password = tokenizer.nextToken(); - return new String[]{username, password}; - }else{ - return new String[]{}; + return new String[] {username, password}; + } else { + return new String[] {}; } } - + /** - * Validate a field if contains space or unacceptable policy input and return "success" if good. - * - * @param field - * @return + * Validate a field if contains space or unacceptable policy input and return "success" if good. + * + * @param field String + * @return String */ - public static String policySpecialCharValidator(String field){ + public static String policySpecialCharValidator(String field) { String error; if ("".equals(field) || field.contains(" ") || !field.matches("^[a-zA-Z0-9_]*$")) { - error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations"; - return error; + error = "The Value in Required Field will allow only" + + " '{0-9}, {a-z}, {A-Z}, _' following set of Combinations"; + return error; } - return SUCCESS; - } - + return SUCCESS; + } + /** - * Validate a field (accepts space) if it contains unacceptable policy input and return "success" if good. - * - * @param field + * Validate a field (accepts space) if it contains unacceptable policy input and return "success" if good. + * + * @param field Input field String * @return */ - public static String policySpecialCharWithSpaceValidator(String field){ + public static String policySpecialCharWithSpaceValidator(String field) { String error; if ("".equals(field) || !field.matches("^[a-zA-Z0-9_ ]*$")) { - error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations"; + error = "The Value in Required Field will allow only " + + "'{0-9}, {a-z}, {A-Z}, _' following set of Combinations"; return error; } - return SUCCESS; - } - + return SUCCESS; + } + /** - * Validate a field (accepts Dash) if it contains unacceptable policy input and return "success" if good. - * - * @param field - * @return + * Validate a field (accepts Dash) if it contains unacceptable policy input and return "success" if good. + * + * @param field String + * @return String */ - public static String policySpecialCharWithDashValidator(String field){ + public static String policySpecialCharWithDashValidator(String field) { String error; if ("".equals(field) || !field.matches("^[a-zA-Z0-9_-]*$")) { - error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _, -' following set of Combinations"; + error = "The Value in Required Field will allow only " + + "'{0-9}, {a-z}, {A-Z}, _, -' following set of Combinations"; return error; } - return SUCCESS; - } - + return SUCCESS; + } + /** - * Validate the XACML description tag and return "success" if good. - * - * @param field - * @return + * Validate the XACML description tag and return "success" if good. + * + * @param field String + * @return String */ public static String descriptionValidator(String field) { String error; if (field.contains("@CreatedBy:") || field.contains("@ModifiedBy:")) { - error = "The value in the description shouldn't contain @CreatedBy: or @ModifiedBy:"; - return error; + error = "The value in the description shouldn't contain @CreatedBy: or @ModifiedBy:"; + return error; } else { error = SUCCESS; } - return error; + return error; } - + /** - * Validate if string contains non ASCII characters - * - * @param value - * @return + * Validate if string contains non ASCII characters. + * + * @param value String + * @return true if contains non ASCII characters */ public static boolean containsNonAsciiEmptyChars(String value) { - return (value == null || value.contains(" ") || "".equals(value.trim()) || !CharMatcher.ascii().matchesAllOf((CharSequence) value)) ? true : false; + return (value == null || value.contains(" ") || "".equals(value.trim()) + || !CharMatcher.ascii().matchesAllOf(value)) ? true : false; } - + /** - * Validate if given string is an integer. - * - * @param number - * @return + * Validate if given string is an integer. + * + * @param number String representing a number + * @return true if integer */ - public static Boolean isInteger(String number){ - if(number==null) { + public static Boolean isInteger(String number) { + if (number == null) { return false; } - for (char c : number.toCharArray()){ + for (char c : number.toCharArray()) { if (!Character.isDigit(c)) { - return false; + return false; } } return true; } - + /** - * Validate Email Address and return "success" if good. - * - * @param emailAddressValue - * @return + * Validate Email Address and return "success" if good. + * + * @param emailAddressValue String email address + * @return SUCCESS String if valid */ public static String validateEmailAddress(String emailAddressValue) { String error = SUCCESS; List<String> emailList = Arrays.asList(emailAddressValue.split(",")); - for(int i =0 ; i < emailList.size() ; i++){ + for (int i = 0; i < emailList.size(); i++) { Pattern pattern = Pattern.compile(EMAIL_PATTERN); Matcher matcher = pattern.matcher(emailList.get(i).trim()); - if(!matcher.matches()){ - error = "Please check the Following Email Address is not Valid .... " +emailList.get(i); + if (!matcher.matches()) { + error = "Please check the Following Email Address is not Valid .... " + emailList.get(i); return error; - }else{ + } else { error = SUCCESS; } } - return error; + return error; } - + /** * Validates BRMS rule as per Policy Platform and return string contains "[ERR" if there are any errors. - * - * @param rule + * + * @param rule BRMS Rule * @return String error message */ - public static String brmsRawValidate(String rule){ - VerifierBuilder vBuilder = VerifierBuilderFactory.newVerifierBuilder(); - Verifier verifier = vBuilder.newVerifier(); + public static String brmsRawValidate(String rule) { + Verifier verifier = VerifierBuilderFactory.newVerifierBuilder().newVerifier(); verifier.addResourcesToVerify(new ReaderResource(new StringReader(rule)), ResourceType.DRL); - // Check if there are any Errors in Verification. - if(!verifier.getErrors().isEmpty()){ + // Check if there are any Errors in Verification. + if (!verifier.getErrors().isEmpty()) { boolean ignore = false; - StringBuilder message = new StringBuilder("Not a Valid DRL rule"); - for(VerifierError error: verifier.getErrors()){ + StringBuilder message = new StringBuilder("Not a Valid DRL rule"); + for (VerifierError error : verifier.getErrors()) { // Ignore annotations Error Messages - if(!error.getMessage().contains("'@'") && !error.getMessage().contains(PACKAGE_ERROR)){ - ignore= true; + if (!error.getMessage().contains("'@'") && !error.getMessage().contains(PACKAGE_ERROR)) { + ignore = true; message.append("\n" + error.getMessage()); } } // Ignore new package names with '{' // More checks for message to check if its a package error. - if(ignore && !message.toString().contains("Parser returned a null Package")){ + if (ignore && !message.toString().contains("Parser returned a null Package")) { message.append("[ERR 107]"); } return message.toString(); } return ""; } - + /** - * Validates if the given string is proper JSON format. - * - * @param data - * @return + * Validates if the given string is proper JSON format. + * + * @param data JSON data + * @return true if it is JSON */ public static boolean isJSONValid(String data) { - try{ + try { JsonParser parser = new JsonParser(); parser.parse(data); - }catch(JsonSyntaxException e){ - LOGGER.error("Exception Occurred While Validating"+e); + } catch (JsonSyntaxException e) { + LOGGER.error("Exception Occurred While Validating" + e); return false; } return true; } /** - * Validates if the given string is proper XML format. - * - * @param data - * @return + * Validates if the given string is proper XML format. + * + * @param data XML data + * @return true if it is XML */ public static boolean isXMLValid(String data) { - if(data == null || data.isEmpty()){ - return false; + if (data == null || data.isEmpty()) { + return false; } SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(false); factory.setNamespaceAware(true); - - try { - factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + + try { + factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setErrorHandler(new XMLErrorHandler()); reader.parse(new InputSource(new StringReader(data))); } catch (Exception e) { - LOGGER.error("Exception Occured While Validating"+e); + LOGGER.error("Exception Occured While Validating" + e); return false; } return true; } /** - * Validates if given string is valid Properties format. - * - * @param prop - * @return + * Validates if given string is valid Properties format. + * + * @param prop String of properties + * @return is valid property format */ public static boolean isPropValid(String prop) { Scanner scanner = new Scanner(prop); while (scanner.hasNextLine()) { String line = scanner.nextLine(); line = line.replaceAll("\\s+", ""); - if (line.startsWith("#")) { - continue; - } else { + if (! line.startsWith("#")) { if (line.contains("=")) { String[] parts = line.split("="); if (parts.length < 2) { scanner.close(); return false; } - } else if(!line.trim().isEmpty()){ + } else if (!line.trim().isEmpty()) { scanner.close(); return false; } @@ -343,15 +344,15 @@ public class PolicyUtils { scanner.close(); return true; } - + /** * Given a version string consisting of integers with dots between them, convert it into an array of integers. - * - * @param version - * @return - * @throws NumberFormatException + * + * @param version String representing the version + * @return array of int + * @throws NumberFormatException NumberFormatException */ - public static int[] versionStringToArray(String version){ + public static int[] versionStringToArray(String version) { if (version == null || version.length() == 0) { return new int[0]; } @@ -362,4 +363,4 @@ public class PolicyUtils { } return resultArray; } -}
\ No newline at end of file +} diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/XMLErrorHandler.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/XMLErrorHandler.java index 3037a423c..00251ee2d 100644 --- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/XMLErrorHandler.java +++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/XMLErrorHandler.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * PolicyEngineUtils * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -28,7 +28,7 @@ import org.xml.sax.SAXParseException; public class XMLErrorHandler implements ErrorHandler { private static final Logger LOGGER = FlexLogger.getLogger(XMLErrorHandler.class); - + @Override public void warning(SAXParseException exception) throws SAXException { LOGGER.debug(exception); |