summaryrefslogtreecommitdiffstats
path: root/POLICY-SDK-APP
diff options
context:
space:
mode:
authorPamela Dragosh <pdragosh@research.att.com>2019-10-11 08:56:16 -0400
committerPamela Dragosh <pdragosh@research.att.com>2019-10-11 09:53:17 -0400
commitf36e53a3637e1204a42491ec0eeed7b3c763f681 (patch)
tree903cc402afb1228fe8f96c550b2bf01c572fc41e /POLICY-SDK-APP
parentb86c95c99240e8ed0ef91932a70ebed313dbd60c (diff)
More sonar cleanup and line consolidation
Missing javadoc and some variable naming to remove consecutive capitlization of letters. 120 line width reduction Missing curly braces Moving variables due to distance requirements Add missing rawtype suppression or useless ones There are some null return statements that are useless Started doing some combining of lines at the risk of making the code even more unreadable than it already is. Started addressing some nested if's. I see opportunity for a lot of common code to be combined or put into a base controller or utility method. Issue-ID: POLICY-2133 Change-Id: I6d4d9618bea685cf1d02899e3a9d4a43919a2a96 Signed-off-by: Pamela Dragosh <pdragosh@research.att.com>
Diffstat (limited to 'POLICY-SDK-APP')
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPdpProperties.java5
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java21
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java33
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java45
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyUserInfoController.java7
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java17
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java30
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java64
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java51
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java2
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java60
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java7
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java421
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateOptimizationController.java249
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java186
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java132
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java93
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java99
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java72
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java1
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java21
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java28
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java20
23 files changed, 911 insertions, 753 deletions
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPdpProperties.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPdpProperties.java
index 81d3fb564..16b6d0979 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPdpProperties.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPdpProperties.java
@@ -53,7 +53,7 @@ import org.onap.policy.xacml.api.XACMLErrorConstants;
*
* <p>The reset() method has been added to assist with the above problem in order to acquire >80% JUnit code coverage.
*
- * <p>This static class doesn't really check a PDP, it simply loads a properties file and tried to ensure
+ * <p>This static class doesn't really check a PDP, it simply loads a properties file and tried to ensure
* that a valid URL exists for a PDP along with user/password.
*/
public class CheckPdpProperties {
@@ -209,8 +209,7 @@ public class CheckPdpProperties {
LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
}
return encoding;
- } else {
- return null;
}
+ return null;
}
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java
index cff9dd57c..343a19f1a 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java
@@ -69,28 +69,25 @@ public class PolicyAdapter {
}
private String getConfigPolicyName(PolicyRestAdapter policyAdapter) {
- String configPolicyName = null;
if (policyAdapter.getPolicyName().startsWith("Config_PM")) {
- configPolicyName = "ClosedLoop_PM";
+ return "ClosedLoop_PM";
} else if (policyAdapter.getPolicyName().startsWith("Config_Fault")) {
- configPolicyName = "ClosedLoop_Fault";
+ return "ClosedLoop_Fault";
} else if (policyAdapter.getPolicyName().startsWith("Config_FW")) {
- configPolicyName = "Firewall Config";
+ return "Firewall Config";
} else if (policyAdapter.getPolicyName().startsWith("Config_BRMS_Raw")) {
- configPolicyName = "BRMS_Raw";
+ return "BRMS_Raw";
} else if (policyAdapter.getPolicyName().startsWith("Config_BRMS_Param")) {
- configPolicyName = "BRMS_Param";
+ return "BRMS_Param";
} else if (policyAdapter.getPolicyName().startsWith("Config_MS")) {
- configPolicyName = "Micro Service";
+ return "Micro Service";
} else if (policyAdapter.getPolicyName().startsWith("Config_OOF")) {
- configPolicyName = "Optimization";
+ return "Optimization";
} else if (policyAdapter.getPolicyName().startsWith("Action")
|| policyAdapter.getPolicyName().startsWith("Decision")) {
- // No configPolicyName is applicable
- } else {
- configPolicyName = "Base";
+ return null;
}
- return configPolicyName;
+ return "Base";
}
private void prePopulatePolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java
index d4378f4dc..9d6210039 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java
@@ -390,7 +390,6 @@ public class PolicyManagerServlet extends HttpServlet {
}
private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) {
- List<Object> policyData = new ArrayList<>();
JSONArray policyList = null;
if (params.has("policyList")) {
policyList = (JSONArray) params.get("policyList");
@@ -398,7 +397,7 @@ public class PolicyManagerServlet extends HttpServlet {
PolicyController controller = getPolicyControllerInstance();
List<JSONObject> resultList = new ArrayList<>();
try {
- if (!lookupPolicyData(request, policyData, policyList, controller, resultList)) {
+ if (!lookupPolicyData(request, new ArrayList<>(), policyList, controller, resultList)) {
return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
}
} catch (Exception e) {
@@ -411,13 +410,11 @@ public class PolicyManagerServlet extends HttpServlet {
private boolean lookupPolicyData(HttpServletRequest request, List<Object> policyData, JSONArray policyList,
PolicyController controller, List<JSONObject> resultList) {
- List<String> roles;
- Set<String> scopes;// Get the Login Id of the User from Request
String userId = UserUtils.getUserSession(request).getOrgUserId();
List<Object> userRoles = controller.getRoles(userId);
Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
- roles = pair.u;
- scopes = pair.t;
+ List<String> roles = pair.u;
+ Set<String> scopes = pair.t;
if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)) {
if (scopes.isEmpty()) {
return false;
@@ -601,13 +598,12 @@ public class PolicyManagerServlet extends HttpServlet {
} else if (path.contains(DECISION2)) {
path = path.replace(DECISION, DECISION1);
}
- PolicyController controller = getPolicyControllerInstance();
String[] split = path.split(":");
String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
SimpleBindings peParams = new SimpleBindings();
peParams.put(SPLIT_1, split[1]);
peParams.put(SPLIT_0, split[0]);
- List<Object> queryData = getDataByQueryFromController(controller, query, peParams);
+ List<Object> queryData = getDataByQueryFromController(getPolicyControllerInstance(), query, peParams);
if (queryData.isEmpty()) {
return error("Error Occured while Describing the Policy - query is empty");
}
@@ -645,11 +641,10 @@ public class PolicyManagerServlet extends HttpServlet {
}
private JSONObject processPolicyList(JSONObject params, HttpServletRequest request) throws ServletException {
- PolicyController controller = getPolicyControllerInstance();
// Get the Login Id of the User from Request
String testUserID = getTestUserId();
String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId();
- List<Object> userRoles = controller.getRoles(userId);
+ List<Object> userRoles = getPolicyControllerInstance().getRoles(userId);
Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
List<String> roles = pair.u;
Set<String> scopes = pair.t;
@@ -741,7 +736,6 @@ public class PolicyManagerServlet extends HttpServlet {
// Get Active Policy List based on Scope Selection from Policy Version table
private void activePolicyList(String inScopeName, List<JSONObject> resultList, List<String> roles,
Set<String> scopes, Map<String, String> roleByScope) {
- final PolicyController controller = getPolicyControllerInstance();
String scopeName = inScopeName;
if (scopeName.contains(FORWARD_SLASH)) {
scopeName = scopeName.replace(FORWARD_SLASH, File.separator);
@@ -754,8 +748,8 @@ public class PolicyManagerServlet extends HttpServlet {
SimpleBindings params = new SimpleBindings();
params.put(SCOPE_NAME, scopeName + "%");
- List<Object> activePolicies = getDataByQueryFromController(controller, query, params);
- List<Object> scopesList = getDataByQueryFromController(controller,
+ List<Object> activePolicies = getDataByQueryFromController(getPolicyControllerInstance(), query, params);
+ List<Object> scopesList = getDataByQueryFromController(getPolicyControllerInstance(),
FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME, params);
for (Object list : scopesList) {
scopeName = checkScope(resultList, scopeName, (PolicyEditorScopes) list, roleByScope);
@@ -845,8 +839,8 @@ public class PolicyManagerServlet extends HttpServlet {
}
private String getUserName(String loginId) {
- PolicyController controller = getPolicyControllerInstance();
- UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId);
+ UserInfo userInfo = (UserInfo) getPolicyControllerInstance().getEntityItem(UserInfo.class, "userLoginId",
+ loginId);
if (userInfo == null) {
return SUPERADMIN;
}
@@ -1543,7 +1537,6 @@ public class PolicyManagerServlet extends HttpServlet {
private JSONObject editFile(JSONObject params) throws ServletException {
// get content
try {
- final PolicyController controller = getPolicyControllerInstance();
final String mode = params.getString("mode");
String path = params.getString("path");
LOGGER.debug("editFile path: {}" + path);
@@ -1560,7 +1553,7 @@ public class PolicyManagerServlet extends HttpServlet {
SimpleBindings peParams = new SimpleBindings();
peParams.put(SPLIT_1, split[1]);
peParams.put(SPLIT_0, split[0]);
- List<Object> queryData = getDataByQueryFromController(controller, query, peParams);
+ List<Object> queryData = getDataByQueryFromController(getPolicyControllerInstance(), query, peParams);
PolicyEntity entity = (PolicyEntity) queryData.get(0);
InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8));
@@ -1599,7 +1592,6 @@ public class PolicyManagerServlet extends HttpServlet {
// Add Scopes
private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException {
- PolicyController controller = getPolicyControllerInstance();
try {
String name = getNameFromParams(params);
String validateName =
@@ -1614,7 +1606,8 @@ public class PolicyManagerServlet extends HttpServlet {
name = name.substring(1);
}
PolicyEditorScopes entity =
- (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, SCOPE_NAME, name);
+ (PolicyEditorScopes) getPolicyControllerInstance().getEntityItem(
+ PolicyEditorScopes.class, SCOPE_NAME, name);
if (entity != null) {
return error("Scope Already Exists");
}
@@ -1625,7 +1618,7 @@ public class PolicyManagerServlet extends HttpServlet {
newScope.setScopeName(name);
newScope.setUserCreatedBy(userInfo);
newScope.setUserModifiedBy(userInfo);
- controller.saveData(newScope);
+ getPolicyControllerInstance().saveData(newScope);
}
return success();
} catch (Exception e) {
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java
index 79b08d2ea..12d3fc334 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java
@@ -132,11 +132,10 @@ public class PolicyRestController extends RestrictedBaseController {
*/
@RequestMapping(value = {"/policycreation/save_policy"}, method = {RequestMethod.POST})
public void policyCreationController(HttpServletRequest request, HttpServletResponse response) {
- String userId = UserUtils.getUserSession(request).getOrgUserId();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try {
- updateAndSendToPap(request, response, userId, mapper);
+ updateAndSendToPap(request, response, UserUtils.getUserSession(request).getOrgUserId(), mapper);
} catch (Exception e) {
policyLogger.error("Exception Occured while saving policy", e);
}
@@ -171,9 +170,8 @@ public class PolicyRestController extends RestrictedBaseController {
policyData.setUserId(userId);
String result;
- String body = PolicyUtils.objectToJsonString(policyData);
- String uri = request.getRequestURI();
- ResponseEntity<?> responseEntity = sendToPap(body, uri, HttpMethod.POST);
+ ResponseEntity<?> responseEntity = sendToPap(PolicyUtils.objectToJsonString(policyData),
+ request.getRequestURI(), HttpMethod.POST);
if (responseEntity != null && responseEntity.getBody().equals(HttpServletResponse.SC_CONFLICT)) {
result = "PolicyExists";
} else if (responseEntity != null) {
@@ -236,10 +234,10 @@ public class PolicyRestController extends RestrictedBaseController {
private ResponseEntity<?> sendToPap(String body, String requestUri, HttpMethod method) {
String papUrl = PolicyController.getPapUrl();
- String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
String papPass = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
- Base64.Encoder encoder = Base64.getEncoder();
- String encoding = encoder.encodeToString((papID + ":" + papPass).getBytes(StandardCharsets.UTF_8));
+ String encoding = Base64.getEncoder().encodeToString(
+ (XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID)
+ + ":" + papPass).getBytes(StandardCharsets.UTF_8));
HttpHeaders headers = new HttpHeaders();
headers.set(AUTHORIZATION, BASIC + encoding);
headers.set(CONTENT_TYPE, PolicyController.getContenttype());
@@ -286,25 +284,23 @@ public class PolicyRestController extends RestrictedBaseController {
}
private String callPap(HttpServletRequest request, String method, String uriValue) {
- String papUrl = PolicyController.getPapUrl();
- String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY));
String papPass = PeCryptoUtils.decrypt((XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)));
Base64.Encoder encoder = Base64.getEncoder();
- String encoding = encoder.encodeToString((papID + ":" + papPass).getBytes(StandardCharsets.UTF_8));
+ String encoding = encoder.encodeToString((XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID)
+ + ":" + papPass).getBytes(StandardCharsets.UTF_8));
HttpHeaders headers = new HttpHeaders();
headers.set(AUTHORIZATION, BASIC + encoding);
headers.set(CONTENT_TYPE, PolicyController.getContenttype());
HttpURLConnection connection = null;
- List<FileItem> items;
FileItem item = null;
File file = null;
String uri = uriValue;
if (uri.contains(IMPORT_DICTIONARY)) {
try {
- items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
+ List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
item = items.get(0);
file = new File(item.getName());
String newFile = file.toString();
@@ -315,7 +311,7 @@ public class PolicyRestController extends RestrictedBaseController {
}
try {
- URL url = new URL(papUrl + uri);
+ URL url = new URL(PolicyController.getPapUrl() + uri);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(method);
connection.setUseCaches(false);
@@ -358,7 +354,6 @@ public class PolicyRestController extends RestrictedBaseController {
private void checkUri(HttpServletRequest request, String uri, HttpURLConnection connection, FileItem item)
throws IOException {
- String boundary;
if (!(uri.endsWith("set_BRMSParamData") || uri.contains(IMPORT_DICTIONARY))) {
connection.setRequestProperty(CONTENT_TYPE, PolicyController.getContenttype());
ObjectMapper mapper = new ObjectMapper();
@@ -385,7 +380,7 @@ public class PolicyRestController extends RestrictedBaseController {
IOUtils.copy(request.getInputStream(), os);
}
} else {
- boundary = "===" + System.currentTimeMillis() + "===";
+ String boundary = "===" + System.currentTimeMillis() + "===";
connection.setRequestProperty(CONTENT_TYPE, "multipart/form-data; boundary=" + boundary);
try (OutputStream os = connection.getOutputStream()) {
if (item != null) {
@@ -407,8 +402,7 @@ public class PolicyRestController extends RestrictedBaseController {
private String doConnect(final HttpURLConnection connection) throws IOException {
connection.connect();
- int responseCode = connection.getResponseCode();
- if (responseCode == 200) {
+ if (connection.getResponseCode() == 200) {
// get the response content into a String
String responseJson = null;
// read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
@@ -438,9 +432,9 @@ public class PolicyRestController extends RestrictedBaseController {
*/
@RequestMapping(value = {"/getDictionary/*"}, method = {RequestMethod.GET})
public void getDictionaryController(HttpServletRequest request, HttpServletResponse response) {
- String uri = request.getRequestURI().replace("/getDictionary", "");
String body;
- ResponseEntity<?> responseEntity = sendToPap(null, uri, HttpMethod.GET);
+ ResponseEntity<?> responseEntity = sendToPap(null, request.getRequestURI().replace("/getDictionary", ""),
+ HttpMethod.GET);
if (responseEntity != null) {
body = responseEntity.getBody().toString();
} else {
@@ -542,8 +536,7 @@ public class PolicyRestController extends RestrictedBaseController {
data.add("Elastic Search Server is down");
resultList = data;
} else {
- JSONObject json = new JSONObject(body);
- resultList = json.get("policyresult");
+ resultList = new JSONObject(body).get("policyresult");
}
} catch (Exception e) {
policyLogger.error(
@@ -555,9 +548,7 @@ public class PolicyRestController extends RestrictedBaseController {
response.setCharacterEncoding(PolicyController.getCharacterencoding());
response.setContentType(PolicyController.getContenttype());
- PrintWriter out = response.getWriter();
- JSONObject json = new JSONObject("{result: " + resultList + "}");
- out.write(json.toString());
+ response.getWriter().write(new JSONObject("{result: " + resultList + "}").toString());
return null;
}
@@ -595,9 +586,7 @@ public class PolicyRestController extends RestrictedBaseController {
response.setContentType("application / json");
request.setCharacterEncoding(UTF_8);
- PrintWriter out = response.getWriter();
- JSONObject json2 = new JSONObject("{result: " + resultList + "}");
- out.write(json2.toString());
+ response.getWriter().write(new JSONObject("{result: " + resultList + "}").toString());
return null;
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyUserInfoController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyUserInfoController.java
index 416318817..9cf647954 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyUserInfoController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyUserInfoController.java
@@ -53,15 +53,12 @@ public class PolicyUserInfoController extends RestrictedBaseController {
*/
@RequestMapping(value = "/get_PolicyUserInfo", method = RequestMethod.GET)
public void getPolicyUserInfo(HttpServletRequest request, HttpServletResponse response) {
- JsonMessage msg;
try {
String userId = UserUtils.getUserSession(request).getOrgUserId();
Map<String, Object> model = new HashMap<>();
- ObjectMapper mapper = new ObjectMapper();
model.put("userid", userId);
- msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject json = new JSONObject(msg);
- response.getWriter().write(json.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(
+ new ObjectMapper().writeValueAsString(model))).toString());
} catch (Exception e) {
LOGGER.error("Exception Occurred" + e);
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java
index 9f89ea0cf..c83cb777d 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java
@@ -8,9 +8,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -36,7 +36,6 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType;
@@ -66,6 +65,11 @@ public class ActionPolicyController extends RestrictedBaseController {
// Default Constructor
}
+ /**
+ * prePopulateActionPolicyData.
+ *
+ * @param policyAdapter PolicyRestAdapter
+ */
public void prePopulateActionPolicyData(PolicyRestAdapter policyAdapter) {
ruleAlgorithmList = new ArrayList<>();
performer.put("PDP", "PDPAction");
@@ -152,11 +156,10 @@ public class ActionPolicyController extends RestrictedBaseController {
policyAdapter.setPolicyDescription(description);
}
- private void setPolicyAdapterRuleAlgorithmschoices(PolicyRestAdapter policyAdapter, RuleType o) {
- ConditionType condition = o.getCondition();
- if (condition != null) {
+ private void setPolicyAdapterRuleAlgorithmschoices(PolicyRestAdapter policyAdapter, RuleType ruleType) {
+ if (ruleType.getCondition() != null) {
int index = 0;
- ApplyType actionApply = (ApplyType) condition.getExpression().getValue();
+ ApplyType actionApply = (ApplyType) ruleType.getCondition().getExpression().getValue();
ruleAlgorithmTracker = new LinkedList<>();
// Populating Rule Algorithms starting from compound.
prePopulateCompoundRuleAlgorithm(index, actionApply);
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java
index 92f125a7d..0ab266071 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java
@@ -74,6 +74,12 @@ public class AdminTabController extends RestrictedBaseController {
AdminTabController.commonClassDao = commonClassDao;
}
+ /**
+ * getAdminTabEntityData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
@RequestMapping(
value = {"/get_LockDownData"},
method = {org.springframework.web.bind.annotation.RequestMethod.GET},
@@ -83,14 +89,20 @@ public class AdminTabController extends RestrictedBaseController {
Map<String, Object> model = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();
model.put("lockdowndata", mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class)));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
LOGGER.error("Exception Occured" + e);
}
}
+ /**
+ * saveAdminTabLockdownValue.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ * @return ModelAndView object
+ * @throws IOException IOException
+ */
@RequestMapping(
value = {"/adminTabController/save_LockDownValue.htm"},
method = {org.springframework.web.bind.annotation.RequestMethod.POST})
@@ -101,10 +113,10 @@ public class AdminTabController extends RestrictedBaseController {
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
String userId = UserUtils.getUserSession(request).getOrgUserId();
LOGGER.info(
- "****************************************Logging UserID for Application Lockdown Function*****************************************");
+ "********************Logging UserID for Application Lockdown Function**************************");
LOGGER.info("UserId: " + userId);
LOGGER.info(
- "*********************************************************************************************************************************");
+ "**********************************************************************************************");
JsonNode root = mapper.readTree(request.getReader());
GlobalRoleSettings globalRole =
mapper.readValue(root.get("lockdowndata").toString(), GlobalRoleSettings.class);
@@ -115,19 +127,17 @@ public class AdminTabController extends RestrictedBaseController {
response.setContentType("application / json");
request.setCharacterEncoding(CHARACTER_ENCODING);
- PrintWriter out = response.getWriter();
String responseString = mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class));
- JSONObject j = new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString + "}");
- out.write(j.toString());
+ response.getWriter().write(new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString
+ + "}").toString());
return null;
} catch (Exception e) {
LOGGER.error("Exception Occured" + e);
response.setCharacterEncoding(CHARACTER_ENCODING);
request.setCharacterEncoding(CHARACTER_ENCODING);
- PrintWriter out = response.getWriter();
- out.write(PolicyUtils.CATCH_EXCEPTION);
+ response.getWriter().write(PolicyUtils.CATCH_EXCEPTION);
}
return null;
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java
index ca62d82a4..f97a131a0 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java
@@ -32,7 +32,6 @@ import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
-import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -99,6 +98,9 @@ public class AutoPushController extends RestrictedBaseController {
this.policyController = policyController;
}
+ /**
+ * refreshGroups.
+ */
public synchronized void refreshGroups() {
synchronized (this.groups) {
this.groups.clear();
@@ -124,6 +126,12 @@ public class AutoPushController extends RestrictedBaseController {
return scopes;
}
+ /**
+ * getPolicyGroupContainerData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
@RequestMapping(
value = {"/get_AutoPushPoliciesContainerData"},
method = {RequestMethod.GET},
@@ -169,18 +177,25 @@ public class AutoPushController extends RestrictedBaseController {
ObjectMapper mapper = new ObjectMapper();
model.put("policydatas", mapper.writeValueAsString(data));
JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ response.getWriter().write(new JSONObject(msg).toString());
} catch (Exception e) {
logger.error("Exception Occurred" + e);
}
}
+ /**
+ * pushPolicyToPDPGroup.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ * @return ModelAndView
+ * @throws IOException IOException
+ */
@RequestMapping(value = {"/auto_Push/PushPolicyToPDP.htm"}, method = {RequestMethod.POST})
public ModelAndView pushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response)
throws IOException {
try {
- ArrayList<Object> selectedPDPS = new ArrayList<>();
+ ArrayList<Object> selectedPdps = new ArrayList<>();
ArrayList<String> selectedPoliciesInUI = new ArrayList<>();
PolicyController controller = getPolicyControllerInstance();
this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
@@ -191,17 +206,17 @@ public class AutoPushController extends RestrictedBaseController {
String userId = UserUtils.getUserSession(request).getOrgUserId();
logger.info(
- "****************************************Logging UserID while Pushing Policy to PDP Group*****************************************");
+ "**********************Logging UserID while Pushing Policy to PDP Group***********************");
logger.info("UserId: " + userId + "Push Policy Data: " + root.get("pushTabData").toString());
logger.info(
- "***********************************************************************************************************************************");
+ "**********************************************************************************************");
AutoPushTabAdapter adapter = mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class);
for (Object pdpGroupId : adapter.getPdpDatas()) {
- LinkedHashMap<?, ?> selectedPDP = (LinkedHashMap<?, ?>) pdpGroupId;
+ LinkedHashMap<?, ?> selectedPdp = (LinkedHashMap<?, ?>) pdpGroupId;
for (OnapPDPGroup pdpGroup : this.groups) {
- if (pdpGroup.getId().equals(selectedPDP.get("id"))) {
- selectedPDPS.add(pdpGroup);
+ if (pdpGroup.getId().equals(selectedPdp.get("id"))) {
+ selectedPdps.add(pdpGroup);
}
}
}
@@ -213,7 +228,7 @@ public class AutoPushController extends RestrictedBaseController {
selectedPoliciesInUI.add(policyName);
}
- for (Object pdpDestinationGroupId : selectedPDPS) {
+ for (Object pdpDestinationGroupId : selectedPdps) {
Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
Set<PDPPolicy> selectedPolicies = new HashSet<>();
for (String policyId : selectedPoliciesInUI) {
@@ -259,10 +274,9 @@ public class AutoPushController extends RestrictedBaseController {
BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
bw.write(policyEntity.getPolicyData());
bw.close();
- URI selectedURI = temp.toURI();
try {
// Create the policy
- selectedPolicy = new StdPDPPolicy(name, true, id, selectedURI);
+ selectedPolicy = new StdPDPPolicy(name, true, id, temp.toURI());
} catch (IOException e) {
logger.error("Unable to create policy '" + name + "': " + e.getMessage(), e);
}
@@ -328,8 +342,7 @@ public class AutoPushController extends RestrictedBaseController {
PrintWriter out = response.getWriter();
refreshGroups();
JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
- JSONObject j = new JSONObject(msg);
- out.write(j.toString());
+ out.write(new JSONObject(msg).toString());
//
// Why is this here? This defeats the purpose of the loop??
// Sonar says to remove it or make it conditional
@@ -339,13 +352,15 @@ public class AutoPushController extends RestrictedBaseController {
} catch (Exception e) {
response.setCharacterEncoding(UTF8);
request.setCharacterEncoding(UTF8);
- PrintWriter out = response.getWriter();
logger.error(e);
- out.write(PolicyUtils.CATCH_EXCEPTION);
+ response.getWriter().write(PolicyUtils.CATCH_EXCEPTION);
}
return null;
}
+ /**
+ * removePDPGroup.
+ */
@SuppressWarnings("unchecked")
@RequestMapping(value = {"/auto_Push/remove_GroupPolicies.htm"}, method = {RequestMethod.POST})
public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
@@ -355,16 +370,16 @@ public class AutoPushController extends RestrictedBaseController {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JsonNode root = mapper.readTree(request.getReader());
- StdPDPGroup group = mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class);
- JsonNode removePolicyData = root.get("data");
+ final StdPDPGroup group = mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class);
+ final JsonNode removePolicyData = root.get("data");
String userId = UserUtils.getUserSession(request).getOrgUserId();
logger.info(
- "****************************************Logging UserID while Removing Policy from PDP Group*****************************************");
+ "**********************Logging UserID while Removing Policy from PDP Group*********************");
logger.info("UserId: " + userId + "PDP Group Data: " + root.get("activePdpGroup").toString()
+ "Remove Policy Data: " + root.get("data"));
logger.info(
- "***********************************************************************************************************************************");
+ "**********************************************************************************************");
policyContainer = new PDPPolicyContainer(group);
if (removePolicyData.size() > 0) {
@@ -388,18 +403,13 @@ public class AutoPushController extends RestrictedBaseController {
PrintWriter out = response.getWriter();
refreshGroups();
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
- JSONObject j = new JSONObject(msg);
-
- out.write(j.toString());
-
+ out.write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString());
return null;
} catch (Exception e) {
response.setCharacterEncoding(UTF8);
request.setCharacterEncoding(UTF8);
- PrintWriter out = response.getWriter();
logger.error(e);
- out.write(PolicyUtils.CATCH_EXCEPTION);
+ response.getWriter().write(PolicyUtils.CATCH_EXCEPTION);
}
return null;
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java
index 33b780348..fa515b202 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java
@@ -26,7 +26,6 @@ import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
-import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@@ -104,6 +103,12 @@ public class CreateBRMSParamController extends RestrictedBaseController {
private static String brmsTemplateVlaue = "<$%BRMSParamTemplate=";
private static String string = "String";
+ /**
+ * getBRMSParamPolicyRuleData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
@RequestMapping(value = {"/policyController/getBRMSTemplateData.htm"}, method = {RequestMethod.POST})
public void getBRMSParamPolicyRuleData(HttpServletRequest request, HttpServletResponse response) {
try {
@@ -117,10 +122,8 @@ public class CreateBRMSParamController extends RestrictedBaseController {
response.setContentType(PolicyController.getContenttype());
request.setCharacterEncoding(PolicyController.getCharacterencoding());
- PrintWriter out = response.getWriter();
- String responseString = mapper.writeValueAsString(dynamicLayoutMap);
- JSONObject j = new JSONObject("{policyData: " + responseString + "}");
- out.write(j.toString());
+ response.getWriter().write(new JSONObject("{policyData: " + mapper.writeValueAsString(dynamicLayoutMap)
+ + "}").toString());
} catch (Exception e) {
policyLogger.error("Exception Occured while getting BRMS Rule data", e);
}
@@ -129,8 +132,7 @@ public class CreateBRMSParamController extends RestrictedBaseController {
private String findRule(String ruleTemplate) {
List<Object> datas = commonClassDao.getDataById(BRMSParamTemplate.class, "ruleName", ruleTemplate);
if (CollectionUtils.isNotEmpty(datas)) {
- BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate) datas.get(0);
- return bRMSParamTemplate.getRule();
+ return ((BRMSParamTemplate) datas.get(0)).getRule();
}
return null;
}
@@ -273,7 +275,7 @@ public class CreateBRMSParamController extends RestrictedBaseController {
// Generate Param UI
try {
- paramUIGenerate(policyAdapter, entity);
+ paramUiGenerate(policyAdapter, entity);
} catch (Exception e) {
policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() + e);
}
@@ -283,7 +285,7 @@ public class CreateBRMSParamController extends RestrictedBaseController {
if (policyAdapter.getDynamicLayoutMap().size() > 0) {
LinkedHashMap<String, String> drlRule = policyAdapter.getDynamicLayoutMap().keySet().stream()
.collect(Collectors.toMap(String::toString,
- keyValue -> policyAdapter.getDynamicLayoutMap().get(keyValue), (a, b) -> b,
+ keyValue -> policyAdapter.getDynamicLayoutMap().get(keyValue), (a, b) -> b,
LinkedHashMap::new));
policyAdapter.setRuleData(drlRule);
}
@@ -328,11 +330,10 @@ public class CreateBRMSParamController extends RestrictedBaseController {
private void setDataToAdapterFromTarget(TargetType target, PolicyRestAdapter policyAdapter) {
// Under target we have AnyOFType
- List<AnyOfType> anyOfList = target.getAnyOf();
- if (anyOfList == null) {
+ if (target.getAnyOf() == null) {
return;
}
- anyOfList.stream().map(AnyOfType::getAllOf).filter(Objects::nonNull).flatMap(Collection::stream)
+ target.getAnyOf().stream().map(AnyOfType::getAllOf).filter(Objects::nonNull).flatMap(Collection::stream)
.forEach(allOf -> setDataToAdapterFromMatchList(allOf.getMatch(), policyAdapter));
}
@@ -367,7 +368,7 @@ public class CreateBRMSParamController extends RestrictedBaseController {
}
// This method generates the UI from rule configuration
- private void paramUIGenerate(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
+ private void paramUiGenerate(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
String data = entity.getConfigurationData().getConfigBody();
if (data == null) {
return;
@@ -473,7 +474,12 @@ public class CreateBRMSParamController extends RestrictedBaseController {
return line;
}
- // set View Rule
+ /**
+ * setViewRule.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
@SuppressWarnings("unchecked")
@RequestMapping(value = {"/policyController/ViewBRMSParamPolicyRule.htm"}, method = {RequestMethod.POST})
public void setViewRule(HttpServletRequest request, HttpServletResponse response) {
@@ -492,7 +498,8 @@ public class CreateBRMSParamController extends RestrictedBaseController {
String body = findRule(policyData.getRuleName()) + "\n";
StringBuilder generatedMetadata = new StringBuilder().append(
- "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t ")
+ "/* Autogenerated Code Please Don't change/remove this comment section. "
+ + "This is for the UI purpose. \n\t ")
.append(brmsTemplateVlaue).append(policyData.getRuleName()).append("%$> \n */ \n");
if (policyData.getDynamicLayoutMap().size() > 0) {
@@ -517,26 +524,22 @@ public class CreateBRMSParamController extends RestrictedBaseController {
// Finding all the keys in the Map data-structure.
Set<String> keySet = copyMap.keySet();
Iterator<String> iterator = keySet.iterator();
- Pattern p;
- Matcher m;
while (iterator.hasNext()) {
// Converting the first character of the key into a lower case.
String input = iterator.next();
String output = Character.toLowerCase(input.charAt(0)) + (input.length() > 1 ? input.substring(1) : "");
// Searching for a pattern in the String using the key.
- p = Pattern.compile("\\$\\{" + output + "\\}");
- m = p.matcher(body);
+ Pattern pattern = Pattern.compile("\\$\\{" + output + "\\}");
+ Matcher matcher = pattern.matcher(body);
// Replacing the value with the inputs provided by the user in the editor.
- body = m.replaceAll(copyMap.get(input));
+ body = matcher.replaceAll(copyMap.get(input));
}
response.setCharacterEncoding("UTF-8");
response.setContentType("application / json");
request.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
- String responseString = mapper.writeValueAsString(body);
- JSONObject j = new JSONObject("{policyData: " + responseString + "}");
- out.write(j.toString());
+ response.getWriter().write(new JSONObject("{policyData: " + mapper.writeValueAsString(body)
+ + "}").toString());
} catch (Exception e) {
policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java
index 9974292fb..081b33cc0 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java
@@ -53,7 +53,6 @@ public class CreateBRMSRawController {
protected PolicyRestAdapter policyAdapter = null;
- @SuppressWarnings("unchecked")
public void prePopulateBRMSRawPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
if (policyAdapter.getPolicyData() instanceof PolicyType) {
@@ -136,6 +135,7 @@ public class CreateBRMSRawController {
policyAdapter.setPolicyDescription(description);
}
+ @SuppressWarnings("unchecked")
private void setPolicyAdapterAttributes(final PolicyRestAdapter policyAdapter, final PolicyType policy) {
ArrayList<Object> attributeList = new ArrayList<>();
AdviceExpressionsType expressionTypes =
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java
index f27941832..062ed2afa 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java
@@ -24,7 +24,6 @@ package org.onap.policy.controller;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.ObjectWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
@@ -91,17 +90,24 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
// Empty constructor
}
+ /**
+ * setDataToPolicyRestAdapter.
+ *
+ * @param policyData PolicyRestAdapter
+ * @param root JsonNode
+ * @return PolicyRestAdapter
+ */
public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) {
try {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- ClosedLoopFaultTrapDatas trapDatas =
+ final ClosedLoopFaultTrapDatas trapDatas =
mapper.readValue(root.get("trapData").toString(), ClosedLoopFaultTrapDatas.class);
- ClosedLoopFaultTrapDatas faultDatas =
+ final ClosedLoopFaultTrapDatas faultDatas =
mapper.readValue(root.get("faultData").toString(), ClosedLoopFaultTrapDatas.class);
- ClosedLoopGridJSONData policyJsonData =
- mapper.readValue(root.get("policyData").get("policy").toString(), ClosedLoopGridJSONData.class);
- ClosedLoopFaultBody jsonBody = mapper.readValue(
+ final ClosedLoopGridJsonData policyJsonData =
+ mapper.readValue(root.get("policyData").get("policy").toString(), ClosedLoopGridJsonData.class);
+ final ClosedLoopFaultBody jsonBody = mapper.readValue(
root.get("policyData").get("policy").get("jsonBodyData").toString(), ClosedLoopFaultBody.class);
// Build trapSignatureDatas list from faultData
@@ -118,10 +124,10 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
triggerSignatures.setTrapMaxAge(Integer.parseInt(policyData.getTrapMaxAge()));
ClosedLoopFaultTriggerUISignatures uiTriggerSignatures = new ClosedLoopFaultTriggerUISignatures();
if (!trapSignatureDatas.isEmpty()) {
- uiTriggerSignatures.setSignatures(getUITriggerSignature(TRAP, trapSignatureDatas.get(0)));
+ uiTriggerSignatures.setSignatures(getUiTriggerSignature(TRAP, trapSignatureDatas.get(0)));
if (!policyJsonData.getConnecttriggerSignatures().isEmpty()) {
uiTriggerSignatures
- .setConnectSignatures(getUIConnectTraps(policyJsonData.getConnecttriggerSignatures()));
+ .setConnectSignatures(getUiConnectTraps(policyJsonData.getConnecttriggerSignatures()));
}
}
jsonBody.setTriggerSignaturesUsedForUI(uiTriggerSignatures);
@@ -144,19 +150,17 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
faultSignatures.setTimeWindow(Integer.parseInt(policyData.getVerificationclearTimeOut()));
ClosedLoopFaultTriggerUISignatures uifaultSignatures = new ClosedLoopFaultTriggerUISignatures();
if (!faultSignatureDatas.isEmpty()) {
- uifaultSignatures.setSignatures(getUITriggerSignature(FAULT, faultSignatureDatas.get(0)));
+ uifaultSignatures.setSignatures(getUiTriggerSignature(FAULT, faultSignatureDatas.get(0)));
if (!policyJsonData.getConnectVerificationSignatures().isEmpty()) {
uifaultSignatures.setConnectSignatures(
- getUIConnectTraps(policyJsonData.getConnectVerificationSignatures()));
+ getUiConnectTraps(policyJsonData.getConnectVerificationSignatures()));
}
}
jsonBody.setVerificationSignaturesUsedForUI(uifaultSignatures);
jsonBody.setVerificationTimeWindowUsedForUI(Integer.parseInt(policyData.getVerificationclearTimeOut()));
}
jsonBody.setVerificationSignatures(faultSignatures);
- ObjectWriter om = new ObjectMapper().writer();
- String json = om.writeValueAsString(jsonBody);
- policyData.setJsonBody(json);
+ policyData.setJsonBody(new ObjectMapper().writer().writeValueAsString(jsonBody));
} catch (Exception e) {
policyLogger.error("Exception Occured while setting data to Adapter", e);
@@ -165,7 +169,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
}
// TODO: Can getResultBody() and getFaultBody() be merged?
- private String getResultBody(final ClosedLoopGridJSONData policyJsonData, final List<Object> trapSignatureDatas) {
+ private String getResultBody(final ClosedLoopGridJsonData policyJsonData, final List<Object> trapSignatureDatas) {
StringBuilder resultBody = new StringBuilder();
if (!policyJsonData.getConnecttriggerSignatures().isEmpty()) {
resultBody.append("(");
@@ -182,7 +186,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
return resultBody.toString();
}
- private String getFaultBody(final ClosedLoopGridJSONData policyJsonData, final List<Object> faultSignatureDatas) {
+ private String getFaultBody(final ClosedLoopGridJsonData policyJsonData, final List<Object> faultSignatureDatas) {
StringBuilder faultBody = new StringBuilder();
if (!policyJsonData.getConnectVerificationSignatures().isEmpty()) {
faultBody.append("(");
@@ -341,7 +345,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
attributesStr = attributesStr + "(" + readAttributes(objectList, iy) + ")";
} catch (NumberFormatException e) {
try {
- trap1Attrib = getVarbindOID(trap1Attrib);
+ trap1Attrib = getVarbindOid(trap1Attrib);
attributesStr = attributesStr + "(" + URLEncoder.encode(trap1Attrib, ENC_UTF_8) + ")";
} catch (UnsupportedEncodingException e1) {
policyLogger.error("Caused Exception while Encoding Varbind Dictionary Values", e1);
@@ -349,7 +353,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
}
} else {
try {
- trap1Attrib = getVarbindOID(trap1Attrib);
+ trap1Attrib = getVarbindOid(trap1Attrib);
attributesStr = attributesStr + "(" + URLEncoder.encode(trap1Attrib, ENC_UTF_8) + ")";
} catch (UnsupportedEncodingException e) {
policyLogger.error("Caused Exception while Encoding Varbind Dictionary Values", e);
@@ -358,7 +362,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
return attributesStr;
}
- private String getVarbindOID(String attrib) {
+ private String getVarbindOid(String attrib) {
VarbindDictionary varbindId;
try {
varbindId =
@@ -372,7 +376,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
// connect traps data set to JSON Body as String
@SuppressWarnings({"unchecked", "rawtypes"})
- private String getUIConnectTraps(List<Object> connectTrapSignatures) {
+ private String getUiConnectTraps(List<Object> connectTrapSignatures) {
StringBuilder resultBody = new StringBuilder();
String connectMainBody = "";
for (Object connectTrapSignature : connectTrapSignatures) {
@@ -413,7 +417,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
}
// get Trigger signature from JSON body
- private String getUITriggerSignature(String trap, Object object2) {
+ private String getUiTriggerSignature(String trap, Object object2) {
ClosedLoopFaultTrapDatas trapDatas = (ClosedLoopFaultTrapDatas) object2;
List<Object> attributeList = new ArrayList<>();
// Read the Trap
@@ -474,6 +478,12 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
return triggerBody.toString();
}
+ /**
+ * prePopulateClosedLoopFaultPolicyData.
+ *
+ * @param policyAdapter PolicyRestAdapter
+ * @param entity PolicyEntity
+ */
public void prePopulateClosedLoopFaultPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
if (policyAdapter.getPolicyData() instanceof PolicyType) {
PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
@@ -482,7 +492,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
setPolicyAdapterPolicyNameAndDescription(policyAdapter, policy);
// Set PolicyAdapter JsonBodyData, timeout settings
- setClosedLoopJSONFile(policyAdapter, entity);
+ setClosedLoopJsonFile(policyAdapter, entity);
// Get the target data under policy.
TargetType target = policy.getTarget();
@@ -550,11 +560,11 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
policyAdapter.setPolicyDescription(description);
}
- private void setClosedLoopJSONFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
- ObjectMapper mapper = new ObjectMapper();
+ private void setClosedLoopJsonFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
try {
ClosedLoopFaultBody closedLoopBody =
- mapper.readValue(entity.getConfigurationData().getConfigBody(), ClosedLoopFaultBody.class);
+ new ObjectMapper().readValue(entity.getConfigurationData().getConfigBody(),
+ ClosedLoopFaultBody.class);
if ("ACTIVE".equalsIgnoreCase(closedLoopBody.getClosedLoopPolicyStatus())) {
closedLoopBody.setClosedLoopPolicyStatus("Active");
} else {
@@ -580,7 +590,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
@Getter
@Setter
-class ClosedLoopGridJSONData {
+class ClosedLoopGridJsonData {
private String clearTimeOut;
private String trapMaxAge;
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java
index 4862efd06..1ca027b9c 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java
@@ -64,7 +64,7 @@ public class CreateClosedLoopPMController {
setPolicyAdapterNameValueAndDescription(policyAdapter, policy);
// Set PolicyAdapter JsonBodyData
- setClosedLoopJSONFile(policyAdapter, entity);
+ setClosedLoopJsonFile(policyAdapter, entity);
// Get the target data under policy.
TargetType target = policy.getTarget();
@@ -95,11 +95,10 @@ public class CreateClosedLoopPMController {
policyAdapter.setPolicyDescription(description);
}
- private void setClosedLoopJSONFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
- ObjectMapper mapper = new ObjectMapper();
+ private void setClosedLoopJsonFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
try {
ClosedLoopPMBody closedLoopBody =
- mapper.readValue(entity.getConfigurationData().getConfigBody(), ClosedLoopPMBody.class);
+ new ObjectMapper().readValue(entity.getConfigurationData().getConfigBody(), ClosedLoopPMBody.class);
policyAdapter.setJsonBodyData(closedLoopBody);
} catch (IOException e) {
LOGGER.error("Exception Occured" + e);
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java
index 2b7974d4e..c5e29e422 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java
@@ -162,6 +162,13 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
private Map<String, LinkedList<String>> arrayTextList = new HashMap<>();
private Map<String, String> jsonStringValues = new HashMap<>();
+ /**
+ * setDataToPolicyRestAdapter.
+ *
+ * @param policyData PolicyRestAdapter
+ * @param root JsonNode
+ * @return PolicyRestAdapter
+ */
public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) {
String jsonContent = null;
@@ -169,9 +176,9 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
LOGGER.info("policyJSON :" + (root.get(POLICYJSON)).toString());
String tempJson = root.get(POLICYJSON).toString();
- JSONObject policyJSON = new JSONObject(root.get(POLICYJSON).toString());
- if (policyJSON != null) {
- tempJson = saveOriginalJsonObject(policyJSON, jsonStringValues).toString();
+ JSONObject policyJson = new JSONObject(root.get(POLICYJSON).toString());
+ if (policyJson != null) {
+ tempJson = saveOriginalJsonObject(policyJson, jsonStringValues).toString();
}
// ---replace empty value with the value below before calling decodeContent method.
String dummyValue = "*empty-value*" + UUID.randomUUID().toString();
@@ -313,15 +320,11 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
modelName + ":" + versionName);
MicroServiceModels model = null;
boolean ruleCheck = false;
- boolean SymptomRuleCheck = false;
if (!triggerData.isEmpty()) {
model = (MicroServiceModels) triggerData.get(0);
if (model.getRuleFormation() != null) {
microServiceObject.setUiContent(jsonContent);
ruleCheck = true;
- if (model.getRuleFormation().contains("@")) {
- SymptomRuleCheck = true;
- }
}
}
try {
@@ -331,7 +334,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
}
LOGGER.info("input json: " + json);
LOGGER.info("input jsonContent: " + jsonContent);
- String cleanJson = cleanUPJson(json);
+ String cleanJson = cleanUpJson(json);
// --- reset empty value back after called cleanUPJson method and before calling removeNullAttributes
String tempJson =
StringUtils.replaceEach(cleanJson, new String[] {"\"" + dummyValue + "\""}, new String[] {"\"\""});
@@ -345,7 +348,6 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
ObjectMapper mapper = new ObjectMapper();
JsonNode tempJsonNode = mapper.readTree(cleanJson);
if (ruleCheck) {
- // JsonNode tempJsonNode = mapper.readTree(cleanJson);
ObjectNode finalJson = (ObjectNode) tempJsonNode;
JsonNode object = tempJsonNode.get("content");
String primaryKey1 = model.getRuleFormation();
@@ -490,6 +492,12 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
}
}
+ /**
+ * removeNullAttributes.
+ *
+ * @param cleanJson String
+ * @returnString
+ */
public String removeNullAttributes(String cleanJson) {
ObjectMapper mapper = new ObjectMapper();
@@ -533,9 +541,9 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
if (contentChanged) {
// set modified content to cleanJson
- JSONObject jObject = new JSONObject(cleanJson);
- jObject.put("content", removed.toString());
- cleanJson = cleanUPJson(jObject.toString());
+ JSONObject jsonObject = new JSONObject(cleanJson);
+ jsonObject.put("content", removed.toString());
+ cleanJson = cleanUpJson(jsonObject.toString());
}
} catch (IOException e) {
@@ -572,52 +580,69 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
return null;
}
+ /**
+ * removeNull.
+ *
+ * @param array JsonArray
+ * @return JsonArray
+ */
public JsonArray removeNull(JsonArray array) {
JsonArrayBuilder builder = Json.createArrayBuilder();
- int i = 0;
- for (Iterator<JsonValue> it = array.iterator(); it.hasNext(); ++i) {
+ int index = 0;
+ for (Iterator<JsonValue> it = array.iterator(); it.hasNext(); ++index) {
JsonValue value = it.next();
switch (value.getValueType()) {
case ARRAY:
- JsonArray a = removeNull(array.getJsonArray(i));
- if (!a.isEmpty())
- builder.add(a);
+ JsonArray tempArray = removeNull(array.getJsonArray(index));
+ if (!tempArray.isEmpty()) {
+ builder.add(tempArray);
+ }
break;
case OBJECT:
- JsonObject object = removeNull(array.getJsonObject(i));
- if (!object.isEmpty())
+ JsonObject object = removeNull(array.getJsonObject(index));
+ if (!object.isEmpty()) {
builder.add(object);
+ }
break;
case STRING:
- String s = array.getString(i);
- if (s != null && !s.isEmpty())
- builder.add(s);
+ String str = array.getString(index);
+ if (str != null && !str.isEmpty()) {
+ builder.add(str);
+ }
break;
case NUMBER:
- builder.add(array.getJsonNumber(i));
+ builder.add(array.getJsonNumber(index));
break;
case TRUE:
case FALSE:
- builder.add(array.getBoolean(i));
+ builder.add(array.getBoolean(index));
break;
case NULL:
+ default:
break;
}
}
return builder.build();
}
+ /**
+ * removeNull.
+ *
+ * @param obj JsonObject
+ * @return JsonObject
+ */
public JsonObject removeNull(JsonObject obj) {
JsonObjectBuilder builder = Json.createObjectBuilder();
for (Iterator<Entry<String, JsonValue>> it = obj.entrySet().iterator(); it.hasNext();) {
- Entry<String, JsonValue> e = it.next();
- String key = e.getKey();
- JsonValue value = e.getValue();
+ Entry<String, JsonValue> entry = it.next();
+ String key = entry.getKey();
+ JsonValue value = entry.getValue();
switch (value.getValueType()) {
case ARRAY:
JsonArray array = removeNull(obj.getJsonArray(key));
- if (!array.isEmpty())
+ if (!array.isEmpty()) {
builder.add(key, array);
+ }
break;
case OBJECT:
JsonObject object = removeNull(obj.getJsonObject(key));
@@ -633,15 +658,15 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
}
break;
case STRING:
- String s = obj.getString(key);
- if (s != null && !s.isEmpty()) {
+ String str = obj.getString(key);
+ if (str != null && !str.isEmpty()) {
if (!jsonStringValues.isEmpty()) {
String originalValue = getOriginalValue(key);
if (originalValue != null) {
- s = getOriginalValue(key);
+ str = getOriginalValue(key);
}
}
- builder.add(key, s);
+ builder.add(key, str);
}
break;
case NUMBER:
@@ -652,13 +677,20 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
builder.add(key, obj.getBoolean(key));
break;
case NULL:
+ default:
break;
}
}
return builder.build();
}
- public String cleanUPJson(String json) {
+ /**
+ * cleanUpJson.
+ *
+ * @param json String
+ * @return String
+ */
+ public String cleanUpJson(String json) {
String cleanJson = StringUtils.replaceEach(json, new String[] {"\\\\", "\\\\\\", "\\\\\\\\"},
new String[] {"\\", "\\", "\\"});
cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\\\\\"}, new String[] {"\\"});
@@ -679,6 +711,12 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
return cleanJson;
}
+ /**
+ * decodeContent.
+ *
+ * @param jsonNode JsonNode
+ * @return JsonNode
+ */
public JSONObject decodeContent(JsonNode jsonNode) {
Iterator<JsonNode> jsonElements = jsonNode.elements();
Iterator<String> jsonKeys = jsonNode.fieldNames();
@@ -927,21 +965,20 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
response.setContentType("application / json");
request.setCharacterEncoding("UTF-8");
List<Object> list = new ArrayList<>();
- PrintWriter out = response.getWriter();
String responseString = mapper.writeValueAsString(returnModel);
- JSONObject j = null;
+ JSONObject json = null;
if ("".equals(allMnyTrueKeys)) {
- j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",dataOrderInfo:"
+ json = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",dataOrderInfo:"
+ dataOrderInfo + ",headDefautlsData:" + headDefautlsData + "}");
} else {
- j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",allManyTrueKeys: "
- + allMnyTrueKeys + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + headDefautlsData
- + "}");
+ json = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel
+ + ",allManyTrueKeys: " + allMnyTrueKeys + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:"
+ + headDefautlsData + "}");
}
- list.add(j);
- out.write(list.toString());
+ list.add(json);
+ response.getWriter().write(list.toString());
return null;
}
@@ -980,10 +1017,9 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
Map gsonObject = (Map) gson.fromJson(subAttributes, Object.class);
JSONObject object = new JSONObject();
- JSONArray array = new JSONArray();
for (Entry<String, String> keySet : attributeMap.entrySet()) {
- array = new JSONArray();
+ JSONArray array = new JSONArray();
String value = keySet.getValue();
if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) {
array.put(value);
@@ -994,7 +1030,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
}
for (Entry<String, String> keySet : refAttributeMap.entrySet()) {
- array = new JSONArray();
+ JSONArray array = new JSONArray();
String value = keySet.getValue().split(":")[0];
if (gsonObject.containsKey(value)) {
if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) {
@@ -1081,7 +1117,12 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
return json;
}
- // call this method to get all MANY-true properties
+ /**
+ * getManyTrueProperties.
+ *
+ * @param referAttributes String
+ * @return a Set of String
+ */
public Set<String> getManyTrueProperties(String referAttributes) {
LOGGER.info("referAttributes : " + referAttributes);
Set<String> manyTrueProperties = new HashSet<>();
@@ -1112,10 +1153,12 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
private Set<String> getAllKeys(JSONArray arr, Set<String> keys) {
for (int i = 0; i < arr.length(); i++) {
Object obj = arr.get(i);
- if (obj instanceof JSONObject)
+ if (obj instanceof JSONObject) {
keys.addAll(getAllKeys(arr.getJSONObject(i)));
- if (obj instanceof JSONArray)
+ }
+ if (obj instanceof JSONArray) {
keys.addAll(getAllKeys(arr.getJSONArray(i)));
+ }
}
return keys;
@@ -1130,10 +1173,12 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
LOGGER.info("obj : " + obj);
allManyTrueKeys.add(key);
}
- if (obj instanceof JSONObject)
+ if (obj instanceof JSONObject) {
keys.addAll(getAllKeys(json.getJSONObject(key)));
- if (obj instanceof JSONArray)
+ }
+ if (obj instanceof JSONArray) {
keys.addAll(getAllKeys(json.getJSONArray(key)));
+ }
}
return keys;
@@ -1146,21 +1191,16 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
-
- String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
- String servicename = value.split("-v")[0];
- Set<String> returnList = getVersionList(servicename);
response.setCharacterEncoding("UTF-8");
response.setContentType("application / json");
request.setCharacterEncoding("UTF-8");
List<Object> list = new ArrayList<>();
- PrintWriter out = response.getWriter();
- String responseString = mapper.writeValueAsString(returnList);
- JSONObject j = new JSONObject("{dcaeModelVersionData: " + responseString + "}");
- list.add(j);
- out.write(list.toString());
+ String value = mapper.readTree(request.getReader()).get("policyData").toString().replaceAll("^\"|\"$", "");
+ String servicename = value.split("-v")[0];
+ Set<String> returnList = getVersionList(servicename);
+ list.add(new JSONObject("{dcaeModelVersionData: " + mapper.writeValueAsString(returnList) + "}"));
+ response.getWriter().write(list.toString());
return null;
}
@@ -1219,93 +1259,102 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
priorityList.add(String.valueOf(i));
}
model.put("priorityDatas", mapper.writeValueAsString(priorityList));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
LOGGER.error(e);
}
}
+ /**
+ * prePopulateDCAEMSPolicyData.
+ *
+ * @param policyAdapter PolicyRestAdapter
+ * @param entity PolicyEntity
+ */
public void prePopulateDCAEMSPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
- if (policyAdapter.getPolicyData() instanceof PolicyType) {
- Object policyData = policyAdapter.getPolicyData();
- PolicyType policy = (PolicyType) policyData;
- policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
- String policyNameValue =
- policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("MS_") + 3);
- policyAdapter.setPolicyName(policyNameValue);
- String description = "";
- try {
- description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
- } catch (Exception e) {
- LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue, e);
- description = policy.getDescription();
+ if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
+ return;
+ }
+ Object policyData = policyAdapter.getPolicyData();
+ PolicyType policy = (PolicyType) policyData;
+ policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
+ String policyNameValue =
+ policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("MS_") + 3);
+ policyAdapter.setPolicyName(policyNameValue);
+ String description = "";
+ try {
+ description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
+ } catch (Exception e) {
+ LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue, e);
+ description = policy.getDescription();
+ }
+ policyAdapter.setPolicyDescription(description);
+ // Get the target data under policy.
+ TargetType target = policy.getTarget();
+ if (target == null) {
+ return;
+ }
+ // Under target we have AnyOFType
+ List<AnyOfType> anyOfList = target.getAnyOf();
+ if (anyOfList == null) {
+ return;
+ }
+ Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
+ while (iterAnyOf.hasNext()) {
+ AnyOfType anyOf = iterAnyOf.next();
+ // Under AnyOFType we have AllOFType
+ List<AllOfType> allOfList = anyOf.getAllOf();
+ if (allOfList == null) {
+ continue;
}
- policyAdapter.setPolicyDescription(description);
- // Get the target data under policy.
- TargetType target = policy.getTarget();
- if (target != null) {
- // Under target we have AnyOFType
- List<AnyOfType> anyOfList = target.getAnyOf();
- if (anyOfList != null) {
- Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
- while (iterAnyOf.hasNext()) {
- AnyOfType anyOf = iterAnyOf.next();
- // Under AnyOFType we have AllOFType
- List<AllOfType> allOfList = anyOf.getAllOf();
- if (allOfList != null) {
- Iterator<AllOfType> iterAllOf = allOfList.iterator();
- while (iterAllOf.hasNext()) {
- AllOfType allOf = iterAllOf.next();
- // Under AllOFType we have Match
- List<MatchType> matchList = allOf.getMatch();
- if (matchList != null) {
- Iterator<MatchType> iterMatch = matchList.iterator();
- while (matchList.size() > 1 && iterMatch.hasNext()) {
- MatchType match = iterMatch.next();
- //
- // Under the match we have attribute value and
- // attributeDesignator. So,finally down to the actual attribute.
- //
- AttributeValueType attributeValue = match.getAttributeValue();
- String value = (String) attributeValue.getContent().get(0);
- AttributeDesignatorType designator = match.getAttributeDesignator();
- String attributeId = designator.getAttributeId();
- // First match in the target is OnapName, so set that value.
- if ("ONAPName".equals(attributeId)) {
- policyAdapter.setOnapName(value);
- }
- if ("ConfigName".equals(attributeId)) {
- policyAdapter.setConfigName(value);
- }
- if ("uuid".equals(attributeId)) {
- policyAdapter.setUuid(value);
- }
- if ("location".equals(attributeId)) {
- policyAdapter.setLocation(value);
- }
- if ("RiskType".equals(attributeId)) {
- policyAdapter.setRiskType(value);
- }
- if ("RiskLevel".equals(attributeId)) {
- policyAdapter.setRiskLevel(value);
- }
- if ("guard".equals(attributeId)) {
- policyAdapter.setGuard(value);
- }
- if ("TTLDate".equals(attributeId) && !value.contains("NA")) {
- PolicyController controller = new PolicyController();
- String newDate = controller.convertDate(value);
- policyAdapter.setTtlDate(newDate);
- }
- }
- readFile(policyAdapter, entity);
- }
- }
- }
+ Iterator<AllOfType> iterAllOf = allOfList.iterator();
+ while (iterAllOf.hasNext()) {
+ AllOfType allOf = iterAllOf.next();
+ // Under AllOFType we have Match
+ List<MatchType> matchList = allOf.getMatch();
+ if (matchList == null) {
+ continue;
+ }
+ Iterator<MatchType> iterMatch = matchList.iterator();
+ while (matchList.size() > 1 && iterMatch.hasNext()) {
+ MatchType match = iterMatch.next();
+ //
+ // Under the match we have attribute value and
+ // attributeDesignator. So,finally down to the actual attribute.
+ //
+ AttributeValueType attributeValue = match.getAttributeValue();
+ String value = (String) attributeValue.getContent().get(0);
+ AttributeDesignatorType designator = match.getAttributeDesignator();
+ String attributeId = designator.getAttributeId();
+ // First match in the target is OnapName, so set that value.
+ if ("ONAPName".equals(attributeId)) {
+ policyAdapter.setOnapName(value);
+ }
+ if ("ConfigName".equals(attributeId)) {
+ policyAdapter.setConfigName(value);
+ }
+ if ("uuid".equals(attributeId)) {
+ policyAdapter.setUuid(value);
+ }
+ if ("location".equals(attributeId)) {
+ policyAdapter.setLocation(value);
+ }
+ if ("RiskType".equals(attributeId)) {
+ policyAdapter.setRiskType(value);
+ }
+ if ("RiskLevel".equals(attributeId)) {
+ policyAdapter.setRiskLevel(value);
+ }
+ if ("guard".equals(attributeId)) {
+ policyAdapter.setGuard(value);
+ }
+ if ("TTLDate".equals(attributeId) && !value.contains("NA")) {
+ PolicyController controller = new PolicyController();
+ String newDate = controller.convertDate(value);
+ policyAdapter.setTtlDate(newDate);
}
}
+ readFile(policyAdapter, entity);
}
}
}
@@ -1334,12 +1383,11 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
*/
@SuppressWarnings("unchecked")
public void readFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
- String policyScopeName = null;
- ObjectMapper mapper = new ObjectMapper();
try {
DCAEMicroServiceObject msBody =
- mapper.readValue(entity.getConfigurationData().getConfigBody(), DCAEMicroServiceObject.class);
- policyScopeName = getPolicyScope(msBody.getPolicyScope());
+ new ObjectMapper().readValue(entity.getConfigurationData().getConfigBody(),
+ DCAEMicroServiceObject.class);
+ String policyScopeName = getPolicyScope(msBody.getPolicyScope());
policyAdapter.setPolicyScope(policyScopeName);
policyAdapter.setPriority(msBody.getPriority());
@@ -1405,16 +1453,27 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
}
}
+ /**
+ * getPolicyScope.
+ *
+ * @param value String
+ * @return String
+ */
public String getPolicyScope(String value) {
List<Object> groupList = commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList", value);
if (groupList != null && !groupList.isEmpty()) {
- GroupPolicyScopeList pScope = (GroupPolicyScopeList) groupList.get(0);
- return pScope.getGroupName();
+ return ((GroupPolicyScopeList) groupList.get(0)).getGroupName();
}
return null;
}
- // Convert the map values and set into JSON body
+ /**
+ * Convert the map values and set into JSON body.
+ *
+ * @param attributesMap Map of attributes
+ * @param attributesRefMap Map of attribute references
+ * @return Map
+ */
public Map<String, String> convertMap(Map<String, String> attributesMap, Map<String, String> attributesRefMap) {
Map<String, String> attribute = new HashMap<>();
StringBuilder temp;
@@ -1495,35 +1554,31 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
}
if (!errorMsg.isEmpty()) {
-
- PrintWriter out = response.getWriter();
-
response.setCharacterEncoding("UTF-8");
response.setContentType("application / json");
request.setCharacterEncoding("UTF-8");
JSONObject j = new JSONObject();
j.put("errorMsg", errorMsg);
- out.write(j.toString());
+ response.getWriter().write(j.toString());
return;
}
List<File> fileList = new ArrayList<>();
- MSModelUtils msMLUtils = new MSModelUtils(commonClassDao);
+ MSModelUtils msModelUtils = new MSModelUtils(commonClassDao);
this.directory = "model";
if (zip) {
extractFolder(this.newFile);
fileList = listModelFiles(this.directory);
} else if (yml) {
- errorMsg = msMLUtils.parseTosca(this.newFile);
+ errorMsg = msModelUtils.parseTosca(this.newFile);
if (errorMsg != null) {
- PrintWriter out = response.getWriter();
response.setCharacterEncoding("UTF-8");
response.setContentType("application / json");
request.setCharacterEncoding("UTF-8");
- JSONObject j = new JSONObject();
- j.put("errorMsg", errorMsg);
- out.write(j.toString());
+ JSONObject json = new JSONObject();
+ json.put("errorMsg", errorMsg);
+ response.getWriter().write(json.toString());
return;
}
@@ -1554,21 +1609,21 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
msAttributes.setClassName(className);
LinkedHashMap<String, String> returnAttributeList = new LinkedHashMap<>();
- returnAttributeList.put(className, msMLUtils.getAttributeString());
+ returnAttributeList.put(className, msModelUtils.getAttributeString());
msAttributes.setAttribute(returnAttributeList);
- msAttributes.setSubClass(msMLUtils.getRetmap());
+ msAttributes.setSubClass(msModelUtils.getRetmap());
- msAttributes.setMatchingSet(msMLUtils.getMatchableValues());
+ msAttributes.setMatchingSet(msModelUtils.getMatchableValues());
LinkedHashMap<String, String> returnReferenceList = new LinkedHashMap<>();
- returnReferenceList.put(className, msMLUtils.getReferenceAttributes());
+ returnReferenceList.put(className, msModelUtils.getReferenceAttributes());
msAttributes.setRefAttribute(returnReferenceList);
- if (msMLUtils.getListConstraints() != "") {
+ if (msModelUtils.getListConstraints() != "") {
LinkedHashMap<String, String> enumList = new LinkedHashMap<>();
- String[] listArray = msMLUtils.getListConstraints().split("#");
+ String[] listArray = msModelUtils.getListConstraints().split("#");
for (String str : listArray) {
String[] strArr = str.split("=");
if (strArr.length > 1) {
@@ -1582,22 +1637,19 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
classMap.put(className, msAttributes);
}
-
- PrintWriter out = response.getWriter();
-
response.setCharacterEncoding("UTF-8");
response.setContentType("application / json");
request.setCharacterEncoding("UTF-8");
ObjectMapper mapper = new ObjectMapper();
- JSONObject j = new JSONObject();
- j.put("classListDatas", modelList);
- j.put("modelDatas", mapper.writeValueAsString(classMap));
- j.put("modelType", modelType);
- j.put("dataOrderInfo", msMLUtils.getDataOrderInfo());
- j.put("ruleFormation", msMLUtils.getJsonRuleFormation());
-
- out.write(j.toString());
+ JSONObject json = new JSONObject();
+ json.put("classListDatas", modelList);
+ json.put("modelDatas", mapper.writeValueAsString(classMap));
+ json.put("modelType", modelType);
+ json.put("dataOrderInfo", msModelUtils.getDataOrderInfo());
+ json.put("ruleFormation", msModelUtils.getJsonRuleFormation());
+
+ response.getWriter().write(json.toString());
}
/*
@@ -1605,7 +1657,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
*/
@SuppressWarnings("rawtypes")
private void extractFolder(String zipFile) {
- int BUFFER = 2048;
+ int buffer = 2048;
File file = new File(zipFile);
try (ZipFile zip = new ZipFile(file)) {
@@ -1628,10 +1680,10 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
if (!entry.isDirectory()) {
BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
int currentByte;
- byte[] data = new byte[BUFFER];
+ byte[] data = new byte[buffer];
try (FileOutputStream fos = new FileOutputStream(destFile);
- BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER)) {
- while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
+ BufferedOutputStream dest = new BufferedOutputStream(fos, buffer)) {
+ while ((currentByte = is.read(data, 0, buffer)) != -1) {
dest.write(data, 0, currentByte);
}
dest.flush();
@@ -1670,8 +1722,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
private List<File> listModelFiles(String directoryName) {
File fileDirectory = new File(directoryName);
List<File> resultList = new ArrayList<>();
- File[] fList = fileDirectory.listFiles();
- for (File file : fList) {
+ for (File file : fileDirectory.listFiles()) {
if (file.isFile()) {
resultList.add(file);
} else if (file.isDirectory()) {
@@ -1682,6 +1733,11 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
return resultList;
}
+ /**
+ * cleanUp.
+ *
+ * @param path String
+ */
public void cleanUp(String path) {
if (path != null) {
try {
@@ -1692,6 +1748,11 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
}
}
+ /**
+ * checkZipDirectory.
+ *
+ * @param zipDirectory String
+ */
public void checkZipDirectory(String zipDirectory) {
Path path = Paths.get(zipDirectory);
@@ -1702,9 +1763,9 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
private List<String> createList() {
List<String> list = new ArrayList<>();
- for (Entry<String, MSAttributeObject> cMap : classMap.entrySet()) {
- if (cMap.getValue().isPolicyTempalate()) {
- list.add(cMap.getKey());
+ for (Entry<String, MSAttributeObject> entrySet : classMap.entrySet()) {
+ if (entrySet.getValue().isPolicyTempalate()) {
+ list.add(entrySet.getKey());
}
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateOptimizationController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateOptimizationController.java
index b77f6a7d2..74a1ed016 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateOptimizationController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateOptimizationController.java
@@ -91,6 +91,9 @@ import org.springframework.web.servlet.ModelAndView;
@RequestMapping("/")
public class CreateOptimizationController extends RestrictedBaseController {
private static final Logger LOGGER = FlexLogger.getLogger(CreateOptimizationController.class);
+
+ private static final int BUFFER = 2048;
+
private static CommonClassDao commonClassDao;
public static CommonClassDao getCommonClassDao() {
@@ -178,7 +181,7 @@ public class CreateOptimizationController extends RestrictedBaseController {
}
LOGGER.info("input json: " + json);
LOGGER.info("input jsonContent: " + jsonContent);
- String cleanJson = msController.cleanUPJson(json);
+ String cleanJson = msController.cleanUpJson(json);
// --- reset empty value back after called cleanUPJson method and before calling removeNullAttributes
String tempJson =
@@ -189,6 +192,14 @@ public class CreateOptimizationController extends RestrictedBaseController {
return policyAdapter;
}
+ /**
+ * getOptimizationTemplateData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ * @return ModelAndView
+ * @throws IOException IOException
+ */
@RequestMapping(
value = {"/policyController/getOptimizationTemplateData.htm"},
method = {org.springframework.web.bind.annotation.RequestMethod.POST})
@@ -200,10 +211,10 @@ public class CreateOptimizationController extends RestrictedBaseController {
JsonNode root = mapper.readTree(request.getReader());
String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
- String servicename = value.toString().split("-v")[0];
+ String servicename = value.split("-v")[0];
String version = null;
- if (value.toString().contains("-v")) {
- version = value.toString().split("-v")[1];
+ if (value.contains("-v")) {
+ version = value.split("-v")[1];
}
OptimizationModels returnModel = getAttributeObject(servicename, version);
@@ -230,8 +241,7 @@ public class CreateOptimizationController extends RestrictedBaseController {
// Get all keys with "MANY-true" defined in their value from subAttribute
Set<String> allkeys = null;
if (returnModel.getSubattributes() != null && !returnModel.getSubattributes().isEmpty()) {
- JSONObject json = new JSONObject(returnModel.getSubattributes());
- getAllKeys(json);
+ getAllKeys(new JSONObject(returnModel.getSubattributes()));
allkeys = allManyTrueKeys;
allManyTrueKeys = new HashSet<>();
LOGGER.info("allkeys : " + allkeys);
@@ -284,19 +294,18 @@ public class CreateOptimizationController extends RestrictedBaseController {
response.setContentType(APPLICATIONJSON);
request.setCharacterEncoding(UTF8);
List<Object> list = new ArrayList<>();
- PrintWriter out = response.getWriter();
String responseString = mapper.writeValueAsString(returnModel);
- JSONObject j = null;
+ JSONObject json = null;
if ("".equals(nameOfTrueKeys)) {
- j = new JSONObject("{optimizationModelData: " + responseString + ",jsonValue: " + jsonModel
+ json = new JSONObject("{optimizationModelData: " + responseString + ",jsonValue: " + jsonModel
+ ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + headDefautlsData + "}");
} else {
- j = new JSONObject("{optimizationModelData: " + responseString + ",jsonValue: " + jsonModel
+ json = new JSONObject("{optimizationModelData: " + responseString + ",jsonValue: " + jsonModel
+ ",allManyTrueKeys: " + allManyTrueKeys + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:"
+ headDefautlsData + "}");
}
- list.add(j);
- out.write(list.toString());
+ list.add(json);
+ response.getWriter().write(list.toString());
return null;
}
@@ -419,10 +428,12 @@ public class CreateOptimizationController extends RestrictedBaseController {
private Set<String> getAllKeys(JSONArray arr, Set<String> keys) {
for (int i = 0; i < arr.length(); i++) {
Object obj = arr.get(i);
- if (obj instanceof JSONObject)
+ if (obj instanceof JSONObject) {
keys.addAll(getAllKeys(arr.getJSONObject(i)));
- if (obj instanceof JSONArray)
+ }
+ if (obj instanceof JSONArray) {
keys.addAll(getAllKeys(arr.getJSONArray(i)));
+ }
}
return keys;
@@ -437,15 +448,25 @@ public class CreateOptimizationController extends RestrictedBaseController {
LOGGER.info("obj : " + obj);
allManyTrueKeys.add(key);
}
- if (obj instanceof JSONObject)
+ if (obj instanceof JSONObject) {
keys.addAll(getAllKeys(json.getJSONObject(key)));
- if (obj instanceof JSONArray)
+ }
+ if (obj instanceof JSONArray) {
keys.addAll(getAllKeys(json.getJSONArray(key)));
+ }
}
return keys;
}
+ /**
+ * getModelServiceVersionData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ * @return ModelAndView
+ * @throws IOException IOException
+ */
@RequestMapping(
value = {"/policyController/getModelServiceVersionData.htm"},
method = {org.springframework.web.bind.annotation.RequestMethod.POST})
@@ -455,19 +476,16 @@ public class CreateOptimizationController extends RestrictedBaseController {
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JsonNode root = mapper.readTree(request.getReader());
- String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
- String servicename = value.split("-v")[0];
- Set<String> returnList = getVersionList(servicename);
+ final String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
+ final String servicename = value.split("-v")[0];
response.setCharacterEncoding(UTF8);
response.setContentType(APPLICATIONJSON);
request.setCharacterEncoding(UTF8);
List<Object> list = new ArrayList<>();
- PrintWriter out = response.getWriter();
- String responseString = mapper.writeValueAsString(returnList);
- JSONObject j = new JSONObject("{optimizationModelVersionData: " + responseString + "}");
- list.add(j);
- out.write(list.toString());
+ list.add(new JSONObject("{optimizationModelVersionData: "
+ + mapper.writeValueAsString(getVersionList(servicename)) + "}"));
+ response.getWriter().write(list.toString());
return null;
}
@@ -512,76 +530,87 @@ public class CreateOptimizationController extends RestrictedBaseController {
modelName);
}
+ /**
+ * prePopulatePolicyData.
+ *
+ * @param policyAdapter PolicyRestAdapter
+ * @param entity PolicyEntity
+ */
public void prePopulatePolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
- if (policyAdapter.getPolicyData() instanceof PolicyType) {
- Object policyData = policyAdapter.getPolicyData();
- PolicyType policy = (PolicyType) policyData;
- policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
- String policyNameValue =
- policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("OOF_") + 4);
- policyAdapter.setPolicyName(policyNameValue);
- String description = "";
- try {
- description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
- } catch (Exception e) {
- LOGGER.error("Error while collecting the description tag in " + policyNameValue, e);
- description = policy.getDescription();
+ if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
+ return;
+ }
+ Object policyData = policyAdapter.getPolicyData();
+ PolicyType policy = (PolicyType) policyData;
+ policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
+ String policyNameValue =
+ policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("OOF_") + 4);
+ policyAdapter.setPolicyName(policyNameValue);
+ String description = "";
+ try {
+ description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
+ } catch (Exception e) {
+ LOGGER.error("Error while collecting the description tag in " + policyNameValue, e);
+ description = policy.getDescription();
+ }
+ policyAdapter.setPolicyDescription(description);
+ // Get the target data under policy.
+ TargetType target = policy.getTarget();
+ if (target == null) {
+ return;
+ }
+ // Under target we have AnyOFType
+ List<AnyOfType> anyOfList = target.getAnyOf();
+ if (anyOfList == null) {
+ return;
+ }
+ Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
+ while (iterAnyOf.hasNext()) {
+ AnyOfType anyOf = iterAnyOf.next();
+ // Under AnyOFType we have AllOFType
+ List<AllOfType> allOfList = anyOf.getAllOf();
+ if (allOfList == null) {
+ continue;
}
- policyAdapter.setPolicyDescription(description);
- // Get the target data under policy.
- TargetType target = policy.getTarget();
- if (target != null) {
- // Under target we have AnyOFType
- List<AnyOfType> anyOfList = target.getAnyOf();
- if (anyOfList != null) {
- Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
- while (iterAnyOf.hasNext()) {
- AnyOfType anyOf = iterAnyOf.next();
- // Under AnyOFType we have AllOFType
- List<AllOfType> allOfList = anyOf.getAllOf();
- if (allOfList != null) {
- Iterator<AllOfType> iterAllOf = allOfList.iterator();
- while (iterAllOf.hasNext()) {
- AllOfType allOf = iterAllOf.next();
- // Under AllOFType we have Match
- List<MatchType> matchList = allOf.getMatch();
- if (matchList != null) {
- Iterator<MatchType> iterMatch = matchList.iterator();
- while (matchList.size() > 1 && iterMatch.hasNext()) {
- MatchType match = iterMatch.next();
- //
- // Under the match we have attribute value and
- // attributeDesignator. So,finally down to the actual attribute.
- //
- AttributeValueType attributeValue = match.getAttributeValue();
- String value = (String) attributeValue.getContent().get(0);
- AttributeDesignatorType designator = match.getAttributeDesignator();
- String attributeId = designator.getAttributeId();
- // First match in the target is OnapName, so set that value.
- if ("ONAPName".equals(attributeId)) {
- policyAdapter.setOnapName(value);
- }
- if ("RiskType".equals(attributeId)) {
- policyAdapter.setRiskType(value);
- }
- if ("RiskLevel".equals(attributeId)) {
- policyAdapter.setRiskLevel(value);
- }
- if ("guard".equals(attributeId)) {
- policyAdapter.setGuard(value);
- }
- if ("TTLDate".equals(attributeId) && !value.contains("NA")) {
- PolicyController controller = new PolicyController();
- String newDate = controller.convertDate(value);
- policyAdapter.setTtlDate(newDate);
- }
- }
- readFile(policyAdapter, entity);
- }
- }
- }
+ Iterator<AllOfType> iterAllOf = allOfList.iterator();
+ while (iterAllOf.hasNext()) {
+ AllOfType allOf = iterAllOf.next();
+ // Under AllOFType we have Match
+ List<MatchType> matchList = allOf.getMatch();
+ if (matchList == null) {
+ continue;
+ }
+ Iterator<MatchType> iterMatch = matchList.iterator();
+ while (matchList.size() > 1 && iterMatch.hasNext()) {
+ MatchType match = iterMatch.next();
+ //
+ // Under the match we have attribute value and
+ // attributeDesignator. So,finally down to the actual attribute.
+ //
+ AttributeValueType attributeValue = match.getAttributeValue();
+ String value = (String) attributeValue.getContent().get(0);
+ AttributeDesignatorType designator = match.getAttributeDesignator();
+ String attributeId = designator.getAttributeId();
+ // First match in the target is OnapName, so set that value.
+ if ("ONAPName".equals(attributeId)) {
+ policyAdapter.setOnapName(value);
+ }
+ if ("RiskType".equals(attributeId)) {
+ policyAdapter.setRiskType(value);
+ }
+ if ("RiskLevel".equals(attributeId)) {
+ policyAdapter.setRiskLevel(value);
+ }
+ if ("guard".equals(attributeId)) {
+ policyAdapter.setGuard(value);
+ }
+ if ("TTLDate".equals(attributeId) && !value.contains("NA")) {
+ PolicyController controller = new PolicyController();
+ String newDate = controller.convertDate(value);
+ policyAdapter.setTtlDate(newDate);
}
}
+ readFile(policyAdapter, entity);
}
}
}
@@ -617,6 +646,14 @@ public class CreateOptimizationController extends RestrictedBaseController {
}
+ /**
+ * setModelData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ * @throws IOException IOException
+ * @throws FileUploadException FileUploadException
+ */
@RequestMapping(
value = {"/oof_dictionary/set_ModelData"},
method = {org.springframework.web.bind.annotation.RequestMethod.POST})
@@ -661,16 +698,10 @@ public class CreateOptimizationController extends RestrictedBaseController {
}
if (!errorMsg.isEmpty()) {
-
- PrintWriter out = response.getWriter();
-
response.setCharacterEncoding(UTF8);
response.setContentType(APPLICATIONJSON);
request.setCharacterEncoding(UTF8);
-
- JSONObject j = new JSONObject();
- j.put("errorMsg", errorMsg);
- out.write(j.toString());
+ response.getWriter().write(new JSONObject().put("errorMsg", errorMsg).toString());
return;
}
@@ -737,20 +768,18 @@ public class CreateOptimizationController extends RestrictedBaseController {
}
- PrintWriter out = response.getWriter();
-
response.setCharacterEncoding(UTF8);
response.setContentType(APPLICATIONJSON);
request.setCharacterEncoding(UTF8);
ObjectMapper mapper = new ObjectMapper();
- JSONObject j = new JSONObject();
- j.put("classListDatas", modelList);
- j.put("modelDatas", mapper.writeValueAsString(classMap));
- j.put("modelType", modelType);
- j.put("dataOrderInfo", modelUtil.getDataOrderInfo());
+ JSONObject json = new JSONObject();
+ json.put("classListDatas", modelList);
+ json.put("modelDatas", mapper.writeValueAsString(classMap));
+ json.put("modelType", modelType);
+ json.put("dataOrderInfo", modelUtil.getDataOrderInfo());
- out.write(j.toString());
+ response.getWriter().write(json.toString());
}
/*
@@ -758,7 +787,6 @@ public class CreateOptimizationController extends RestrictedBaseController {
*/
@SuppressWarnings("rawtypes")
private void extractFolder(String zipFile) {
- int BUFFER = 2048;
File file = new File(zipFile);
try (ZipFile zip = new ZipFile(file)) {
@@ -823,8 +851,7 @@ public class CreateOptimizationController extends RestrictedBaseController {
private List<File> listModelFiles(String directoryName) {
File fileDirectory = new File(directoryName);
List<File> resultList = new ArrayList<>();
- File[] fList = fileDirectory.listFiles();
- for (File file : fList) {
+ for (File file : fileDirectory.listFiles()) {
if (file.isFile()) {
resultList.add(file);
} else if (file.isDirectory()) {
@@ -837,9 +864,9 @@ public class CreateOptimizationController extends RestrictedBaseController {
private List<String> createList() {
List<String> list = new ArrayList<>();
- for (Entry<String, MSAttributeObject> cMap : classMap.entrySet()) {
- if (cMap.getValue().isPolicyTempalate()) {
- list.add(cMap.getKey());
+ for (Entry<String, MSAttributeObject> entrySet : classMap.entrySet()) {
+ if (entrySet.getValue().isPolicyTempalate()) {
+ list.add(entrySet.getKey());
}
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java
index f7295d587..af4f8cfc3 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -51,100 +51,106 @@ public class CreatePolicyController extends RestrictedBaseController {
private ArrayList<Object> attributeList;
boolean isValidForm = false;
+ /**
+ * prePopulateBaseConfigPolicyData.
+ *
+ * @param policyAdapter PolicyRestAdapter
+ * @param entity PolicyEntity
+ */
public void prePopulateBaseConfigPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
attributeList = new ArrayList<>();
- if (policyAdapter.getPolicyData() instanceof PolicyType) {
- Object policyData = policyAdapter.getPolicyData();
- PolicyType policy = (PolicyType) policyData;
- policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
- policyAdapter.setConfigType(entity.getConfigurationData().getConfigType());
- policyAdapter.setConfigBodyData(entity.getConfigurationData().getConfigBody());
- String policyNameValue =
- policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf('_') + 1);
- policyAdapter.setPolicyName(policyNameValue);
- String description = "";
- try {
- description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
- } catch (Exception e) {
- policyLogger.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue, e);
- description = policy.getDescription();
- }
- policyAdapter.setPolicyDescription(description);
- // Get the target data under policy.
- TargetType target = policy.getTarget();
- if (target != null) {
- // Under target we have AnyOFType
- List<AnyOfType> anyOfList = target.getAnyOf();
- if (anyOfList != null) {
- Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
- while (iterAnyOf.hasNext()) {
- AnyOfType anyOf = iterAnyOf.next();
- // Under AnyOFType we have AllOFType
- List<AllOfType> allOfList = anyOf.getAllOf();
- if (allOfList != null) {
- Iterator<AllOfType> iterAllOf = allOfList.iterator();
- int index = 0;
- while (iterAllOf.hasNext()) {
- AllOfType allOf = iterAllOf.next();
- // Under AllOFType we have Match
- List<MatchType> matchList = allOf.getMatch();
- if (matchList != null) {
- Iterator<MatchType> iterMatch = matchList.iterator();
- while (iterMatch.hasNext()) {
- MatchType match = iterMatch.next();
- //
- // Under the match we have attribute value and
- // attributeDesignator. So,finally down to the actual attribute.
- //
- AttributeValueType attributeValue = match.getAttributeValue();
- String value = (String) attributeValue.getContent().get(0);
- AttributeDesignatorType designator = match.getAttributeDesignator();
- String attributeId = designator.getAttributeId();
- // First match in the target is OnapName, so set that value.
- if ("ONAPName".equals(attributeId)) {
- policyAdapter.setOnapName(value);
- }
- if ("RiskType".equals(attributeId)) {
- policyAdapter.setRiskType(value);
- }
- if ("RiskLevel".equals(attributeId)) {
- policyAdapter.setRiskLevel(value);
- }
- if ("guard".equals(attributeId)) {
- policyAdapter.setGuard(value);
- }
- if ("TTLDate".equals(attributeId) && !value.contains("NA")) {
- PolicyController controller = new PolicyController();
- String newDate = controller.convertDate(value);
- policyAdapter.setTtlDate(newDate);
- }
- if ("ConfigName".equals(attributeId)) {
- policyAdapter.setConfigName(value);
- }
- // After Onap and Config it is optional to have attributes, so
- // check weather dynamic values or there or not.
- if (index >= 7) {
- Map<String, String> attribute = new HashMap<>();
- attribute.put("key", attributeId);
- attribute.put("value", value);
- attributeList.add(attribute);
- }
- index++;
- }
- }
- }
+ if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
+ return;
+ }
+ Object policyData = policyAdapter.getPolicyData();
+ PolicyType policy = (PolicyType) policyData;
+ policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
+ policyAdapter.setConfigType(entity.getConfigurationData().getConfigType());
+ policyAdapter.setConfigBodyData(entity.getConfigurationData().getConfigBody());
+ String policyNameValue =
+ policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf('_') + 1);
+ policyAdapter.setPolicyName(policyNameValue);
+ String description = "";
+ try {
+ description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
+ } catch (Exception e) {
+ policyLogger.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue, e);
+ description = policy.getDescription();
+ }
+ policyAdapter.setPolicyDescription(description);
+ // Get the target data under policy.
+ TargetType target = policy.getTarget();
+ if (target != null && target.getAnyOf() != null) {
+ // Under target we have AnyOFType
+ List<AnyOfType> anyOfList = target.getAnyOf();
+ Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
+ while (iterAnyOf.hasNext()) {
+ AnyOfType anyOf = iterAnyOf.next();
+ // Under AnyOFType we have AllOFType
+ List<AllOfType> allOfList = anyOf.getAllOf();
+ if (allOfList == null) {
+ continue;
+ }
+ Iterator<AllOfType> iterAllOf = allOfList.iterator();
+ int index = 0;
+ while (iterAllOf.hasNext()) {
+ AllOfType allOf = iterAllOf.next();
+ // Under AllOFType we have Match
+ List<MatchType> matchList = allOf.getMatch();
+ if (matchList == null) {
+ continue;
+ }
+ Iterator<MatchType> iterMatch = matchList.iterator();
+ while (iterMatch.hasNext()) {
+ MatchType match = iterMatch.next();
+ //
+ // Under the match we have attribute value and
+ // attributeDesignator. So,finally down to the actual attribute.
+ //
+ AttributeValueType attributeValue = match.getAttributeValue();
+ String value = (String) attributeValue.getContent().get(0);
+ AttributeDesignatorType designator = match.getAttributeDesignator();
+ String attributeId = designator.getAttributeId();
+ // First match in the target is OnapName, so set that value.
+ if ("ONAPName".equals(attributeId)) {
+ policyAdapter.setOnapName(value);
+ }
+ if ("RiskType".equals(attributeId)) {
+ policyAdapter.setRiskType(value);
+ }
+ if ("RiskLevel".equals(attributeId)) {
+ policyAdapter.setRiskLevel(value);
}
+ if ("guard".equals(attributeId)) {
+ policyAdapter.setGuard(value);
+ }
+ if ("TTLDate".equals(attributeId) && !value.contains("NA")) {
+ PolicyController controller = new PolicyController();
+ String newDate = controller.convertDate(value);
+ policyAdapter.setTtlDate(newDate);
+ }
+ if ("ConfigName".equals(attributeId)) {
+ policyAdapter.setConfigName(value);
+ }
+ // After Onap and Config it is optional to have attributes, so
+ // check weather dynamic values or there or not.
+ if (index >= 7) {
+ Map<String, String> attribute = new HashMap<>();
+ attribute.put("key", attributeId);
+ attribute.put("value", value);
+ attributeList.add(attribute);
+ }
+ index++;
}
}
-
- policyAdapter.setAttributes(attributeList);
}
- List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
- for (Object o : ruleList) {
- if (o instanceof RuleType) {
- // get the condition data under the rule for rule Algorithms.
- policyAdapter.setRuleID(((RuleType) o).getRuleId());
- }
+ policyAdapter.setAttributes(attributeList);
+ }
+ List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
+ for (Object o : ruleList) {
+ if (o instanceof RuleType) {
+ // get the condition data under the rule for rule Algorithms.
+ policyAdapter.setRuleID(((RuleType) o).getRuleId());
}
}
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java
index b90cc52c8..891398aef 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java
@@ -122,7 +122,7 @@ public class DashboardController extends RestrictedBaseController {
/**
* This method is to retrieve all the data of last 30 days from PolicyEntity table as default.
- *
+ *
* @param request object
* @param response object contains retrieved data
*/
@@ -137,9 +137,7 @@ public class DashboardController extends RestrictedBaseController {
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
addPolicyCrudInfoToTable();
model.put("papStatusCRUDData", mapper.writeValueAsString(policyStatusCrudData));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
policyLogger.error(exceptionOccured, e);
}
@@ -147,7 +145,7 @@ public class DashboardController extends RestrictedBaseController {
/**
* This method retrieves data based on input criteria.
- *
+ *
* @param request object
* @param response object contains retrieved data
*/
@@ -188,9 +186,7 @@ public class DashboardController extends RestrictedBaseController {
getPolicyData(lscope, lstage, isDelected, ttlDateAfter, ttlDateBefore);
Map<String, Object> model = new HashMap<>();
model.put("policyStatusCRUDData", mapper.writeValueAsString(policyStatusCrudData));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
@@ -201,7 +197,7 @@ public class DashboardController extends RestrictedBaseController {
/**
* This method is to retrieve data from PolicyEntity table.
- *
+ *
* @param request object
* @param response object contains retrieved data
*/
@@ -215,14 +211,18 @@ public class DashboardController extends RestrictedBaseController {
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
model.put("pdpStatusCRUDData", mapper.writeValueAsString(pdpStatusCrudData));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
policyLogger.error(exceptionOccured, e);
}
}
+ /**
+ * getData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
@RequestMapping(
value = {"/get_DashboardLoggingData"},
method = {org.springframework.web.bind.annotation.RequestMethod.GET},
@@ -232,14 +232,18 @@ public class DashboardController extends RestrictedBaseController {
Map<String, Object> model = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();
model.put("availableLoggingDatas", mapper.writeValueAsString(systemDAO.getLoggingData()));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
policyLogger.error(exceptionOccured + e);
}
}
+ /**
+ * getSystemAlertData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
@RequestMapping(
value = {"/get_DashboardSystemAlertData"},
method = {org.springframework.web.bind.annotation.RequestMethod.GET},
@@ -249,14 +253,18 @@ public class DashboardController extends RestrictedBaseController {
Map<String, Object> model = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();
model.put("systemAlertsTableDatas", mapper.writeValueAsString(systemDAO.getSystemAlertData()));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
policyLogger.error(exceptionOccured + e);
}
}
+ /**
+ * getPAPStatusData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
@RequestMapping(
value = {"/get_DashboardPAPStatusData"},
method = {org.springframework.web.bind.annotation.RequestMethod.GET},
@@ -268,21 +276,25 @@ public class DashboardController extends RestrictedBaseController {
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
addPAPToTable();
model.put("papTableDatas", mapper.writeValueAsString(papStatusData));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
policyLogger.error(exceptionOccured + e);
}
}
+ /**
+ * getPDPStatusData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
@RequestMapping(
value = {"/get_DashboardPDPStatusData"},
method = {org.springframework.web.bind.annotation.RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getPDPStatusData(HttpServletRequest request, HttpServletResponse response) {
try {
- Map<String, Object> model = new HashMap<>();
+ final Map<String, Object> model = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
PolicyController controller = getPolicyControllerInstance();
@@ -290,29 +302,32 @@ public class DashboardController extends RestrictedBaseController {
addPDPToTable();
model.put("pdpTableDatas", mapper.writeValueAsString(pdpStatusData));
JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ response.getWriter().write(new JSONObject(msg).toString());
} catch (Exception e) {
policyLogger.error(exceptionOccured + e);
}
}
+ /**
+ * getPolicyActivityData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
@RequestMapping(
value = {"/get_DashboardPolicyActivityData"},
method = {org.springframework.web.bind.annotation.RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getPolicyActivityData(HttpServletRequest request, HttpServletResponse response) {
try {
- Map<String, Object> model = new HashMap<>();
+ final Map<String, Object> model = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
PolicyController controller = getPolicyControllerInstance();
this.pdpConatiner = new PDPGroupContainer(controller.getPapEngine());
addPolicyToTable();
model.put("policyActivityTableDatas", mapper.writeValueAsString(policyActivityData));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
policyLogger.error(exceptionOccured + e);
}
@@ -336,9 +351,9 @@ public class DashboardController extends RestrictedBaseController {
papStatus = "CANNOT_CONNECT";
policyLogger.error("Error getting PAP status, PAP not responding to requests", e1);
}
- String papURL = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
+ String papUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
JSONObject object = new JSONObject();
- object.put("system", papURL);
+ object.put("system", papUrl);
object.put("status", papStatus);
List<Object> data = commonClassDao.getDataByQuery("from PolicyEntity", new SimpleBindings());
object.put("noOfPolicy", data.size());
@@ -346,8 +361,8 @@ public class DashboardController extends RestrictedBaseController {
papStatusData.add(0, object);
}
- /*
- * Add the PAP Policy information to the PAP Table
+ /**
+ * Add the PAP Policy information to the PAP Table.
*/
public void addPolicyCrudInfoToTable() {
policyStatusCrudData = new ArrayList<>();
@@ -370,7 +385,7 @@ public class DashboardController extends RestrictedBaseController {
object.put(scope, ((PolicyEntity) data).getScope());
object.put("policyName", ((PolicyEntity) data).getPolicyName());
object.put("version", ((PolicyEntity) data).getVersion());
- if (isPushedToPDP(((PolicyEntity) data).getPolicyId())) {
+ if (isPushedToPdp(((PolicyEntity) data).getPolicyId())) {
object.put(stage, "PDP");
} else {
object.put(stage, "PAP");
@@ -396,13 +411,13 @@ public class DashboardController extends RestrictedBaseController {
/*
* Add the PDP Policy information to the PDP Table
*/
- private boolean isPushedToPDP(long policyId) {
+ private boolean isPushedToPdp(long policyId) {
try {
String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId";
SimpleBindings geParams = new SimpleBindings();
geParams.put("policyEntityId", policyId);
List<Object> groupobject = commonClassDao.getDataByQuery(groupEntityquery, geParams);
- if (groupobject != null && groupobject.size() > 0) {
+ if (groupobject != null && ! groupobject.isEmpty()) {
return true;
}
} catch (Exception e) {
@@ -488,7 +503,7 @@ public class DashboardController extends RestrictedBaseController {
object.put(scope, data.getScope());
object.put("policyName", data.getPolicyName());
object.put("version", data.getVersion());
- if (isPushedToPDP(data.getPolicyId())) {
+ if (isPushedToPdp(data.getPolicyId())) {
object.put(stage, "PDP");
} else {
object.put(stage, "PAP");
@@ -512,7 +527,7 @@ public class DashboardController extends RestrictedBaseController {
}
/**
- * Add PDP Information to the PDP Table
+ * Add PDP Information to the PDP Table.
*
*/
public void addPDPToTable() {
@@ -525,7 +540,7 @@ public class DashboardController extends RestrictedBaseController {
for (PDP pdp : group.getPdps()) {
naCount = -1;
if ("UP_TO_DATE".equals(pdp.getStatus().getStatus().toString()) && ((OnapPDP) pdp).getJmxPort() != 0) {
- String pdpIpAddress = parseIPSystem(pdp.getId());
+ String pdpIpAddress = parseIpSystem(pdp.getId());
int port = ((OnapPDP) pdp).getJmxPort();
if (port != 0) {
policyLogger.debug("Getting JMX Response Counts from " + pdpIpAddress + " at JMX port " + port);
@@ -562,7 +577,7 @@ public class DashboardController extends RestrictedBaseController {
}
}
- private static String parseIPSystem(String line) {
+ private static String parseIpSystem(String line) {
Pattern pattern = Pattern.compile("://(.+?):");
Matcher ip = pattern.matcher(line);
if (ip.find()) {
@@ -579,12 +594,12 @@ public class DashboardController extends RestrictedBaseController {
policyLogger.debug("Create an RMI connector client and connect it to the JMX connector server");
HashMap map = null;
- try (JMXConnector jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map)) {
+ try (JMXConnector jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionUrl(host, port), map)) {
jmxConnection.connect();
- Object o = jmxConnection.getMBeanServerConnection()
+ Object obj = jmxConnection.getMBeanServerConnection()
.getAttribute(new ObjectName("PdpRest:type=PdpRestMonitor"), jmxAttribute);
- policyLogger.debug("pdpEvaluationNA value retreived: " + o);
- return (long) o;
+ policyLogger.debug("pdpEvaluationNA value retreived: " + obj);
+ return (long) obj;
} catch (MalformedURLException e) {
policyLogger.error("MalformedURLException for JMX connection", e);
} catch (IOException e) {
@@ -605,7 +620,7 @@ public class DashboardController extends RestrictedBaseController {
return -1;
}
- private static JMXServiceURL createConnectionURL(String host, int port) throws MalformedURLException {
+ private static JMXServiceURL createConnectionUrl(String host, int port) throws MalformedURLException {
return new JMXServiceURL("rmi", "", 0, "/jndi/rmi://" + host + ":" + port + "/jmxrmi");
}
@@ -633,8 +648,8 @@ public class DashboardController extends RestrictedBaseController {
// Add rows to the Policy Table
policyList = null;
if ("UP_TO_DATE".equals(pdp.getStatus().getStatus().toString()) && ((OnapPDP) pdp).getJmxPort() != 0) {
- String pdpIpAddress = parseIPSystem(pdp.getId());
- policyList = getPolicy(pdpIpAddress, ((OnapPDP) pdp).getJmxPort(), "policyCount");
+ String pdpIpAddress = parseIpSystem(pdp.getId());
+ policyList = getPolicy(pdpIpAddress, ((OnapPDP) pdp).getJmxPort());
}
if (policyList != null && policyList.toString().length() > 3) {
String[] splitPolicy = policyList.toString().split(",");
@@ -650,19 +665,15 @@ public class DashboardController extends RestrictedBaseController {
}
}
} else {
+ JSONObject object = new JSONObject();
if (policyList != null) {
- JSONObject object = new JSONObject();
object.put("policyId", "Unable to retrieve policy information");
- object.put("fireCount", "NA");
- object.put("system", pdp.getId());
- policyActivityData.add(object);
} else {
- JSONObject object = new JSONObject();
object.put("policyId", "Unable to access PDP JMX Server");
- object.put("fireCount", "NA");
- object.put("system", pdp.getId());
- policyActivityData.add(object);
}
+ object.put("fireCount", "NA");
+ object.put("system", pdp.getId());
+ policyActivityData.add(object);
}
}
}
@@ -672,16 +683,16 @@ public class DashboardController extends RestrictedBaseController {
* Contact JMX Connector Sever and return the list of {policy id , count}
*/
@SuppressWarnings({"rawtypes", "unchecked"})
- private Object getPolicy(String host, int port, String jmxAttribute) {
+ private Object getPolicy(String host, int port) {
policyLogger
.debug("Create an RMI connector client and connect it to the JMX connector server for Policy: " + host);
HashMap map = null;
- try (JMXConnector jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map)) {
+ try (JMXConnector jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionUrl(host, port), map)) {
jmxConnection.connect();
- Object o = jmxConnection.getMBeanServerConnection()
+ Object obj = jmxConnection.getMBeanServerConnection()
.getAttribute(new ObjectName("PdpRest:type=PdpRestMonitor"), "policyMap");
- policyLogger.debug("policyMap value retreived: " + o);
- return o;
+ policyLogger.debug("policyMap value retreived: " + obj);
+ return obj;
} catch (MalformedURLException e) {
policyLogger.error("MalformedURLException for JMX connection", e);
} catch (IOException e) {
@@ -711,8 +722,7 @@ public class DashboardController extends RestrictedBaseController {
private static Integer countPolicyID(String line) {
String[] splitLine = line.split("=");
- String sCount = splitLine[1].replace("}", "");
- return Integer.parseInt(sCount);
+ return Integer.parseInt(splitLine[1].replace("}", ""));
}
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java
index d6a4e8285..d12cbb2d4 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -83,7 +83,13 @@ public class DecisionPolicyController extends RestrictedBaseController {
// This constructor is empty
}
- public void rawXACMLPolicy(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
+ /**
+ * rawXacmlPolicy. Should this method be private?
+ *
+ * @param policyAdapter PolicyRestAdapter
+ * @param entity PolicyEntity
+ */
+ public void rawXacmlPolicy(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
try (InputStream policyXmlStream = XACMLPolicyWriter.getXmlAsInputStream(policyAdapter.getPolicyData())) {
String name = StringUtils.substringAfter(entity.getPolicyName(), "Decision_");
policyAdapter.setPolicyName(name.substring(0, name.indexOf('.')));
@@ -94,6 +100,12 @@ public class DecisionPolicyController extends RestrictedBaseController {
}
}
+ /**
+ * prePopulateDecisionPolicyData.
+ *
+ * @param policyAdapter PolicyRestAdapter
+ * @param entity PolicyEntity
+ */
@SuppressWarnings("unchecked")
public void prePopulateDecisionPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
List<Object> attributeList = new ArrayList<>();
@@ -109,7 +121,7 @@ public class DecisionPolicyController extends RestrictedBaseController {
}
if (rawPolicyCheck) {
- rawXACMLPolicy(policyAdapter, entity);
+ rawXacmlPolicy(policyAdapter, entity);
} else {
RainyDayParams rainydayParams = new RainyDayParams();
Object policyData = policyAdapter.getPolicyData();
@@ -143,45 +155,46 @@ public class DecisionPolicyController extends RestrictedBaseController {
AnyOfType anyOf = iterAnyOf.next();
// Under AntOfType we have AllOfType
List<AllOfType> allOfList = anyOf.getAllOf();
- if (allOfList != null) {
- Iterator<AllOfType> iterAllOf = allOfList.iterator();
- while (iterAllOf.hasNext()) {
- AllOfType allOf = iterAllOf.next();
- // Under AllOfType we have Mathch.
- List<MatchType> matchList = allOf.getMatch();
- int index = 0;
- if (matchList != null) {
- Iterator<MatchType> iterMatch = matchList.iterator();
- while (iterMatch.hasNext()) {
- MatchType match = iterMatch.next();
- //
- // Under the match we have attributevalue and
- // attributeDesignator. So,finally down to the actual attribute.
- //
- AttributeValueType attributeValue = match.getAttributeValue();
- String value = (String) attributeValue.getContent().get(0);
- if (value != null) {
- value = value.replaceAll("\\(\\?i\\)", "");
- }
- AttributeDesignatorType designator = match.getAttributeDesignator();
- String attributeId = designator.getAttributeId();
- // First match in the target is OnapName, so set that value.
- if ("ONAPName".equals(attributeId)) {
- policyAdapter.setOnapName(value);
- }
- // Component attributes are saved under Target here we are fetching them back.
- // One row is default so we are not adding dynamic component at index 0.
- if (index >= 1) {
- Map<String, String> attribute = new HashMap<>();
- attribute.put("key", attributeId);
- attribute.put("value", value);
- attributeList.add(attribute);
- }
- index++;
+ if (allOfList == null) {
+ continue;
+ }
+ Iterator<AllOfType> iterAllOf = allOfList.iterator();
+ while (iterAllOf.hasNext()) {
+ AllOfType allOf = iterAllOf.next();
+ // Under AllOfType we have Mathch.
+ List<MatchType> matchList = allOf.getMatch();
+ int index = 0;
+ if (matchList != null) {
+ Iterator<MatchType> iterMatch = matchList.iterator();
+ while (iterMatch.hasNext()) {
+ MatchType match = iterMatch.next();
+ //
+ // Under the match we have attributevalue and
+ // attributeDesignator. So,finally down to the actual attribute.
+ //
+ AttributeValueType attributeValue = match.getAttributeValue();
+ String value = (String) attributeValue.getContent().get(0);
+ if (value != null) {
+ value = value.replaceAll("\\(\\?i\\)", "");
+ }
+ AttributeDesignatorType designator = match.getAttributeDesignator();
+ String attributeId = designator.getAttributeId();
+ // First match in the target is OnapName, so set that value.
+ if ("ONAPName".equals(attributeId)) {
+ policyAdapter.setOnapName(value);
+ }
+ // Component attributes are saved under Target here we are fetching them back.
+ // One row is default so we are not adding dynamic component at index 0.
+ if (index >= 1) {
+ Map<String, String> attribute = new HashMap<>();
+ attribute.put("key", attributeId);
+ attribute.put("value", value);
+ attributeList.add(attribute);
}
+ index++;
}
- policyAdapter.setAttributes(attributeList);
}
+ policyAdapter.setAttributes(attributeList);
}
}
// Setting rainy day attributes to the parameters object if they exist
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java
index 56d882fb4..6c1969cdd 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -83,6 +83,11 @@ public class PDPController extends RestrictedBaseController {
this.policyController = policyController;
}
+ /**
+ * refreshGroups.
+ *
+ * @param request HttpServletRequest
+ */
public synchronized void refreshGroups(HttpServletRequest request) {
synchronized (this.groups) {
this.groups.clear();
@@ -98,7 +103,7 @@ public class PDPController extends RestrictedBaseController {
scopes = pair.t;
if (!junit && controller.getPapEngine() == null) {
- setPAPEngine(request);
+ setPapEngine(request);
}
if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) {
if (!junit) {
@@ -148,35 +153,44 @@ public class PDPController extends RestrictedBaseController {
}
}
- private void setPAPEngine(HttpServletRequest request) {
- String myRequestURL = request.getRequestURL().toString();
+ private void setPapEngine(HttpServletRequest request) {
try {
//
// Set the URL for the RESTful PAP Engine
//
- PolicyController.setPapEngine((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL));
+ PolicyController.setPapEngine(new RESTfulPAPEngine(request.getRequestURL().toString()));
} catch (Exception e) {
policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Exception Occured while loading PAP", e);
}
}
+ /**
+ * getPDPGroupEntityData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
@RequestMapping(
value = {"/get_PDPGroupData"},
method = {org.springframework.web.bind.annotation.RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getPDPGroupEntityData(HttpServletRequest request, HttpServletResponse response) {
try {
- ObjectMapper mapper = new ObjectMapper();
refreshGroups(request);
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(
+ new ObjectMapper().writeValueAsString(groups))).toString());
} catch (Exception e) {
policyLogger.error(
XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while retrieving the PDP Group data" + e);
}
}
+ /**
+ * savePDPGroup.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
@RequestMapping(
value = {"/pdp_Group/save_pdp_group"},
method = {org.springframework.web.bind.annotation.RequestMethod.POST})
@@ -190,10 +204,10 @@ public class PDPController extends RestrictedBaseController {
String userId = UserUtils.getUserSession(request).getOrgUserId();
policyLogger.info(
- "****************************************Logging UserID for Save PDP Group Function*****************************************");
+ "*******************Logging UserID for Save PDP Group Function*******************************");
policyLogger.info("UserId: " + userId + "PDP Group Data: " + root.get("pdpGroupData").toString());
policyLogger.info(
- "***************************************************************************************************************************");
+ "********************************************************************************************");
StdPDPGroup pdpGroupData = mapper
.readValue(root.get("pdpGroupData").toString().replace("groupName", "name"), StdPDPGroup.class);
@@ -214,11 +228,8 @@ public class PDPController extends RestrictedBaseController {
response.setContentType("application / json");
request.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
refreshGroups(request);
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
- JSONObject j = new JSONObject(msg);
- out.write(j.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString());
} catch (Exception e) {
policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Saving the PDP Group" + e);
response.setCharacterEncoding("UTF-8");
@@ -234,6 +245,12 @@ public class PDPController extends RestrictedBaseController {
}
}
+ /**
+ * removePDPGroup.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
@RequestMapping(
value = {"/pdp_Group/remove_pdp_group"},
method = {org.springframework.web.bind.annotation.RequestMethod.POST})
@@ -247,10 +264,10 @@ public class PDPController extends RestrictedBaseController {
String userId = UserUtils.getUserSession(request).getOrgUserId();
policyLogger.info(
- "****************************************Logging UserID for Remove PDP Group Function*****************************************");
+ "*********************Logging UserID for Remove PDP Group Function*******************************");
policyLogger.info("UserId: " + userId + "PDP Group Data: " + root.get("pdpGroupData").toString());
policyLogger.info(
- "*****************************************************************************************************************************");
+ "************************************************************************************************");
StdPDPGroup pdpGroupData = mapper.readValue(root.get("pdpGroupData").toString(), StdPDPGroup.class);
if ("Default".equals(pdpGroupData.getName())) {
@@ -262,13 +279,8 @@ public class PDPController extends RestrictedBaseController {
response.setCharacterEncoding("UTF-8");
response.setContentType("application / json");
request.setCharacterEncoding("UTF-8");
-
- PrintWriter out = response.getWriter();
-
refreshGroups(request);
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
- JSONObject j = new JSONObject(msg);
- out.write(j.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString());
} catch (Exception e) {
policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Removing the PDP Group" + e);
PrintWriter out;
@@ -283,6 +295,12 @@ public class PDPController extends RestrictedBaseController {
}
}
+ /**
+ * savePDPToGroup.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
@RequestMapping(
value = {"/pdp_Group/save_pdpTogroup"},
method = {org.springframework.web.bind.annotation.RequestMethod.POST})
@@ -299,11 +317,11 @@ public class PDPController extends RestrictedBaseController {
String userId = UserUtils.getUserSession(request).getOrgUserId();
policyLogger.info(
- "****************************************Logging UserID while Saving pdp in PDP Group*****************************************");
+ "*************Logging UserID while Saving pdp in PDP Group***********************************");
policyLogger.info("UserId: " + userId + "PDP Group Data: " + root.get("pdpInGroup").toString()
+ "Active Group Data: " + root.get("activePDP").toString());
policyLogger.info(
- "*******************************************************************************************************************************");
+ "**********************************************************************************************");
try {
@@ -322,12 +340,8 @@ public class PDPController extends RestrictedBaseController {
response.setCharacterEncoding("UTF-8");
response.setContentType("application / json");
request.setCharacterEncoding("UTF-8");
-
- PrintWriter out = response.getWriter();
refreshGroups(request);
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
- JSONObject j = new JSONObject(msg);
- out.write(j.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString());
} catch (Exception e) {
policyLogger
.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Creating Pdp in PDP Group" + e);
@@ -343,6 +357,12 @@ public class PDPController extends RestrictedBaseController {
}
}
+ /**
+ * removePDPFromGroup.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
@RequestMapping(
value = {"/pdp_Group/remove_pdpFromGroup"},
method = {org.springframework.web.bind.annotation.RequestMethod.POST})
@@ -353,36 +373,31 @@ public class PDPController extends RestrictedBaseController {
JsonNode root = mapper.readTree(request.getReader());
PolicyController controller = getPolicyControllerInstance();
this.container = new PDPGroupContainer(controller.getPapEngine());
- StdPDP deletePdp = mapper.readValue(root.get("data").toString(), StdPDP.class);
- StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class);
String userId = UserUtils.getUserSession(request).getOrgUserId();
policyLogger.info(
- "****************************************Logging UserID while Removing pdp from PDP Group*****************************************");
+ "********************Logging UserID while Removing pdp from PDP Group**************************");
policyLogger.info("UserId: " + userId + "Delete PDP Group Data: " + root.get("data").toString()
+ "Active Group Data: " + root.get("activePDP").toString());
policyLogger.info(
- "***********************************************************************************************************************************");
+ "************************************************************************************************");
+ StdPDP deletePdp = mapper.readValue(root.get("data").toString(), StdPDP.class);
+ StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class);
this.container.removePDP(deletePdp, activeGroupData);
response.setCharacterEncoding("UTF-8");
response.setContentType("application / json");
request.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
refreshGroups(request);
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
- JSONObject j = new JSONObject(msg);
- out.write(j.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString());
} catch (Exception e) {
policyLogger.error(
XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Removing Pdp from PDP Group" + e);
- PrintWriter out;
try {
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
- out = response.getWriter();
- out.write(e.getMessage());
+ response.getWriter().write(e.getMessage());
} catch (Exception e1) {
policyLogger.error("Exception Occured" + e1);
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java
index 78fb87346..40f6be8d7 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java
@@ -164,8 +164,8 @@ public class PolicyController extends RestrictedBaseController {
return jUnit;
}
- public static void setjUnit(boolean jUnit) {
- PolicyController.jUnit = jUnit;
+ public static void setjUnit(boolean isJunit) {
+ PolicyController.jUnit = isJunit;
}
@Autowired
@@ -321,9 +321,7 @@ public class PolicyController extends RestrictedBaseController {
ObjectMapper mapper = new ObjectMapper();
model.put("functionDefinitionDatas",
mapper.writeValueAsString(commonClassDao.getDataByColumn(FunctionDefinition.class, "shortname")));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
policyLogger.error(
XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while retriving the Function Definition data" + e);
@@ -378,9 +376,7 @@ public class PolicyController extends RestrictedBaseController {
Map<String, Object> model = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();
model.put("userRolesDatas", mapper.writeValueAsString(getRolesOfUser(userId)));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
policyLogger.error("Exception Occured" + e);
}
@@ -601,11 +597,11 @@ public class PolicyController extends RestrictedBaseController {
/**
* Switch Version Policy Content.
*
- * @param pName which is used to find associated versions.
+ * @param thePolicyName which is used to find associated versions.
* @return list of available versions based on policy name.
*/
- public JSONObject switchVersionPolicyContent(String pName) {
- String policyName = pName;
+ public JSONObject switchVersionPolicyContent(String thePolicyName) {
+ String policyName = thePolicyName;
String dbCheckName = policyName.replace("/", ".");
if (dbCheckName.contains("Config_")) {
dbCheckName = dbCheckName.replace(".Config_", ":Config_");
@@ -621,14 +617,13 @@ public class PolicyController extends RestrictedBaseController {
SimpleBindings params = new SimpleBindings();
params.put("splitDBCheckName1", splitDbCheckName[1] + "%");
params.put("splitDBCheckName0", splitDbCheckName[0]);
- List<Object> policyEntity = commonClassDao.getDataByQuery(query, params);
List<String> av = new ArrayList<>();
- for (Object entity : policyEntity) {
- PolicyEntity pEntity = (PolicyEntity) entity;
- String removeExtension = pEntity.getPolicyName().replace(".xml", "");
+ for (Object entity : commonClassDao.getDataByQuery(query, params)) {
+ PolicyEntity policyEntity = (PolicyEntity) entity;
+ String removeExtension = policyEntity.getPolicyName().replace(".xml", "");
String version = removeExtension.substring(removeExtension.lastIndexOf('.') + 1);
- String userName = getUserId(pEntity, "@ModifiedBy:");
- av.add(version + " | " + pEntity.getModifiedDate() + " | " + userName);
+ String userName = getUserId(policyEntity, "@ModifiedBy:");
+ av.add(version + " | " + policyEntity.getModifiedDate() + " | " + userName);
}
if (policyName.contains("/")) {
policyName = policyName.replace("/", File.separator);
@@ -642,13 +637,20 @@ public class PolicyController extends RestrictedBaseController {
return el;
}
+ /**
+ * getUserId.
+ *
+ * @param data PolicyEntity
+ * @param value String
+ * @return String
+ */
public String getUserId(PolicyEntity data, String value) {
String userId = "";
- String uValue = value;
+ String userValue = value; // Why?
String description = getDescription(data);
- if (description.contains(uValue)) {
- userId = description.substring(description.indexOf(uValue) + uValue.length(),
- description.lastIndexOf(uValue));
+ if (description.contains(userValue)) {
+ userId = description.substring(description.indexOf(userValue) + userValue.length(),
+ description.lastIndexOf(userValue));
}
UserInfo userInfo = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", userId);
if (userInfo == null) {
@@ -657,6 +659,12 @@ public class PolicyController extends RestrictedBaseController {
return userInfo.getUserName();
}
+ /**
+ * getDescription.
+ *
+ * @param data PolicyEntity
+ * @return String
+ */
public String getDescription(PolicyEntity data) {
InputStream stream = new ByteArrayInputStream(data.getPolicyData().getBytes(StandardCharsets.UTF_8));
Object policy = XACMLPolicyScanner.readPolicy(stream);
@@ -664,13 +672,19 @@ public class PolicyController extends RestrictedBaseController {
return ((PolicySetType) policy).getDescription();
} else if (policy instanceof PolicyType) {
return ((PolicyType) policy).getDescription();
- } else {
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Expecting a PolicySet/Policy/Rule object. Got: "
- + policy.getClass().getCanonicalName());
- return null;
}
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Expecting a PolicySet/Policy/Rule object. Got: "
+ + policy.getClass().getCanonicalName());
+ return null;
}
+ /**
+ * getUserInfo.
+ *
+ * @param data PolicyEntity
+ * @param activePolicies list of active policies
+ * @return array of String
+ */
public String[] getUserInfo(PolicyEntity data, List<PolicyVersion> activePolicies) {
String policyName = data.getScope().replace(".", File.separator) + File.separator
+ data.getPolicyName().substring(0, data.getPolicyName().indexOf('.'));
@@ -963,13 +977,13 @@ public class PolicyController extends RestrictedBaseController {
/**
* Function to convert date.
*
- * @param dateTTL input date value.
+ * @param dateTimeToLive input date value.
* @return
*/
- public String convertDate(String dateTTL) {
+ public String convertDate(String dateTimeToLive) {
String formateDate = null;
- if (dateTTL.contains("-")) {
- formateDate = dateTTL.replace("-", "/");
+ if (dateTimeToLive.contains("-")) {
+ formateDate = dateTimeToLive.replace("-", "/");
}
return formateDate;
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java
index 11075ef6a..77deeb5f3 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java
@@ -563,6 +563,7 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
return false;
}
+ @SuppressWarnings("rawtypes")
private boolean isContinue(List<String> roles, String scope, UserInfo userInfo, Set scopes) {
if (roles.contains(admin) || roles.contains(editor)) {
if (scopes.isEmpty()) {
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java
index eeff137ef..51bc3e987 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -21,7 +21,7 @@
package org.onap.policy.controller;
/*
- *
+ *
* */
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
@@ -58,6 +58,14 @@ public class PolicyNotificationController extends RestrictedBaseController {
@Autowired
CommonClassDao commonClassDao;
+ /**
+ * watchPolicy.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ * @return ModelAndView
+ * @throws IOException IOException
+ */
@RequestMapping(value = {"/watchPolicy"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST})
public ModelAndView watchPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException {
StringBuilder path = new StringBuilder();
@@ -114,11 +122,8 @@ public class PolicyNotificationController extends RestrictedBaseController {
response.setContentType("application / json");
request.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
- String responseString = mapper.writeValueAsString(responseValue);
- JSONObject j = new JSONObject("{watchData: " + responseString + "}");
- out.write(j.toString());
- return null;
+ response.getWriter().write(new JSONObject("{watchData: "
+ + mapper.writeValueAsString(responseValue) + "}").toString());
} catch (Exception e) {
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java
index f416386c5..4e16a0ab4 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -82,9 +82,7 @@ public class PolicyRolesController extends RestrictedBaseController {
Map<String, Object> model = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();
model.put("rolesDatas", mapper.writeValueAsString(commonClassDao.getUserRoles()));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
LOGGER.error("Exception Occured" + e);
}
@@ -116,11 +114,11 @@ public class PolicyRolesController extends RestrictedBaseController {
}
}
LOGGER.info(
- "****************************************Logging UserID for Roles Function********************************************************");
+ "*************************Logging UserID for Roles Function***********************************");
LOGGER.info("UserId: " + userId + "Updating the Scope for following user" + adapter.getLoginId()
+ "ScopeNames" + adapter.getScope());
LOGGER.info(
- "*********************************************************************************************************************************");
+ "*********************************************************************************************");
UserInfo userInfo = new UserInfo();
userInfo.setUserLoginId(adapter.getLoginId().getUserName());
userInfo.setUserName(adapter.getLoginId().getUserName());
@@ -129,11 +127,11 @@ public class PolicyRolesController extends RestrictedBaseController {
if (adapter.getId() == 0 && "mechid".equals(adapter.getRole())) {
// Save new mechid scopes entity data.
LOGGER.info(
- "****************************************Logging UserID for New Mechid Function***************************************************");
+ "*********************Logging UserID for New Mechid Function********************************");
LOGGER.info("UserId:" + userId + "Adding new mechid-scopes for following user" + adapter.getLoginId()
+ "ScopeNames " + adapter.getScope());
LOGGER.info(
- "*********************************************************************************************************************************");
+ "*******************************************************************************************");
// First add the mechid to userinfo
commonClassDao.save(userInfo);
checkNew = true;
@@ -153,12 +151,8 @@ public class PolicyRolesController extends RestrictedBaseController {
response.setCharacterEncoding("UTF-8");
response.setContentType("application / json");
request.setCharacterEncoding("UTF-8");
-
- PrintWriter out = response.getWriter();
- String responseString = mapper.writeValueAsString(commonClassDao.getUserRoles());
- JSONObject j = new JSONObject("{rolesDatas: " + responseString + "}");
-
- out.write(j.toString());
+ response.getWriter().write(new JSONObject("{rolesDatas: "
+ + mapper.writeValueAsString(commonClassDao.getUserRoles()) + "}").toString());
} catch (Exception e) {
LOGGER.error("Exception Occured" + e);
}
@@ -183,9 +177,7 @@ public class PolicyRolesController extends RestrictedBaseController {
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
List<String> scopesData = commonClassDao.getDataByColumn(PolicyEditorScopes.class, "scopeName");
model.put("scopeDatas", mapper.writeValueAsString(scopesData));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
LOGGER.error("Exception Occured" + e);
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java
index fc94087fc..0c29f8fb7 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -47,6 +47,14 @@ public class PolicyValidationController extends RestrictedBaseController {
private static final Logger LOGGER = FlexLogger.getLogger(PolicyValidationController.class);
+ /**
+ * validatePolicy.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ * @return ModelAndView
+ * @throws IOException IOException
+ */
@RequestMapping(
value = {"/policyController/validate_policy.htm"},
method = {org.springframework.web.bind.annotation.RequestMethod.POST})
@@ -61,12 +69,8 @@ public class PolicyValidationController extends RestrictedBaseController {
PolicyRestAdapter policyData = wrapper.populateRequestParameters(request);
responseString = validation.validatePolicy(policyData);
- PrintWriter out = response.getWriter();
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(responseString.toString()));
- JSONObject j = new JSONObject(msg);
- out.write(j.toString());
-
- return null;
+ response.getWriter().write(new JSONObject(
+ new JsonMessage(mapper.writeValueAsString(responseString.toString()))).toString());
} catch (Exception e) {
LOGGER.error("Exception Occured During Policy Validation" + e);
response.setCharacterEncoding("UTF-8");