diff options
author | Michael Mokry <mm117s@att.com> | 2018-03-16 20:50:41 -0500 |
---|---|---|
committer | Michael Mokry <mm117s@att.com> | 2018-03-26 09:43:24 -0500 |
commit | b6d9063e06ab8cdf2d97fc75810792659344e4a8 (patch) | |
tree | 189c47e59cef6650ba0d39bbee31dcdaaa3ddbc7 /ONAP-PAP-REST/src/main/java | |
parent | c8bed1e392b935ec50aaeeb5fb82d25a9568b790 (diff) |
New Optimization Policy
This is the new Optimization Policy to support the Integration of
the OOF Policy Model into the Policy Platform.
Added changes from Frank Wang to fix the following issues with existing Model
Parser:
1. TOSCA Rendering issues
2. Matching Attributes support
3. ImportModelAPI to support TOSCA model upload via REST API
Running local Sonar tonight to start fixing Sonar issues
Added changes per review comments and fixed Sonar issues
Change-Id: Ia8ce09c28a718ce4460475e76a750caef774bd6b
Issue-ID: POLICY-622
Signed-off-by: Michael Mokry <mm117s@att.com>
Diffstat (limited to 'ONAP-PAP-REST/src/main/java')
15 files changed, 1589 insertions, 136 deletions
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DictionaryNames.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DictionaryNames.java index 3735316c4..38e2c96f5 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DictionaryNames.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DictionaryNames.java @@ -32,6 +32,7 @@ public enum DictionaryNames { ActionPolicyDictionary, OnapName, MSPolicyDictionary, + OptimizationPolicyDictionary, VNFType, VSCLAction, ClosedLoopService, diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java index a30c9c7ec..1acec1bd9 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java @@ -46,7 +46,7 @@ import java.util.Scanner; import java.util.Set; import java.util.UUID; import java.util.concurrent.CopyOnWriteArrayList; -import javax.json.JsonException; + import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.PersistenceException; @@ -1018,24 +1018,26 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList im.startTransaction(); loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doPut im startTransaction"); - } catch(AdministrativeStateException e) { - String message = "PUT interface called for PAP " + papResourceName + - " but it has an Administrative state of " + im.getStateManager().getAdminState() + - "\n Exception Message: " + e.getMessage(); - logMessage(e, message, loggingContext, response); - return; - } catch(StandbyStatusException e) { - String message = "PUT interface called for PAP " + papResourceName + - " but it has a Standby Status of " + im.getStateManager().getStandbyStatus() + - "\n Exception Message: " + e.getMessage(); - logMessage(e, message, loggingContext, response); - return; } catch (IntegrityMonitorException e) { - String message = "PUT interface called for PAP " + papResourceName + - " but an exception occurred" + - "\n Exception Message: " + e.getMessage(); - logMessage(e, message, loggingContext, response); - return; + String message = "PUT interface called for PAP " + papResourceName; + if (e instanceof AdministrativeStateException) { + message += " but it has an Administrative state of " + + im.getStateManager().getAdminState(); + } else if (e instanceof StandbyStatusException) { + message += " but it has a Standby Status of " + + im.getStateManager().getStandbyStatus(); + } else { + message += " but an exception occurred"; + + } + message += "\n Exception Message: " + e.getMessage(); + + LOGGER.info(message, e); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + return; } loggingContext.metricStarted(); @@ -2840,21 +2842,24 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.audit("Transaction Failed - See Error.log"); response.setStatus(HttpServletResponse.SC_OK); return; - }catch (ForwardProgressException e){ - String message = "GET:/pap/test called and PAP " + papResourceName + " is not making forward progress." - + " Exception Message: " + e.getMessage(); - logMessage(e, message, loggingContext, response); - return; - }catch (AdministrativeStateException e){ - String message = "GET:/pap/test called and PAP " + papResourceName + " Administrative State is LOCKED." - + " Exception Message: " + e.getMessage(); - logMessage(e, message, loggingContext, response); - return; - }catch (StandbyStatusException e){ - String message = "GET:/pap/test called and PAP " + papResourceName + " Standby Status is NOT PROVIDING SERVICE." - + " Exception Message: " + e.getMessage(); - logMessage(e, message, loggingContext, response); - return; + }catch (ForwardProgressException | AdministrativeStateException | StandbyStatusException e){ + String submsg; + if (e instanceof ForwardProgressException) { + submsg = " is not making forward progress."; + } else if (e instanceof AdministrativeStateException) { + submsg = " Administrative State is LOCKED."; + } else { + submsg = " Standby Status is NOT PROVIDING SERVICE."; + } + + String message = "GET:/pap/test called and PAP " + papResourceName + submsg + + " Exception Message: " + e.getMessage(); + LOGGER.info(message, e); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + return; }catch (Exception e) { //A subsystem is not making progress, is locked, standby or is not responding String eMsg = e.getMessage(); @@ -3029,12 +3034,4 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList public static void setMsPolicyName(String msPolicyName) { XACMLPapServlet.msPolicyName = msPolicyName; } - - private void logMessage(Exception e, String message, ONAPLoggingContext loggingContext, HttpServletResponse response) { - LOGGER.info(message, e); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - } -} +}
\ No newline at end of file diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java index d5233ce3d..7757c2f19 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java @@ -29,6 +29,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; @@ -48,6 +49,8 @@ import org.onap.policy.rest.util.MSAttributeObject; import org.onap.policy.rest.util.MSModelUtils; import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE; +import com.google.gson.Gson; + public class CreateNewMicroServiceModel { private static final Logger logger = FlexLogger.getLogger(CreateNewMicroServiceModel.class); private MicroServiceModels newModel = null; @@ -79,8 +82,18 @@ public class CreateNewMicroServiceModel { //get all the files from a director for (File file : fileList){ if (file.isFile()){ - tempMap = utils.processEpackage(file.getAbsolutePath(), MODEL_TYPE.XMI); - classMap.putAll(tempMap); + int i = file.getName().lastIndexOf('.'); + String type = file.getName().substring(i+1); + + if(type != null && "yml".equalsIgnoreCase(type)){ + + processYmlModel(file.toString(), modelName); + + }else{ + + tempMap = utils.processEpackage(file.getAbsolutePath(), MODEL_TYPE.XMI); + classMap.putAll(tempMap); + } } } cleanUpFile = "ExtractDir" + File.separator + randomID + ".zip"; @@ -92,15 +105,67 @@ public class CreateNewMicroServiceModel { } catch (IOException e) { logger.error("Failed to unzip model file " + randomID, e); } - }else { - tempMap = utils.processEpackage("ExtractDir" + File.separator + randomID+".xmi", MODEL_TYPE.XMI); - classMap.putAll(tempMap); - cleanUpFile = "ExtractDir" + File.separator + randomID+".xmi"; + }else { + if(importFile.contains(".yml")){ + + processYmlModel("ExtractDir" + File.separator + randomID+".yml", modelName); + cleanUpFile = "ExtractDir" + File.separator + randomID+".yml"; + + }else{ + tempMap = utils.processEpackage("ExtractDir" + File.separator + randomID+".xmi", MODEL_TYPE.XMI); + classMap.putAll(tempMap); + cleanUpFile = "ExtractDir" + File.separator + randomID+".xmi"; + } + File deleteFile = new File(cleanUpFile); deleteFile.delete(); } } + private void processYmlModel(String fileName, String modelName){ + + try { + + + utils.parseTosca(fileName); + + MSAttributeObject msAttributes= new MSAttributeObject(); + msAttributes.setClassName(modelName); + + LinkedHashMap<String, String> returnAttributeList =new LinkedHashMap<>(); + returnAttributeList.put(modelName, utils.getAttributeString()); + msAttributes.setAttribute(returnAttributeList); + + msAttributes.setSubClass(utils.getRetmap()); + + msAttributes.setMatchingSet(utils.getMatchableValues()); + + LinkedHashMap<String, String> returnReferenceList =new LinkedHashMap<>(); + + returnReferenceList.put(modelName, utils.getReferenceAttributes()); + msAttributes.setRefAttribute(returnReferenceList); + + if(utils.getListConstraints()!=""){ + LinkedHashMap<String, String> enumList =new LinkedHashMap<>(); + String[] listArray=utils.getListConstraints().split("#"); + for(String str:listArray){ + String[] strArr= str.split("="); + if(strArr.length>1){ + enumList.put(strArr[0], strArr[1]); + } + } + msAttributes.setEnumType(enumList); + } + + classMap=new LinkedHashMap<>(); + classMap.put(modelName, msAttributes); + + } catch (Exception e) { + logger.error("Failed to process yml model" + e); + } + + } + private List<File> listModelFiles(String directoryName) { File directory = new File(directoryName); List<File> resultList = new ArrayList<>(); @@ -171,7 +236,7 @@ public class CreateNewMicroServiceModel { } } - public Map<String, String> addValuesToNewModel() { + public Map<String, String> addValuesToNewModel(String type) { Map<String, String> successMap = new HashMap<>(); MSAttributeObject mainClass = null; @@ -185,29 +250,75 @@ public class CreateNewMicroServiceModel { return successMap; } mainClass = classMap.get(this.newModel.getModelName()); - String dependTemp = StringUtils.replaceEach(mainClass.getDependency(), new String[]{"[", "]", " "}, new String[]{"", "", ""}); - this.newModel.setDependency(dependTemp); - if (!this.newModel.getDependency().equals("")){ - dependency = new ArrayList<String>(Arrays.asList(dependTemp.split(","))); - dependency = utils.getFullDependencyList(dependency, classMap); - if (!dependency.isEmpty()){ - for (String element : dependency){ - MSAttributeObject temp; - if (classMap.containsKey(element)){ - temp = classMap.get(element); - mainClass.addAllRefAttribute(temp.getRefAttribute()); - mainClass.addAllAttribute(temp.getAttribute()); + + + if(".yml".equalsIgnoreCase(type)){ + + newModel.setDependency("[]"); + if(mainClass.getSubClass() != null){ + String value = new Gson().toJson(mainClass.getSubClass()); + newModel.setSub_attributes(value); + } + + if(mainClass.getAttribute() != null){ + String attributes= mainClass.getAttribute().toString().replace("{", "").replace("}", ""); + int equalsIndexForAttributes= attributes.indexOf("="); + String atttributesAfterFirstEquals= attributes.substring(equalsIndexForAttributes+1); + this.newModel.setAttributes(atttributesAfterFirstEquals); + } + + if(mainClass.getRefAttribute() != null){ + String refAttributes= mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""); + int equalsIndex= refAttributes.indexOf("="); + String refAttributesAfterFirstEquals= refAttributes.substring(equalsIndex+1); + this.newModel.setRef_attributes(refAttributesAfterFirstEquals); + } + + if(mainClass.getEnumType() != null){ + this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", "")); + } + + if(mainClass.getMatchingSet() != null){ + this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", "")); + } + + }else{ + + String dependTemp = StringUtils.replaceEach(mainClass.getDependency(), new String[]{"[", "]", " "}, new String[]{"", "", ""}); + this.newModel.setDependency(dependTemp); + if (this.newModel.getDependency() != null && !this.newModel.getDependency().isEmpty()){ + dependency = new ArrayList<String>(Arrays.asList(dependTemp.split(","))); + dependency = utils.getFullDependencyList(dependency, classMap); + if (!dependency.isEmpty()){ + for (String element : dependency){ + MSAttributeObject temp = new MSAttributeObject(); + if (classMap.containsKey(element)){ + temp = classMap.get(element); + mainClass.addAllRefAttribute(temp.getRefAttribute()); + mainClass.addAllAttribute(temp.getAttribute()); + } } - } - } + } + } + subAttribute = utils.createSubAttributes(dependency, classMap, this.newModel.getModelName()); + + this.newModel.setSub_attributes(subAttribute); + if(mainClass.getAttribute() != null && !mainClass.getAttribute().isEmpty()){ + this.newModel.setAttributes(mainClass.getAttribute().toString().replace("{", "").replace("}", "")); + } + + if(mainClass.getRefAttribute() != null && !mainClass.getRefAttribute().isEmpty()){ + this.newModel.setRef_attributes(mainClass.getRefAttribute().toString().replace("{", "").replace("}", "")); + } + + if(mainClass.getEnumType() != null && !mainClass.getEnumType().isEmpty()){ + this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", "")); + } + + if(mainClass.getMatchingSet() != null && !mainClass.getMatchingSet().isEmpty()){ + this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", "")); + } } - subAttribute = utils.createSubAttributes(dependency, classMap, this.newModel.getModelName()); - - this.newModel.setSub_attributes(subAttribute); - this.newModel.setAttributes(mainClass.getAttribute().toString().replace("{", "").replace("}", "")); - this.newModel.setRef_attributes(mainClass.getRefAttribute().toString().replace("{", "").replace("}", "")); - this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", "")); - this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", "")); successMap.put("success", "success"); return successMap; @@ -231,6 +342,7 @@ public class CreateNewMicroServiceModel { model.setEnumValues(this.newModel.getEnumValues()); model.setRef_attributes(this.newModel.getRef_attributes()); model.setSub_attributes(this.newModel.getSub_attributes()); + model.setDataOrderInfo(this.newModel.getDataOrderInfo()); UserInfo userInfo = new UserInfo(); userInfo.setUserLoginId(imported_by); userInfo.setUserName(imported_by); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewOptimizationModel.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewOptimizationModel.java new file mode 100644 index 000000000..c4de9a059 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewOptimizationModel.java @@ -0,0 +1,292 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.xacml.rest.components; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +import org.apache.commons.io.FileUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pap.xacml.rest.XACMLPapServlet; +import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; +import org.onap.policy.rest.jpa.OptimizationModels; +import org.onap.policy.rest.jpa.UserInfo; +import org.onap.policy.rest.util.MSAttributeObject; +import org.onap.policy.rest.util.MSModelUtils; +import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE; + +import com.google.gson.Gson; + +public class CreateNewOptimizationModel { + private static final Logger logger = FlexLogger.getLogger(CreateNewOptimizationModel.class); + private OptimizationModels newModel = null; + private HashMap<String,MSAttributeObject > classMap = new HashMap<>(); + + private static final String EXTRACTDIR = "ExtractDir"; + private static final String SUCCESS = "success"; + + + MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName()); + + public CreateNewOptimizationModel() { + super(); + } + + public CreateNewOptimizationModel(String importFile, String modelName, String description, String version, String randomID) { + + this.newModel = new OptimizationModels(); + this.newModel.setVersion(version); + this.newModel.setModelName(modelName); + this.newModel.setDescription(description); + UserInfo userInfo = new UserInfo(); + userInfo.setUserLoginId("API"); + this.newModel.setUserCreatedBy(userInfo); + String cleanUpFile = null; + + Map<String, MSAttributeObject> tempMap = new HashMap<>(); + //Need to delete the file + if (importFile.contains(".zip")){ + extractFolder(randomID + ".zip"); + File directory = new File(EXTRACTDIR + File.separator + randomID); + List<File> fileList = listModelFiles(directory.toString()); + //get all the files from a director + for (File file : fileList){ + if (file.isFile()){ + processYmlModel(file.toString(), modelName); + } + } + cleanUpFile = EXTRACTDIR + File.separator + randomID + ".zip"; + try { + FileUtils.deleteDirectory(new File(EXTRACTDIR + File.separator + randomID)); + FileUtils.deleteDirectory(new File(randomID)); + File deleteFile = new File(cleanUpFile); + FileUtils.forceDelete(deleteFile); + } catch (IOException e) { + logger.error("Failed to unzip model file " + randomID, e); + } + }else { + if(importFile.contains(".yml")){ + + processYmlModel(EXTRACTDIR + File.separator + randomID+".yml", modelName); + cleanUpFile = EXTRACTDIR + File.separator + randomID+".yml"; + + }else{ + tempMap = utils.processEpackage(EXTRACTDIR + File.separator + randomID+".xmi", MODEL_TYPE.XMI); + classMap.putAll(tempMap); + cleanUpFile = EXTRACTDIR + File.separator + randomID+".xmi"; + } + File deleteFile = new File(cleanUpFile); + deleteFile.delete(); + } + } + + private void processYmlModel(String fileName, String modelName){ + + try { + + utils.parseTosca(fileName); + + MSAttributeObject msAttributes= new MSAttributeObject(); + msAttributes.setClassName(modelName); + + LinkedHashMap<String, String> returnAttributeList =new LinkedHashMap<>(); + returnAttributeList.put(modelName, utils.getAttributeString()); + msAttributes.setAttribute(returnAttributeList); + + msAttributes.setSubClass(utils.getRetmap()); + + msAttributes.setMatchingSet(utils.getMatchableValues()); + + LinkedHashMap<String, String> returnReferenceList =new LinkedHashMap<>(); + + returnReferenceList.put(modelName, utils.getReferenceAttributes()); + msAttributes.setRefAttribute(returnReferenceList); + + if(!"".equals(utils.getListConstraints())){ + LinkedHashMap<String, String> enumList =new LinkedHashMap<>(); + String[] listArray=utils.getListConstraints().split("#"); + for(String str:listArray){ + String[] strArr= str.split("="); + if(strArr.length>1){ + enumList.put(strArr[0], strArr[1]); + } + } + msAttributes.setEnumType(enumList); + } + + classMap=new LinkedHashMap<>(); + classMap.put(modelName, msAttributes); + + } catch (Exception e) { + logger.error("Failed to process yml model" + e); + } + + } + + private List<File> listModelFiles(String directoryName) { + File directory = new File(directoryName); + List<File> resultList = new ArrayList<>(); + File[] fList = directory.listFiles(); + for (File file : fList) { + if (file.isFile()) { + resultList.add(file); + } else if (file.isDirectory()) { + resultList.addAll(listModelFiles(file.getAbsolutePath())); + } + } + return resultList; + } + + @SuppressWarnings("rawtypes") + private void extractFolder(String zipFile) { + int buffer = 2048; + File file = new File(zipFile); + + try(ZipFile zip = new ZipFile(EXTRACTDIR + File.separator +file);){ + String newPath = zipFile.substring(0, zipFile.length() - 4); + new File(newPath).mkdir(); + Enumeration zipFileEntries = zip.entries(); + + // Process each entry + while (zipFileEntries.hasMoreElements()){ + // grab a zip file entry + ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); + String currentEntry = entry.getName(); + File destFile = new File(EXTRACTDIR + File.separator + newPath + File.separator + currentEntry); + File destinationParent = destFile.getParentFile(); + + destinationParent.mkdirs(); + + if (!entry.isDirectory()){ + int currentByte; + + byte[] data = new byte[buffer]; + try(FileOutputStream fos = new FileOutputStream(destFile); + BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry)); + BufferedOutputStream dest = new BufferedOutputStream(fos, buffer)) { + + while ((currentByte = is.read(data, 0, buffer)) != -1) { + dest.write(data, 0, currentByte); + } + dest.flush(); + } + } + + if (currentEntry.endsWith(".zip")){ + extractFolder(destFile.getAbsolutePath()); + } + } + } catch (IOException e) { + logger.error("Failed to unzip model file " + zipFile + e); + } + } + + public Map<String, String> addValuesToNewModel() { + + Map<String, String> successMap = new HashMap<>(); + MSAttributeObject mainClass; + + if (!classMap.containsKey(this.newModel.getModelName())){ + logger.error("Model Provided does not contain the service name provided in request. Unable to import new model"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "AddValuesToNewModel", "Unable to pull out required values, file missing service name provided in request"); + successMap.put("error", "MISSING"); + return successMap; + } + mainClass = classMap.get(this.newModel.getModelName()); + newModel.setDependency("[]"); + if(mainClass.getSubClass() != null){ + String value = new Gson().toJson(mainClass.getSubClass()); + newModel.setSubattributes(value); + } + + if(mainClass.getAttribute() != null){ + String attributes= mainClass.getAttribute().toString().replace("{", "").replace("}", ""); + int equalsIndexForAttributes= attributes.indexOf('='); + String atttributesAfterFirstEquals= attributes.substring(equalsIndexForAttributes+1); + this.newModel.setAttributes(atttributesAfterFirstEquals); + } + + if(mainClass.getRefAttribute() != null){ + String refAttributes= mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""); + int equalsIndex= refAttributes.indexOf('='); + String refAttributesAfterFirstEquals= refAttributes.substring(equalsIndex+1); + this.newModel.setRefattributes(refAttributesAfterFirstEquals); + } + + if(mainClass.getEnumType() != null){ + this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", "")); + } + + if(mainClass.getMatchingSet() != null){ + this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", "")); + } + + successMap.put(SUCCESS, SUCCESS); + return successMap; + + } + + public Map<String, String> saveImportService(){ + String modelName = this.newModel.getModelName(); + String importedBy = "API"; + String version = this.newModel.getVersion(); + Map<String, String> successMap = new HashMap<>(); + CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); + List<Object> result = dbConnection.getDataById(OptimizationModels.class, "modelName:version", modelName+":"+version); + if(result.isEmpty()){ + OptimizationModels model = new OptimizationModels(); + model.setModelName(modelName); + model.setVersion(version); + model.setAttributes(this.newModel.getAttributes()); + model.setAnnotation(this.newModel.getAnnotation()); + model.setDependency(this.newModel.getDependency()); + model.setDescription(this.newModel.getDescription()); + model.setEnumValues(this.newModel.getEnumValues()); + model.setRefattributes(this.newModel.getRefattributes()); + model.setSubattributes(this.newModel.getSubattributes()); + model.setDataOrderInfo(this.newModel.getDataOrderInfo()); + UserInfo userInfo = new UserInfo(); + userInfo.setUserLoginId(importedBy); + userInfo.setUserName(importedBy); + model.setUserCreatedBy(userInfo); + dbConnection.save(model); + successMap.put(SUCCESS, SUCCESS); + }else{ + successMap.put("DBError", "EXISTS"); + logger.error("Import new service failed. Service already exists"); + } + return successMap; + } +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicy.java new file mode 100644 index 000000000..2a03482d2 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicy.java @@ -0,0 +1,530 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.xacml.rest.components; + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.lang.StringUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.jpa.OptimizationModels; + +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.std.IdentifierImpl; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Splitter; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +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.EffectType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + +public class OptimizationConfigPolicy extends Policy { + + private static final Logger LOGGER = FlexLogger.getLogger(OptimizationConfigPolicy.class); + + private static Map<String, String> mapAttribute = new HashMap<>(); + private static Map<String, String> mapMatch = new HashMap<>(); + + private static synchronized Map<String, String> getMatchMap () { + return mapMatch; + } + + private static synchronized void setMatchMap(Map<String, String> mm) { + mapMatch = mm; + } + + public OptimizationConfigPolicy() { + super(); + } + + public OptimizationConfigPolicy(PolicyRestAdapter policyAdapter){ + this.policyAdapter = policyAdapter; + } + + //save configuration of the policy based on the policyname + private void saveConfigurations(String policyName, String jsonBody) { + try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName +".json");){ + if(policyName.endsWith(".xml")){ + policyName = policyName.replace(".xml", ""); + } + out.println(jsonBody); + } catch (Exception e) { + LOGGER.error("Exception Occured While writing Configuration data"+e); + } + } + + + @Override + public Map<String, String> savePolicies() throws PAPException { + + Map<String, String> successMap = new HashMap<>(); + if(isPolicyExists()){ + successMap.put("EXISTS", "This Policy already exist on the PAP"); + return successMap; + } + + if(!isPreparedToSave()){ + //Prep and configure the policy for saving + prepareToSave(); + } + + // Until here we prepared the data and here calling the method to create xml. + Path newPolicyPath = null; + newPolicyPath = Paths.get(policyAdapter.getNewFileName()); + + successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject()); + + return successMap; + } + + //This is the method for preparing the policy for saving. We have broken it out + //separately because the fully configured policy is used for multiple things + @Override + public boolean prepareToSave() throws PAPException{ + + if(isPreparedToSave()){ + //we have already done this + return true; + } + + int version = 0; + String policyID = policyAdapter.getPolicyID(); + version = policyAdapter.getHighestVersion(); + + // Create the Instance for pojo, PolicyType object is used in marshalling. + if (policyAdapter.getPolicyType().equals("Config")) { + PolicyType policyConfig = new PolicyType(); + + policyConfig.setVersion(Integer.toString(version)); + policyConfig.setPolicyId(policyID); + policyConfig.setTarget(new TargetType()); + policyAdapter.setData(policyConfig); + } + policyName = policyAdapter.getNewFileName(); + if (policyAdapter.getData() != null) { + // Save the Configurations file with the policy name with extention based on selection. + String jsonBody = policyAdapter.getJsonBody(); + saveConfigurations(policyName, jsonBody); + + // Make sure the filename ends with an extension + if (!policyName.endsWith(".xml")) { + policyName = policyName + ".xml"; + } + + + PolicyType configPolicy = (PolicyType) policyAdapter.getData(); + + configPolicy.setDescription(policyAdapter.getPolicyDescription()); + + configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId()); + + AllOfType allOfOne = new AllOfType(); + String fileName = policyAdapter.getNewFileName(); + String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length()); + if ((name == null) || (name.equals(""))) { + name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length()); + } + + //setup values for pulling out matching attributes + ObjectMapper mapper = new ObjectMapper(); + String matching = null; + Map<String, String> matchMap = null; + try { + JsonNode rootNode = mapper.readTree(policyAdapter.getJsonBody()); + if (policyAdapter.getTtlDate()==null){ + policyAdapter.setTtlDate("NA"); + } + if (policyAdapter.getServiceType().contains("-v")){ + matching = getValueFromDictionary(policyAdapter.getServiceType()); + } else { + String jsonVersion = StringUtils.replaceEach(rootNode.get("version").toString(), new String[]{"\""}, new String[]{""}); + matching = getValueFromDictionary(policyAdapter.getServiceType() + "-v" + jsonVersion); + } + if (matching != null && !matching.isEmpty()){ + matchMap = Splitter.on(",").withKeyValueSeparator("=").split(matching); + setMatchMap(matchMap); + if(policyAdapter.getJsonBody() != null){ + pullMatchValue(rootNode); + } + } + } catch (IOException e1) { + throw new PAPException(e1); + } + + // Match for policyName + allOfOne.getMatch().add(createMatch("PolicyName", name)); + + AllOfType allOf = new AllOfType(); + + // Adding the matches to AllOfType element Match for Onap + allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName())); + if (matchMap!=null && !matchMap.isEmpty()) { + for (Entry<String, String> matchValue : matchMap.entrySet()){ + String value = matchValue.getValue(); + String key = matchValue.getKey().trim(); + if (value.contains("matching-true") && mapAttribute.containsKey(key)){ + allOf.getMatch().add(createDynamicMatch(key, mapAttribute.get(key))); + } + } + } + + // Match for riskType + allOf.getMatch().add( + createDynamicMatch("RiskType", policyAdapter.getRiskType())); + // Match for riskLevel + allOf.getMatch().add( + createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); + // Match for riskguard + allOf.getMatch().add( + createDynamicMatch("guard", policyAdapter.getGuard())); + // Match for ttlDate + allOf.getMatch().add( + createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); + + AnyOfType anyOf = new AnyOfType(); + anyOf.getAllOf().add(allOfOne); + anyOf.getAllOf().add(allOf); + + TargetType target = new TargetType(); + target.getAnyOf().add(anyOf); + + // Adding the target to the policy element + configPolicy.setTarget((TargetType) target); + + RuleType rule = new RuleType(); + rule.setRuleId(policyAdapter.getRuleID()); + + rule.setEffect(EffectType.PERMIT); + + // Create Target in Rule + AllOfType allOfInRule = new AllOfType(); + + // Creating match for ACCESS in rule target + MatchType accessMatch = new MatchType(); + AttributeValueType accessAttributeValue = new AttributeValueType(); + accessAttributeValue.setDataType(STRING_DATATYPE); + accessAttributeValue.getContent().add("ACCESS"); + accessMatch.setAttributeValue(accessAttributeValue); + AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType(); + URI accessURI = null; + try { + accessURI = new URI(ACTION_ID); + } catch (URISyntaxException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "OptimizationConfigPolicy", "Exception creating ACCESS URI"); + } + accessAttributeDesignator.setCategory(CATEGORY_ACTION); + accessAttributeDesignator.setDataType(STRING_DATATYPE); + accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue()); + accessMatch.setAttributeDesignator(accessAttributeDesignator); + accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); + + // Creating Config Match in rule Target + MatchType configMatch = new MatchType(); + AttributeValueType configAttributeValue = new AttributeValueType(); + configAttributeValue.setDataType(STRING_DATATYPE); + configAttributeValue.getContent().add("Config"); + configMatch.setAttributeValue(configAttributeValue); + AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType(); + URI configURI = null; + try { + configURI = new URI(RESOURCE_ID); + } catch (URISyntaxException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "OptimizationConfigPolicy", "Exception creating Config URI"); + } + configAttributeDesignator.setCategory(CATEGORY_RESOURCE); + configAttributeDesignator.setDataType(STRING_DATATYPE); + configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue()); + configMatch.setAttributeDesignator(configAttributeDesignator); + configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); + + allOfInRule.getMatch().add(accessMatch); + allOfInRule.getMatch().add(configMatch); + + AnyOfType anyOfInRule = new AnyOfType(); + anyOfInRule.getAllOf().add(allOfInRule); + + TargetType targetInRule = new TargetType(); + targetInRule.getAnyOf().add(anyOfInRule); + + rule.setTarget(targetInRule); + rule.setAdviceExpressions(getAdviceExpressions(version, policyName)); + + configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule); + policyAdapter.setPolicyData(configPolicy); + + } else { + PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName()); + } + setPreparedToSave(true); + return true; + } + + private void pullMatchValue(JsonNode rootNode) { + Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields(); + String newValue = null; + while (fieldsIterator.hasNext()) { + Map.Entry<String, JsonNode> field = fieldsIterator.next(); + final String key = field.getKey(); + final JsonNode value = field.getValue(); + if (value.isContainerNode() && !value.isArray()) { + pullMatchValue(value); // RECURSIVE CALL + } else { + newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""}); + mapAttribute.put(key, newValue); + } + } + + } + + private String getValueFromDictionary(String service){ + String ruleTemplate=null; + String modelName = service.split("-v")[0]; + String modelVersion = service.split("-v")[1]; + + CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); + List<Object> result = dbConnection.getDataById(OptimizationModels.class, "modelName:version", modelName+":"+modelVersion); + if(result != null && !result.isEmpty()){ + OptimizationModels model = (OptimizationModels) result.get(0); + ruleTemplate = model.getAnnotation(); + } + return ruleTemplate; + } + + // Data required for Advice part is setting here. + private AdviceExpressionsType getAdviceExpressions(int version, String fileName) { + AdviceExpressionsType advices = new AdviceExpressionsType(); + AdviceExpressionType advice = new AdviceExpressionType(); + advice.setAdviceId("OptimizationID"); + advice.setAppliesTo(EffectType.PERMIT); + + // For Configuration + AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType(); + assignment1.setAttributeId("type"); + assignment1.setCategory(CATEGORY_RESOURCE); + assignment1.setIssuer(""); + + AttributeValueType configNameAttributeValue = new AttributeValueType(); + configNameAttributeValue.setDataType(STRING_DATATYPE); + configNameAttributeValue.getContent().add("Configuration"); + assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue)); + + advice.getAttributeAssignmentExpression().add(assignment1); + + // For Config file Url if configurations are provided. + AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType(); + assignment2.setAttributeId("URLID"); + assignment2.setCategory(CATEGORY_RESOURCE); + assignment2.setIssuer(""); + + AttributeValueType attributeValue = new AttributeValueType(); + attributeValue.setDataType(URI_DATATYPE); + String configName; + if(policyName.endsWith(".xml")){ + configName = policyName.replace(".xml", ""); + }else{ + configName = policyName; + } + String content = CONFIG_URL +"/Config/" + configName + ".json"; + attributeValue.getContent().add(content); + assignment2.setExpression(new ObjectFactory().createAttributeValue(attributeValue)); + + advice.getAttributeAssignmentExpression().add(assignment2); + + //PolicyName Attribute Assignment + AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType(); + assignment3.setAttributeId("PolicyName"); + assignment3.setCategory(CATEGORY_RESOURCE); + assignment3.setIssuer(""); + + AttributeValueType attributeValue3 = new AttributeValueType(); + attributeValue3.setDataType(STRING_DATATYPE); + fileName = FilenameUtils.removeExtension(fileName); + fileName = fileName + ".xml"; + String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length()); + if ((name == null) || (name.equals(""))) { + name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length()); + } + attributeValue3.getContent().add(name); + assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3)); + advice.getAttributeAssignmentExpression().add(assignment3); + + //VersionNumber Attribute Assignment + AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType(); + assignment4.setAttributeId("VersionNumber"); + assignment4.setCategory(CATEGORY_RESOURCE); + assignment4.setIssuer(""); + + AttributeValueType configNameAttributeValue4 = new AttributeValueType(); + configNameAttributeValue4.setDataType(STRING_DATATYPE); + configNameAttributeValue4.getContent().add(Integer.toString(version)); + assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4)); + + advice.getAttributeAssignmentExpression().add(assignment4); + + //OnapName Attribute Assignment + AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType(); + assignment5.setAttributeId("matching:" + ONAPID); + assignment5.setCategory(CATEGORY_RESOURCE); + assignment5.setIssuer(""); + + AttributeValueType configNameAttributeValue5 = new AttributeValueType(); + configNameAttributeValue5.setDataType(STRING_DATATYPE); + configNameAttributeValue5.getContent().add(policyAdapter.getOnapName()); + assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5)); + + advice.getAttributeAssignmentExpression().add(assignment5); + + //ServiceType Attribute Assignment + AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType(); + assignment7.setAttributeId("matching:service"); + assignment7.setCategory(CATEGORY_RESOURCE); + assignment7.setIssuer(""); + + AttributeValueType configNameAttributeValue7 = new AttributeValueType(); + configNameAttributeValue7.setDataType(STRING_DATATYPE); + configNameAttributeValue7.getContent().add(policyAdapter.getServiceType()); + assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7)); + + advice.getAttributeAssignmentExpression().add(assignment7); + + // Add matching attribute assignments if exist + Map<String, String> matchMap = getMatchMap(); + if (matchMap!=null && !matchMap.isEmpty()) { + for (Entry<String, String> matchValue : matchMap.entrySet()){ + String value = matchValue.getValue(); + String key = matchValue.getKey().trim(); + if (value.contains("matching-true") && mapAttribute.containsKey(key)){ + AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType(); + assignment9.setAttributeId("matching:" + key); + assignment9.setCategory(CATEGORY_RESOURCE); + assignment9.setIssuer(""); + + AttributeValueType configNameAttributeValue9 = new AttributeValueType(); + configNameAttributeValue9.setDataType(STRING_DATATYPE); + configNameAttributeValue9.getContent().add(mapAttribute.get(key)); + assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9)); + + advice.getAttributeAssignmentExpression().add(assignment9); + } + } + } + + // Priority Attribute Assignment + AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType(); + assignment10.setAttributeId("Priority"); + assignment10.setCategory(CATEGORY_RESOURCE); + assignment10.setIssuer(""); + + AttributeValueType configNameAttributeValue10 = new AttributeValueType(); + configNameAttributeValue10.setDataType(STRING_DATATYPE); + configNameAttributeValue10.getContent().add(policyAdapter.getPriority()); + assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10)); + + advice.getAttributeAssignmentExpression().add(assignment10); + + //RiskType Attribute Assignment + AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType(); + assignment11.setAttributeId("RiskType"); + assignment11.setCategory(CATEGORY_RESOURCE); + assignment11.setIssuer(""); + + AttributeValueType configNameAttributeValue11 = new AttributeValueType(); + configNameAttributeValue11.setDataType(STRING_DATATYPE); + configNameAttributeValue11.getContent().add(policyAdapter.getRiskType()); + assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11)); + + advice.getAttributeAssignmentExpression().add(assignment11); + + //RiskLevel Attribute Assignment + AttributeAssignmentExpressionType assignment12 = new AttributeAssignmentExpressionType(); + assignment12.setAttributeId("RiskLevel"); + assignment12.setCategory(CATEGORY_RESOURCE); + assignment12.setIssuer(""); + + AttributeValueType configNameAttributeValue12 = new AttributeValueType(); + configNameAttributeValue12.setDataType(STRING_DATATYPE); + configNameAttributeValue12.getContent().add(policyAdapter.getRiskLevel()); + assignment12.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue12)); + + advice.getAttributeAssignmentExpression().add(assignment12); + + //Guard Attribute Assignment + AttributeAssignmentExpressionType assignment13 = new AttributeAssignmentExpressionType(); + assignment13.setAttributeId("guard"); + assignment13.setCategory(CATEGORY_RESOURCE); + assignment13.setIssuer(""); + + AttributeValueType configNameAttributeValue13 = new AttributeValueType(); + configNameAttributeValue13.setDataType(STRING_DATATYPE); + configNameAttributeValue13.getContent().add(policyAdapter.getGuard()); + assignment13.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue13)); + + advice.getAttributeAssignmentExpression().add(assignment13); + + //TTLDate Attribute Assignment + AttributeAssignmentExpressionType assignment14 = new AttributeAssignmentExpressionType(); + assignment14.setAttributeId("TTLDate"); + assignment14.setCategory(CATEGORY_RESOURCE); + assignment14.setIssuer(""); + + AttributeValueType configNameAttributeValue14 = new AttributeValueType(); + configNameAttributeValue14.setDataType(STRING_DATATYPE); + configNameAttributeValue14.getContent().add(policyAdapter.getTtlDate()); + assignment14.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue14)); + + advice.getAttributeAssignmentExpression().add(assignment14); + + advices.getAdviceExpression().add(advice); + return advices; + } + + @Override + public Object getCorrectPolicyDataObject() { + return policyAdapter.getPolicyData(); + } +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/Policy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/Policy.java index 2196209d8..3b3e81ee2 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/Policy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/Policy.java @@ -204,9 +204,9 @@ public abstract class Policy { String policyDir = EMPTY_STRING; String absolutePath = parent.toString(); if (absolutePath != null && !absolutePath.equals(EMPTY_STRING)) { - policyDir = absolutePath.substring(absolutePath.lastIndexOf("\\") + 1, absolutePath.length()); + policyDir = absolutePath.substring(absolutePath.lastIndexOf('\\') + 1, absolutePath.length()); if (policyDir == null || policyDir.equals(EMPTY_STRING)) { - policyDir = absolutePath.substring(absolutePath.lastIndexOf("/") + 1, absolutePath.length()); + policyDir = absolutePath.substring(absolutePath.lastIndexOf('/') + 1, absolutePath.length()); } } @@ -214,10 +214,9 @@ public abstract class Policy { if (policyDir != null && !policyDir.equals(EMPTY_STRING)) { fileName = policyType + "_" + String.format(polcyFileName) + "." + version + ".xml"; } - if (fileName != null) { - newFile = Paths.get(parent.toString(), fileName); - } - if (Files.notExists(newFile)) { + + newFile = Paths.get(parent.toString(), fileName); + if (newFile.toFile().exists()) { return newFile; } return null; @@ -231,26 +230,28 @@ public abstract class Policy { String policyDir = EMPTY_STRING; String absolutePath = parentPath.toString(); if (absolutePath != null && !absolutePath.equals(EMPTY_STRING)) { - policyDir = absolutePath.substring(absolutePath.lastIndexOf("\\") + 1, absolutePath.length()); + policyDir = absolutePath.substring(absolutePath.lastIndexOf('\\') + 1, absolutePath.length()); if (policyDir == null || policyDir.equals(EMPTY_STRING)) { - policyDir = absolutePath.substring(absolutePath.lastIndexOf("/") + 1, absolutePath.length()); + policyDir = absolutePath.substring(absolutePath.lastIndexOf('/') + 1, absolutePath.length()); } } String fileName = "default"; if (policyDir != null && !policyDir.equals(EMPTY_STRING)) { - if(policyConfigType.equals("ClosedLoop_PM")){ + if("ClosedLoop_PM".equals(policyConfigType)){ fileName = policyType + "_" + "PM" + "_" +java.lang.String.format(policyFileName) + "." +version +".xml"; - }else if(policyConfigType.equals("ClosedLoop_Fault")){ + }else if("ClosedLoop_Fault".equals(policyConfigType)){ fileName = policyType + "_" + "Fault" + "_" +java.lang.String.format(policyFileName) + "." + version + ".xml"; - }else if(policyConfigType.equals("Micro Service")){ + }else if("Micro Service".equals(policyConfigType)){ fileName = policyType + "_" + "MS" + "_" + java.lang.String.format(policyFileName) + "." + version + ".xml"; + }else if("Optimization".equals(policyConfigType)) { + fileName = policyType + "_" + "OOF" + "_" + java.lang.String.format(policyFileName) + "." + version + ".xml"; } } - if (fileName != null) { - newFile = Paths.get(parentPath.toString(), fileName); - } - if (Files.notExists(newFile)) { + + newFile = Paths.get(parentPath.toString(), fileName); + + if (newFile.toFile().exists()) { return newFile; } return null; diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportController.java index f3c78ffb9..9423017c3 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportController.java @@ -79,16 +79,21 @@ public class DictionaryImportController { private static CommonClassDao commonClassDao; private static final String DESCRIPTION= "description"; + private static final String ERROR= "Error"; + private static final String DEPENDENCY= "dependency"; @Autowired public DictionaryImportController(CommonClassDao commonClassDao){ + setCommonClassDao(commonClassDao); + } + + public static void setCommonClassDao(CommonClassDao commonClassDao) { DictionaryImportController.commonClassDao = commonClassDao; } public DictionaryImportController(){ - super(); - } - + super(); + } @RequestMapping(value={"/dictionary/import_dictionary"}, method={RequestMethod.POST}) public void importDictionaryData(HttpServletRequest request, HttpServletResponse response) throws IOException{ @@ -100,15 +105,15 @@ public class DictionaryImportController { if(dictionaryName == null || dictionaryName.isEmpty()){ LOGGER.error("dictionaryName is null/empty"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.getWriter().write("Error"); + response.getWriter().write(ERROR); return; } // fix Fortify Path Manipulation issue if(!isValidDictionaryName(dictionaryName)){ LOGGER.error("dictionaryName is invalid"); - response.setStatus(HttpServletResponse.SC_OK); - response.getWriter().write("Dictionary Import failed. Hence the following dictionary doen't support import function : "+ dictionaryName); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.getWriter().write(ERROR); return; } File file = new File(dictionaryName); @@ -230,7 +235,7 @@ public class DictionaryImportController { if(DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])){ attribute.setDescription(rows[j]); } - if("dependency".equalsIgnoreCase(dictSheet.get(0)[j])){ + if(DEPENDENCY.equalsIgnoreCase(dictSheet.get(0)[j])){ attribute.setDependency(rows[j]); } if("attributes".equalsIgnoreCase(dictSheet.get(0)[j])){ @@ -245,6 +250,50 @@ public class DictionaryImportController { if("Sub Attributes".equalsIgnoreCase(dictSheet.get(0)[j])){ attribute.setSub_attributes(rows[j]); } + if("annotations".equalsIgnoreCase(dictSheet.get(0)[j])) { + attribute.setAnnotation(rows[j]); + } + } + + commonClassDao.save(attribute); + } + } + + if(dictionaryName.startsWith("OptimizationPolicyDictionary")){ + for(int i = 1; i< dictSheet.size(); i++){ + MicroServiceModels attribute = new MicroServiceModels(); + UserInfo userinfo = new UserInfo(); + userinfo.setUserLoginId(userId); + attribute.setUserCreatedBy(userinfo); + String[] rows = dictSheet.get(i); + for (int j=0 ; j<rows.length; j++ ){ + if("modelName".equalsIgnoreCase(dictSheet.get(0)[j]) || "Optimization Service Model".equalsIgnoreCase(dictSheet.get(0)[j])){ + attribute.setModelName(rows[j]); + } + if("version".equalsIgnoreCase(dictSheet.get(0)[j]) || "Model Version".equalsIgnoreCase(dictSheet.get(0)[j])){ + attribute.setVersion(rows[j]); + } + if(DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])){ + attribute.setDescription(rows[j]); + } + if(DEPENDENCY.equalsIgnoreCase(dictSheet.get(0)[j])){ + attribute.setDependency(rows[j]); + } + if("attributes".equalsIgnoreCase(dictSheet.get(0)[j])){ + attribute.setAttributes(rows[j]); + } + if("enumValues".equalsIgnoreCase(dictSheet.get(0)[j])){ + attribute.setEnumValues(rows[j]); + } + if("Ref Attributes".equalsIgnoreCase(dictSheet.get(0)[j])){ + attribute.setRef_attributes(rows[j]); + } + if("Sub Attributes".equalsIgnoreCase(dictSheet.get(0)[j])){ + attribute.setSub_attributes(rows[j]); + } + if("annotations".equalsIgnoreCase(dictSheet.get(0)[j])) { + attribute.setAnnotation(rows[j]); + } } commonClassDao.save(attribute); @@ -427,7 +476,7 @@ public class DictionaryImportController { if(DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])){ attribute.setDescription(rows[j]); } - if("dependency".equalsIgnoreCase(dictSheet.get(0)[j])){ + if(DEPENDENCY.equalsIgnoreCase(dictSheet.get(0)[j])){ attribute.setDependency(rows[j]); } } @@ -677,7 +726,7 @@ public class DictionaryImportController { }catch(Exception e){ LOGGER.error("Exception Occured while importing dictionary"+e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.getWriter().write("Error"); + response.getWriter().write(ERROR); }finally{ if(file != null && file.exists()){ boolean deleted = file.delete(); @@ -696,6 +745,7 @@ public class DictionaryImportController { case ActionPolicyDictionary: case OnapName: case MSPolicyDictionary: + case OptimizationPolicyDictionary: case VNFType: case VSCLAction: case ClosedLoopService: diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java index becf5adf7..6acae3fbd 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java @@ -24,6 +24,7 @@ import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; @@ -44,6 +45,7 @@ import org.onap.policy.rest.jpa.MicroServiceAttribute; import org.onap.policy.rest.jpa.MicroServiceConfigName; import org.onap.policy.rest.jpa.MicroServiceLocation; import org.onap.policy.rest.jpa.MicroServiceModels; +import org.onap.policy.rest.jpa.MicroserviceHeaderdeFaults; import org.onap.policy.rest.jpa.PrefixList; import org.onap.policy.rest.jpa.UserInfo; import org.onap.policy.rest.util.MSAttributeObject; @@ -72,9 +74,11 @@ public class MicroServiceDictionaryController { private static String getDictionary = "getDictionary"; private static String errorMsg = "error"; private static String dictionaryDBQuery = "dictionaryDBQuery"; - private HashMap<String,MSAttributeObject > classMap; + private LinkedHashMap<String,MSAttributeObject > classMap; private List<String> modelList = new ArrayList<>(); + private static String apiflag = "apiflag"; private static String dictionaryFields ="dictionaryFields"; + private static String update = "update"; private static String duplicateResponseString = "Duplicate"; private static String microServiceModelsDictionaryDatas = "microServiceModelsDictionaryDatas"; private static String modelName = "modelName"; @@ -86,6 +90,7 @@ public class MicroServiceDictionaryController { private static String microServiceConfigNameDatas = "microServiceConfigNameDictionaryDatas"; private static String microServiceLocationDatas = "microServiceLocationDictionaryDatas"; private static String microServiceAttributeDatas = "microServiceAttributeDictionaryDatas"; + private static String microServiceHeaderDefaultDatas = "microServiceHeaderDefaultDatas"; public MicroServiceDictionaryController(){ super(); @@ -136,7 +141,7 @@ public class MicroServiceDictionaryController { List<Object> duplicateData = commonClassDao.checkDuplicateEntry(dCAEuuid.getName(), "name", DCAEuuid.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if(duplicateData != null && !duplicateData.isEmpty()){ DCAEuuid data = (DCAEuuid) duplicateData.get(0); if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ dCAEuuid.setId(data.getId()); @@ -201,7 +206,7 @@ public class MicroServiceDictionaryController { } List<Object> duplicateData = commonClassDao.checkDuplicateEntry(microServiceConfigName.getName(), "name", MicroServiceConfigName.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if(duplicateData != null && !duplicateData.isEmpty()){ MicroServiceConfigName data = (MicroServiceConfigName) duplicateData.get(0); if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ microServiceConfigName.setId(data.getId()); @@ -267,7 +272,7 @@ public class MicroServiceDictionaryController { List<Object> duplicateData = commonClassDao.checkDuplicateEntry(microServiceLocation.getName(), "name", MicroServiceLocation.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if(duplicateData != null && !duplicateData.isEmpty()){ MicroServiceLocation data = (MicroServiceLocation) duplicateData.get(0); if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ microServiceLocation.setId(data.getId()); @@ -329,16 +334,13 @@ public class MicroServiceDictionaryController { String checkValue; if (fromAPI) { microServiceAttribute = mapper.readValue(root.get(dictionaryFields).toString(), MicroServiceAttribute.class); - MicroServiceAttribute initialAttribute = (MicroServiceAttribute)mapper.readValue(root.get("initialFields").toString(), MicroServiceAttribute.class); - checkValue = initialAttribute.getName() + ":" + initialAttribute.getValue() + ":" + initialAttribute.getModelName(); } else { microServiceAttribute = mapper.readValue(root.get("modelAttributeDictionaryData").toString(), MicroServiceAttribute.class); - checkValue = microServiceAttribute.getName() + ":" + microServiceAttribute.getValue() + ":" + microServiceAttribute.getModelName(); } - + checkValue = microServiceAttribute.getName() + ":" + microServiceAttribute.getValue() + ":" + microServiceAttribute.getModelName(); List<Object> duplicateData = commonClassDao.checkDuplicateEntry(checkValue, "name:value:modelName", MicroServiceAttribute.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if(duplicateData != null && !duplicateData.isEmpty()){ MicroServiceAttribute data = (MicroServiceAttribute) duplicateData.get(0); if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ microServiceAttribute.setId(data.getId()); @@ -472,6 +474,11 @@ public class MicroServiceDictionaryController { JsonNode root = mapper.readTree(request.getReader()); MicroServiceModels microServiceModels = new MicroServiceModels(); String userId = null; + + String dataOrderInfo = null; + if(root.has("dataOrderInfo")){ + dataOrderInfo = root.get("dataOrderInfo").toString(); + } if(root.has("modelType")){ JsonNode dataType = root.get("modelType"); @@ -491,7 +498,7 @@ public class MicroServiceDictionaryController { } } - classMap = new HashMap<>(); + classMap = new LinkedHashMap<>(); JsonNode data = root.get(classMapData); ObjectMapper mapper1 = new ObjectMapper(); String data1 = data.toString().substring(1, data.toString().length()-1); @@ -513,11 +520,11 @@ public class MicroServiceDictionaryController { this.newModel.setSub_attributes(value); String attributes= mainClass.getAttribute().toString().replace("{", "").replace("}", ""); int equalsIndexForAttributes= attributes.indexOf('='); - String atttributesAfterFirstEquals= attributes.substring(equalsIndexForAttributes+1, attributes.length()-1); + String atttributesAfterFirstEquals= attributes.substring(equalsIndexForAttributes+1); this.newModel.setAttributes(atttributesAfterFirstEquals); String refAttributes= mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""); - int equalsIndex= refAttributes.indexOf('='); - String refAttributesAfterFirstEquals= refAttributes.substring(equalsIndex+1, refAttributes.length()-1); + int equalsIndex= refAttributes.indexOf("="); + String refAttributesAfterFirstEquals= refAttributes.substring(equalsIndex+1); this.newModel.setRef_attributes(refAttributesAfterFirstEquals); this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", "")); this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", "")); @@ -541,7 +548,7 @@ public class MicroServiceDictionaryController { } } if(root.has(classMapData)){ - classMap = new HashMap<>(); + classMap = new LinkedHashMap<>(); JsonNode data = root.get(classMapData); ObjectMapper mapper1 = new ObjectMapper(); String data1 = data.toString().substring(1, data.toString().length()-1); @@ -567,11 +574,13 @@ public class MicroServiceDictionaryController { microServiceModels.setVersion(this.newModel.getVersion()); microServiceModels.setEnumValues(this.newModel.getEnumValues()); microServiceModels.setAnnotation(this.newModel.getAnnotation()); - + if(dataOrderInfo != null){ + microServiceModels.setDataOrderInfo(dataOrderInfo); + } String checkName = microServiceModels.getModelName() + ":" + microServiceModels.getVersion(); List<Object> duplicateData = commonClassDao.checkDuplicateEntry(checkName, "modelName:version", MicroServiceModels.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if(duplicateData != null && !duplicateData.isEmpty()){ MicroServiceModels data = (MicroServiceModels) duplicateData.get(0); if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ microServiceModels.setId(data.getId()); @@ -667,5 +676,74 @@ public class MicroServiceDictionaryController { return returnList; } - -} + + @RequestMapping(value={"/get_MicroServiceHeaderDefaultsDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getMicroServiceHeaderDefaultsEntityDataByName(HttpServletResponse response){ + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, microServiceHeaderDefaultDatas, "modelName", MicroserviceHeaderdeFaults.class); + } + + @RequestMapping(value={"/get_MicroServiceHeaderDefaultsData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getMicroServiceHeaderDefaultsEntityData(HttpServletResponse response){ + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, microServiceHeaderDefaultDatas, MicroserviceHeaderdeFaults.class); + } + + + @RequestMapping(value={"/ms_dictionary/save_headerDefaults"}, method={RequestMethod.POST}) + public ModelAndView saveMicroServiceHeaderDefaultValues(HttpServletRequest request, HttpServletResponse response) throws IOException{ + DictionaryUtils utils = getDictionaryUtilsInstance(); + try { + boolean fromAPI = utils.isRequestFromAPI(request); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + + MicroserviceHeaderdeFaults msHeaderdeFaults; + if(fromAPI){ + msHeaderdeFaults = mapper.readValue(root.get(dictionaryFields).toString(), MicroserviceHeaderdeFaults.class); + }else{ + msHeaderdeFaults = mapper.readValue(root.get("modelAttributeDictionaryData").toString(), MicroserviceHeaderdeFaults.class); + } + + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(msHeaderdeFaults.getModelName(), "modelName", MicroserviceHeaderdeFaults.class); + boolean duplicateflag = false; + if(duplicateData != null && !duplicateData.isEmpty()){ + MicroserviceHeaderdeFaults data = (MicroserviceHeaderdeFaults) duplicateData.get(0); + if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + msHeaderdeFaults.setId(data.getId()); + }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || + (request.getParameter(operation) == null && (data.getId() != msHeaderdeFaults.getId()))){ + duplicateflag = true; + } + } + + String responseString = null; + if(!duplicateflag){ + if(msHeaderdeFaults.getId() == 0){ + commonClassDao.save(msHeaderdeFaults); + }else{ + commonClassDao.update(msHeaderdeFaults); + } + responseString = mapper.writeValueAsString(commonClassDao.getData(MicroserviceHeaderdeFaults.class)); + }else{ + responseString = duplicateResponseString; + } + if(fromAPI){ + return utils.getResultForApi(responseString); + }else{ + utils.setResponseData(response, microServiceHeaderDefaultDatas, responseString); + } + } + catch (Exception e){ + utils.setErrorResponseData(response, e); + } + return null; + } + + @RequestMapping(value={"/ms_dictionary/remove_headerDefaults"}, method={RequestMethod.POST}) + public void removeMicroServiceHeaderDefaults(HttpServletRequest request, HttpServletResponse response) throws IOException{ + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.removeData(request, response, microServiceHeaderDefaultDatas, MicroserviceHeaderdeFaults.class); + } +}
\ No newline at end of file diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryController.java new file mode 100644 index 000000000..acb5a2afe --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryController.java @@ -0,0 +1,318 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.policy.pap.xacml.rest.controller; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringUtils; +import org.json.JSONObject; +import org.onap.policy.pap.xacml.rest.XACMLPapServlet; +import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.OptimizationModels; +import org.onap.policy.rest.jpa.UserInfo; +import org.onap.policy.rest.util.MSAttributeObject; +import org.onap.policy.rest.util.MSModelUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; + +@Controller +public class OptimizationDictionaryController { + private static CommonClassDao commonClassDao; + + private static String operation = "operation"; + private LinkedHashMap<String,MSAttributeObject > classMap; + private static String dictionaryFields ="dictionaryFields"; + private static String duplicateResponseString = "Duplicate"; + private static String optimizationModelsDictionaryDatas = "optimizationModelsDictionaryDatas"; + private static String modelName = "modelName"; + private static String optimizationModelsDictionaryData = "optimizationModelsDictionaryData"; + private static String description = "description"; + private static String version = "version"; + private static String classMapData = "classMap"; + private static final String UPDATE = "update"; + + + public OptimizationDictionaryController(){ + super(); + } + + private DictionaryUtils getDictionaryUtilsInstance(){ + return DictionaryUtils.getDictionaryUtils(); + } + + @Autowired + public OptimizationDictionaryController(CommonClassDao commonClassDao){ + setCommonClassDao(commonClassDao); + } + public static void setCommonClassDao(CommonClassDao commonClassDao) { + OptimizationDictionaryController.commonClassDao = commonClassDao; + } + + MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName()); + + private OptimizationModels newModel; + + @RequestMapping(value={"/get_OptimizationModelsData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getOptimizationModelsDictionaryEntityData(HttpServletResponse response){ + DictionaryUtils dUtils = getDictionaryUtilsInstance(); + dUtils.getData(response, optimizationModelsDictionaryDatas, OptimizationModels.class); + } + + @RequestMapping(value={"/get_OptimizationModelsDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getOptimizationModelsDictionaryByNameEntityData(HttpServletResponse response){ + DictionaryUtils dUtils = getDictionaryUtilsInstance(); + dUtils.getDataByEntity(response, optimizationModelsDictionaryDatas, modelName, OptimizationModels.class); + } + + @RequestMapping(value={"/oof_dictionary/save_model"}, method={RequestMethod.POST}) + public ModelAndView saveOptimizationModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + DictionaryUtils dUtils = getDictionaryUtilsInstance(); + try { + this.newModel = new OptimizationModels(); + boolean fromAPI = dUtils.isRequestFromAPI(request); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + OptimizationModels optimizationModels = new OptimizationModels(); + String userId = null; + + String dataOrderInfo = null; + if(root.has("dataOrderInfo")){ + dataOrderInfo = root.get("dataOrderInfo").toString(); + } + + if(root.has("modelType")){ + JsonNode dataType = root.get("modelType"); + String modelType= dataType.toString(); + if(modelType.contains("yml")){ + if (root.has(optimizationModelsDictionaryData)){ + if (root.get(optimizationModelsDictionaryData).has(description)){ + optimizationModels.setDescription(root.get(optimizationModelsDictionaryData).get(description).asText().replace("\"", "")); + } + if (root.get(optimizationModelsDictionaryData).has(modelName)){ + optimizationModels.setModelName(root.get(optimizationModelsDictionaryData).get(modelName).asText().replace("\"", "")); + this.newModel.setModelName(optimizationModels.getModelName()); + } + if (root.get(optimizationModelsDictionaryData).has(version)){ + optimizationModels.setVersion(root.get(optimizationModelsDictionaryData).get(version).asText().replace("\"", "")); + this.newModel.setVersion(optimizationModels.getVersion()); + } + } + + classMap = new LinkedHashMap<>(); + JsonNode data = root.get(classMapData); + ObjectMapper mapper1 = new ObjectMapper(); + String data1 = data.toString().substring(1, data.toString().length()-1); + data1 = data1.replace("\\", ""); + data1=data1.replace("\"{","{"); + data1=data1.replace("}\"","}"); + JSONObject jsonObject = new JSONObject(data1); + Set<String> keys = jsonObject.keySet(); + for(String key : keys){ + String value = jsonObject.get(key).toString(); + MSAttributeObject msAttributeObject = mapper1.readValue(value, MSAttributeObject.class); + classMap.put(key, msAttributeObject); + } + + userId = root.get("userid").textValue(); + MSAttributeObject mainClass = classMap.get(this.newModel.getModelName()); + this.newModel.setDependency("[]"); + String value = new Gson().toJson(mainClass.getSubClass()); + this.newModel.setSubattributes(value); + String attributes= mainClass.getAttribute().toString().replace("{", "").replace("}", ""); + int equalsIndexForAttributes= attributes.indexOf('='); + String atttributesAfterFirstEquals= attributes.substring(equalsIndexForAttributes+1, attributes.length()-1); + this.newModel.setAttributes(atttributesAfterFirstEquals); + String refAttributes= mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""); + int equalsIndex= refAttributes.indexOf('='); + String refAttributesAfterFirstEquals= refAttributes.substring(equalsIndex+1, refAttributes.length()-1); + this.newModel.setRefattributes(refAttributesAfterFirstEquals); + this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", "")); + this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", "")); + + }else{ + if (fromAPI) { + optimizationModels = mapper.readValue(root.get(dictionaryFields).toString(), OptimizationModels.class); + userId = "API"; + } else { + if (root.has(optimizationModelsDictionaryData)){ + if (root.get(optimizationModelsDictionaryData).has(description)){ + optimizationModels.setDescription(root.get(optimizationModelsDictionaryData).get(description).asText().replace("\"", "")); + } + if (root.get(optimizationModelsDictionaryData).has(modelName)){ + optimizationModels.setModelName(root.get(optimizationModelsDictionaryData).get(modelName).asText().replace("\"", "")); + this.newModel.setModelName(optimizationModels.getModelName()); + } + if (root.get(optimizationModelsDictionaryData).has(version)){ + optimizationModels.setVersion(root.get(optimizationModelsDictionaryData).get(version).asText().replace("\"", "")); + this.newModel.setVersion(optimizationModels.getVersion()); + } + } + if(root.has(classMapData)){ + classMap = new LinkedHashMap<>(); + JsonNode data = root.get(classMapData); + ObjectMapper mapper1 = new ObjectMapper(); + String data1 = data.toString().substring(1, data.toString().length()-1); + data1 = data1.replace("\\", ""); + JSONObject jsonObject = new JSONObject(data1); + Set<String> keys = jsonObject.keySet(); + for(String key : keys){ + String value = jsonObject.get(key).toString(); + MSAttributeObject msAttributeObject = mapper1.readValue(value, MSAttributeObject.class); + classMap.put(key, msAttributeObject); + } + } + userId = root.get("userid").textValue(); + addValuesToNewModel(classMap); + } + } + } + optimizationModels.setAttributes(this.newModel.getAttributes()); + optimizationModels.setRefattributes(this.newModel.getRefattributes()); + optimizationModels.setDependency(this.newModel.getDependency()); + optimizationModels.setModelName(this.newModel.getModelName()); + optimizationModels.setSubattributes(this.newModel.getSubattributes()); + optimizationModels.setVersion(this.newModel.getVersion()); + optimizationModels.setEnumValues(this.newModel.getEnumValues()); + optimizationModels.setAnnotation(this.newModel.getAnnotation()); + + if(dataOrderInfo != null){ + optimizationModels.setDataOrderInfo(dataOrderInfo); + } + + String checkName = optimizationModels.getModelName() + ":" + optimizationModels.getVersion(); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(checkName, "modelName:version", OptimizationModels.class); + boolean duplicateflag = false; + if(duplicateData!=null && !duplicateData.isEmpty()){ + OptimizationModels data = (OptimizationModels) duplicateData.get(0); + if(request.getParameter(operation) != null && UPDATE.equals(request.getParameter(operation))){ + optimizationModels.setId(data.getId()); + }else if((request.getParameter(operation) != null && !UPDATE.equals(request.getParameter(operation))) || + (request.getParameter(operation) == null && (data.getId() != optimizationModels.getId()))){ + duplicateflag = true; + } + } + UserInfo userInfo = dUtils.getUserInfo(userId); + + String responseString = null; + if(!duplicateflag){ + optimizationModels.setUserCreatedBy(userInfo); + if(optimizationModels.getId() == 0){ + commonClassDao.save(optimizationModels); + }else{ + commonClassDao.update(optimizationModels); + } + responseString = mapper.writeValueAsString(commonClassDao.getData(OptimizationModels.class)); + }else{ + responseString = duplicateResponseString; + } + if(fromAPI){ + return dUtils.getResultForApi(responseString); + }else{ + dUtils.setResponseData(response, optimizationModelsDictionaryDatas, responseString); + } + }catch (Exception e){ + dUtils.setErrorResponseData(response, e); + } + return null; + } + + @RequestMapping(value={"/oof_dictionary/remove_model"}, method={RequestMethod.POST}) + public void removeOptimizationModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + DictionaryUtils dUtils = getDictionaryUtilsInstance(); + dUtils.removeData(request, response, optimizationModelsDictionaryDatas, OptimizationModels.class); + } + + private void addValuesToNewModel(HashMap<String,MSAttributeObject > classMap) { + //Loop through the classmap and pull out the required info for the new file. + String subAttribute = null; + + MSAttributeObject mainClass = classMap.get(this.newModel.getModelName()); + + if (mainClass !=null){ + String dependTemp = StringUtils.replaceEach(mainClass.getDependency(), new String[]{"[", "]", " "}, new String[]{"", "", ""}); + ArrayList<String> dependency = new ArrayList<>(Arrays.asList(dependTemp.split(","))); + dependency = getFullDependencyList(dependency); + for (String element : dependency){ + MSAttributeObject temp = classMap.get(element); + if (temp!=null){ + mainClass.addAllRefAttribute(temp.getRefAttribute()); + mainClass.addAllAttribute(temp.getAttribute()); + } + } + subAttribute = utils.createSubAttributes(dependency, classMap, this.newModel.getModelName()); + }else{ + subAttribute = "{}"; + this.newModel.setDependency(""); + } + + if (mainClass != null && mainClass.getDependency()==null){ + mainClass.setDependency(""); + } + if(mainClass != null){ + this.newModel.setDependency(mainClass.getDependency()); + this.newModel.setSubattributes(subAttribute); + this.newModel.setAttributes(mainClass.getAttribute().toString().replace("{", "").replace("}", "")); + this.newModel.setRefattributes(mainClass.getRefAttribute().toString().replace("{", "").replace("}", "")); + this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", "")); + this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", "")); + } + } + + private ArrayList<String> getFullDependencyList(ArrayList<String> dependency) { + ArrayList<String> returnList = new ArrayList<>(); + ArrayList<String> workingList; + returnList.addAll(dependency); + for (String element : dependency ){ + if (classMap.containsKey(element)){ + MSAttributeObject value = classMap.get(element); + String rawValue = StringUtils.replaceEach(value.getDependency(), new String[]{"[", "]"}, new String[]{"", ""}); + workingList = new ArrayList<>(Arrays.asList(rawValue.split(","))); + for(String depend : workingList){ + if (!returnList.contains(depend) && !depend.isEmpty()){ + returnList.add(depend.trim()); + } + } + } + } + + return returnList; + } + +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java index 1dea5dd4b..83d5c3ff9 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java @@ -47,6 +47,7 @@ public interface ElkConnector { Config_PM, Config_FW, Config_MS, + Config_OOF, none, } @@ -85,6 +86,8 @@ public interface ElkConnector { return PolicyIndexType.config; } else if (policyName.startsWith("Config_MS")) { return PolicyIndexType.config; + } else if (policyName.startsWith("Config_OOF")) { + return PolicyIndexType.config; }else if (policyName.startsWith("Action")) { return PolicyIndexType.action; } else if (policyName.startsWith("Decision")) { diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/APIRequestHandler.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/APIRequestHandler.java index a031ac647..db7711039 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/APIRequestHandler.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/APIRequestHandler.java @@ -60,7 +60,7 @@ public class APIRequestHandler { } public void doPut(HttpServletRequest request, HttpServletResponse response, String service) throws IOException { - if ("MICROSERVICE".equalsIgnoreCase(service) || "BRMSPARAM".equalsIgnoreCase(service)){ + if ("MICROSERVICE".equalsIgnoreCase(service) || "BRMSPARAM".equalsIgnoreCase(service) || "OPTIMIZATION".equalsIgnoreCase(service)){ ImportService importService = new ImportService(); importService.doImportMicroServicePut(request, response); return; diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerImpl.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerImpl.java index f1cc9e6e4..d0cd985a3 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerImpl.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerImpl.java @@ -117,6 +117,12 @@ public class DictionaryHandlerImpl implements DictionaryHandler{ case "MicroServiceModels": dictionary.getMicroServiceModelsDictionary(response); break; + case "MicroServiceDictionary": + dictionary.getMicroServiceDictionary(response); + break; + case "OptimizationModels": + dictionary.getOptimizationModelsDictionary(response); + break; case "PolicyScopeService": dictionary.getPSServiceDictionary(response); break; @@ -138,9 +144,6 @@ public class DictionaryHandlerImpl implements DictionaryHandler{ case "SafePolicyWarning": dictionary.getSafePolicyWarningDictionary(response); break; - case "MicroServiceDictionary": - dictionary.getMicroServiceDictionary(response); - break; default: extendedOptions(dictionaryType, request, response, true); return; @@ -260,6 +263,12 @@ public class DictionaryHandlerImpl implements DictionaryHandler{ case "MicroServiceModels": result = dictionary.saveMicroServiceModelsDictionary(request, response); break; + case "MicroServiceDictionary": + result = dictionary.saveMicroServiceDictionary(request, response); + break; + case "OptimizationModels": + result = dictionary.saveOptimizationModelsDictionary(request, response); + break; case "PolicyScopeService": result = dictionary.savePSServiceDictionary(request, response); break; @@ -281,9 +290,6 @@ public class DictionaryHandlerImpl implements DictionaryHandler{ case "SafePolicyWarning": result = dictionary.saveSafePolicyWarningDictionary(request, response); break; - case "MicroServiceDictionary": - result = dictionary.saveMicroServiceDictionary(request, response); - break; default: result = extendedOptions(dictionaryType, request, response, false); if(result==null){ diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreation.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreation.java index 48f67aa94..f7ef1a097 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreation.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreation.java @@ -44,6 +44,7 @@ import org.onap.policy.pap.xacml.rest.components.CreateClosedLoopPerformanceMetr import org.onap.policy.pap.xacml.rest.components.DecisionPolicy; import org.onap.policy.pap.xacml.rest.components.FirewallConfigPolicy; import org.onap.policy.pap.xacml.rest.components.MicroServiceConfigPolicy; +import org.onap.policy.pap.xacml.rest.components.OptimizationConfigPolicy; import org.onap.policy.pap.xacml.rest.components.Policy; import org.onap.policy.pap.xacml.rest.components.PolicyDBDao; import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTransaction; @@ -133,6 +134,8 @@ public class PolicyCreation extends AbstractPolicyCreation{ filePrefix = "Config_PM_"; }else if ("Micro Service".equalsIgnoreCase(policyConfigType)) { filePrefix = "Config_MS_"; + }else if ("Optimization".equalsIgnoreCase(policyConfigType)) { + filePrefix = "Config_OOF_"; }else if ("BRMS_Raw".equalsIgnoreCase(policyConfigType)) { filePrefix = "Config_BRMS_Raw_"; }else if ("BRMS_Param".equalsIgnoreCase(policyConfigType)) { @@ -247,14 +250,14 @@ public class PolicyCreation extends AbstractPolicyCreation{ policyData.setHighestVersion(version); // Calling Component class per policy type - if (policyType.equalsIgnoreCase("Config")) { - if (policyConfigType.equalsIgnoreCase("Firewall Config")) { + if ("Config".equalsIgnoreCase(policyType)) { + if ("Firewall Config".equalsIgnoreCase(policyConfigType)) { newPolicy = new FirewallConfigPolicy(policyData); - }else if (policyConfigType.equalsIgnoreCase("BRMS_Raw")) { + }else if ("BRMS_Raw".equalsIgnoreCase(policyConfigType)) { policyData.setOnapName("DROOLS"); policyData.setConfigName("BRMS_RAW_RULE"); newPolicy = new CreateBrmsRawPolicy(policyData); - }else if (policyConfigType.equalsIgnoreCase("BRMS_Param")) { + }else if ("BRMS_Param".equalsIgnoreCase(policyConfigType)) { policyData.setOnapName("DROOLS"); policyData.setConfigName("BRMS_PARAM_RULE"); Map<String, String> drlRuleAndUIParams = new HashMap<>(); @@ -287,11 +290,11 @@ public class PolicyCreation extends AbstractPolicyCreation{ } } newPolicy = new CreateBrmsParamPolicy(policyData); - }else if (policyConfigType.equalsIgnoreCase("Base")) { + }else if ("Base".equalsIgnoreCase(policyConfigType)) { newPolicy = new ConfigPolicy(policyData); - }else if (policyConfigType.equalsIgnoreCase("ClosedLoop_Fault")) { + }else if ("ClosedLoop_Fault".equalsIgnoreCase(policyConfigType)) { newPolicy = new ClosedLoopPolicy(policyData); - }else if (policyConfigType.equalsIgnoreCase("ClosedLoop_PM")) { + }else if ("ClosedLoop_PM".equalsIgnoreCase(policyConfigType)) { if(policyData.getApiflag() == null){ policyData.setServiceType(policyData.getServiceTypePolicyName().get("serviceTypePolicyName").toString()); ObjectMapper jsonMapper = new ObjectMapper(); @@ -301,10 +304,12 @@ public class PolicyCreation extends AbstractPolicyCreation{ policyData.setJsonBody(jsonBody); } newPolicy = new CreateClosedLoopPerformanceMetrics(policyData); - }else if (policyConfigType.equalsIgnoreCase("Micro Service")) { + }else if ("Micro Service".equalsIgnoreCase(policyConfigType)) { newPolicy = new MicroServiceConfigPolicy(policyData); + }else if ("Optimization".equalsIgnoreCase(policyConfigType)) { + newPolicy = new OptimizationConfigPolicy(policyData); } - }else if(policyType.equalsIgnoreCase("Action")) { + }else if("Action".equalsIgnoreCase(policyType)) { if(policyData.getApiflag() == null){ List<String> dynamicRuleAlgorithmLabels = new LinkedList<>(); List<String> dynamicRuleAlgorithmCombo = new LinkedList<>(); @@ -361,7 +366,7 @@ public class PolicyCreation extends AbstractPolicyCreation{ } } newPolicy = new ActionPolicy(policyData, commonClassDao); - } else if (policyType.equalsIgnoreCase("Decision")) { + } else if ("Decision".equalsIgnoreCase(policyType)) { if(policyData.getApiflag() == null){ Map<String, String> settingsMap = new HashMap<>(); Map<String, String> treatmentMap = new HashMap<>(); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/DictionaryService.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/DictionaryService.java index 00ae10fb6..cb03d44ec 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/DictionaryService.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/DictionaryService.java @@ -32,6 +32,7 @@ import org.onap.policy.pap.xacml.rest.controller.DescriptiveDictionaryController import org.onap.policy.pap.xacml.rest.controller.DictionaryController; import org.onap.policy.pap.xacml.rest.controller.FirewallDictionaryController; import org.onap.policy.pap.xacml.rest.controller.MicroServiceDictionaryController; +import org.onap.policy.pap.xacml.rest.controller.OptimizationDictionaryController; import org.onap.policy.pap.xacml.rest.controller.PolicyScopeDictionaryController; import org.onap.policy.pap.xacml.rest.controller.SafePolicyController; import org.springframework.stereotype.Service; @@ -236,6 +237,13 @@ public class DictionaryService { return result.getViewName(); } + public String saveOptimizationModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + OptimizationDictionaryController dictionary = new OptimizationDictionaryController(); + ModelAndView result = dictionary.saveOptimizationModelsDictionary(request, response); + return result.getViewName(); + } + public String savePSServiceDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); @@ -424,6 +432,11 @@ public class DictionaryService { dictionary.getMicroServiceModelsDictionaryEntityData(response); } + public void getOptimizationModelsDictionary(HttpServletResponse response){ + OptimizationDictionaryController dictionary = new OptimizationDictionaryController(); + dictionary.getOptimizationModelsDictionaryEntityData(response); + } + public void getPSServiceDictionary(HttpServletResponse response){ PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); dictionary.getPSServiceEntityData(response); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/ImportService.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/ImportService.java index c804f2b20..7382a77a1 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/ImportService.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/ImportService.java @@ -38,6 +38,7 @@ import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.pap.xacml.rest.components.CreateBRMSRuleTemplate; import org.onap.policy.pap.xacml.rest.components.CreateNewMicroServiceModel; +import org.onap.policy.pap.xacml.rest.components.CreateNewOptimizationModel; public class ImportService { private static final Logger logger = FlexLogger.getLogger(ImportService.class); @@ -50,6 +51,7 @@ public class ImportService { private static String successMessage = "success"; private static String invalidServiceName = "Invalid ServiceName"; private static final String REGEX = "[0-9a-zA-Z._ ]*"; + private static final String MISSING = "missing"; public void doImportMicroServicePut(HttpServletRequest request, HttpServletResponse response) { String importServiceCreation = request.getParameter("importService"); @@ -59,7 +61,7 @@ public class ImportService { if(serviceName == null || serviceName.isEmpty() || !serviceName.matches(REGEX)){ response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, "missing"); + response.addHeader(errorMsg, MISSING); response.addHeader(operation, importHeader); response.addHeader(service, invalidServiceName); return; @@ -78,7 +80,7 @@ public class ImportService { logger.error(e); PolicyLogger.error(errorMessage); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader(errorMsg, "missing"); + response.addHeader(errorMsg, MISSING); response.addHeader(operation, importHeader); response.addHeader(service, serviceName); } @@ -88,12 +90,16 @@ public class ImportService { else if(("MICROSERVICE").equals(importServiceCreation)){ CreateNewMicroServiceModel newMS = null; String randomID = UUID.randomUUID().toString(); + String type = ".xmi"; if ( fileName != null) { File extracDir = new File(extractDir); if (!extracDir.exists()){ extracDir.mkdirs(); } - if (fileName.contains(".xmi")){ + if (fileName.contains(".xmi") || fileName.contains(".yml")){ + if(fileName.contains(".yml")){ + type = ".yml"; + } // get the request content into a String String xmi = null; java.util.Scanner scanner; @@ -107,9 +113,9 @@ public class ImportService { PolicyLogger.error(errorMessage); return; } - PolicyLogger.info("XML request from API for import new Service"); + PolicyLogger.info("Request from API to import new Service"); try (Writer writer = new BufferedWriter(new OutputStreamWriter( - new FileOutputStream(extractDir + File.separator + randomID+".xmi"), "utf-8"))) { + new FileOutputStream(extractDir + File.separator + randomID+type), "utf-8"))) { writer.write(xmi); } catch (IOException e) { logger.error(e); @@ -138,13 +144,54 @@ public class ImportService { } } } + newMS = new CreateNewMicroServiceModel(fileName, serviceName, "API", version, randomID); - successMap = newMS.addValuesToNewModel(); + + successMap = newMS.addValuesToNewModel(type); + if (successMap.containsKey(successMessage)) { successMap.clear(); successMap = newMS.saveImportService(); } } + } else if(("OPTIMIZATION").equals(importServiceCreation)){ + CreateNewOptimizationModel newOOF = null; + String randomID = UUID.randomUUID().toString(); + if ( fileName != null) { + File extracDir = new File(extractDir); + if (!extracDir.exists()){ + extracDir.mkdirs(); + } + + String type = ".yml"; + + // get the request content into a String + String yml = null; + try (java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());){ + scanner.useDelimiter("\\A"); + yml = scanner.hasNext() ? scanner.next() : ""; + } catch (IOException e1) { + logger.error(e1); + PolicyLogger.error(errorMessage); + return; + } + PolicyLogger.info("Request from API to import new Optimization Service Model"); + try (Writer writer = new BufferedWriter(new OutputStreamWriter( + new FileOutputStream(extractDir + File.separator + randomID+type), "utf-8"))) { + writer.write(yml); + } catch (IOException e) { + logger.error(e); + PolicyLogger.error(errorMessage); + return; + } + + newOOF = new CreateNewOptimizationModel(fileName, serviceName, "API Import Service", version, randomID); + successMap = newOOF.addValuesToNewModel(); + if (successMap.containsKey(successMessage)) { + successMap.clear(); + successMap = newOOF.saveImportService(); + } + } } // return a response to the PAP @@ -166,7 +213,7 @@ public class ImportService { response.addHeader(service, serviceName); }else if (successMap.get(errorMsg).contains("MISSING")){ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader(errorMsg, "missing"); + response.addHeader(errorMsg, MISSING); response.addHeader(operation, importHeader); response.addHeader(service, serviceName); }else if (successMap.get(errorMsg).contains("VALIDATION")){ |