2  * ============LICENSE_START=======================================================
 
   4  * ================================================================================
 
   5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 
   6  * ================================================================================
 
   7  * Licensed under the Apache License, Version 2.0 (the "License");
 
   8  * you may not use this file except in compliance with the License.
 
   9  * You may obtain a copy of the License at
 
  11  *      http://www.apache.org/licenses/LICENSE-2.0
 
  13  * Unless required by applicable law or agreed to in writing, software
 
  14  * distributed under the License is distributed on an "AS IS" BASIS,
 
  15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
  16  * See the License for the specific language governing permissions and
 
  17  * limitations under the License.
 
  18  * ============LICENSE_END=========================================================
 
  21 package org.onap.policy.pap.xacml.rest.components;
 
  23 import java.io.BufferedInputStream;
 
  24 import java.io.BufferedOutputStream;
 
  26 import java.io.FileOutputStream;
 
  27 import java.io.IOException;
 
  28 import java.util.ArrayList;
 
  29 import java.util.Arrays;
 
  30 import java.util.Enumeration;
 
  31 import java.util.HashMap;
 
  32 import java.util.List;
 
  34 import java.util.zip.ZipEntry;
 
  35 import java.util.zip.ZipFile;
 
  37 import org.apache.commons.io.FileUtils;
 
  38 import org.apache.commons.lang.StringUtils;
 
  39 import org.onap.policy.common.logging.eelf.MessageCodes;
 
  40 import org.onap.policy.common.logging.eelf.PolicyLogger;
 
  41 import org.onap.policy.common.logging.flexlogger.FlexLogger;
 
  42 import org.onap.policy.common.logging.flexlogger.Logger;
 
  43 import org.onap.policy.pap.xacml.rest.XACMLPapServlet;
 
  44 import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl;
 
  45 import org.onap.policy.rest.jpa.MicroServiceModels;
 
  46 import org.onap.policy.rest.jpa.UserInfo;
 
  47 import org.onap.policy.rest.util.MSAttributeObject;
 
  48 import org.onap.policy.rest.util.MSModelUtils;
 
  49 import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE;
 
  51 public class CreateNewMicroServiceModel {
 
  52         private static final Logger logger = FlexLogger.getLogger(CreateNewMicroServiceModel.class);
 
  53         private MicroServiceModels newModel = null;
 
  54         private HashMap<String,MSAttributeObject > classMap = new HashMap<>();
 
  57         MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName());
 
  59         public CreateNewMicroServiceModel(String fileName, String serviceName, String string, String version) {
 
  63         public CreateNewMicroServiceModel(String importFile, String  modelName, String description, String version, String randomID) {
 
  65                 this.newModel = new MicroServiceModels();
 
  66                 this.newModel.setVersion(version);
 
  67                 this.newModel.setModelName(modelName);
 
  68                 UserInfo userInfo = new UserInfo();
 
  69                 userInfo.setUserLoginId("API");
 
  70                 this.newModel.setUserCreatedBy(userInfo);
 
  71                 String cleanUpFile = null;
 
  73             HashMap<String, MSAttributeObject> tempMap = new HashMap<>();
 
  74             //Need to delete the file
 
  75             if (importFile.contains(".zip")){
 
  76                 extractFolder(randomID + ".zip");
 
  77                 File directory = new File("ExtractDir" + File.separator + randomID);
 
  78                 List<File> fileList = listModelFiles(directory.toString());
 
  79                 //get all the files from a director
 
  80                 for (File file : fileList){
 
  82                                     tempMap = utils.processEpackage(file.getAbsolutePath(), MODEL_TYPE.XMI);
 
  83                                     classMap.putAll(tempMap);
 
  86                 cleanUpFile = "ExtractDir" + File.separator + randomID + ".zip";
 
  88                                 FileUtils.deleteDirectory(new File("ExtractDir" + File.separator + randomID));
 
  89                                 FileUtils.deleteDirectory(new File(randomID));
 
  90                                 File deleteFile = new File(cleanUpFile); 
 
  91                                 FileUtils.forceDelete(deleteFile);
 
  92                         } catch (IOException e) {
 
  93                                 logger.error("Failed to unzip model file " + randomID, e);
 
  96                     tempMap = utils.processEpackage("ExtractDir" + File.separator + randomID+".xmi", MODEL_TYPE.XMI);
 
  97                     classMap.putAll(tempMap);
 
  98                     cleanUpFile = "ExtractDir" + File.separator + randomID+".xmi";
 
  99                     File deleteFile = new File(cleanUpFile); 
 
 104         private List<File> listModelFiles(String directoryName) {
 
 105                 File directory = new File(directoryName);
 
 106                 List<File> resultList = new ArrayList<>();
 
 107                 File[] fList = directory.listFiles();
 
 108                 for (File file : fList) {
 
 110                                 resultList.add(file);
 
 111                         } else if (file.isDirectory()) {
 
 112                                 resultList.addAll(listModelFiles(file.getAbsolutePath()));
 
 118         @SuppressWarnings("rawtypes")
 
 119         private void extractFolder(String zipFile) {
 
 121             File file = new File(zipFile);
 
 125                         zip = new ZipFile("ExtractDir" + File.separator +file);
 
 126                     String newPath =  zipFile.substring(0, zipFile.length() - 4);
 
 127                     new File(newPath).mkdir();
 
 128                     Enumeration zipFileEntries = zip.entries();
 
 130                     // Process each entry
 
 131                     while (zipFileEntries.hasMoreElements()){
 
 132                         // grab a zip file entry
 
 133                         ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
 
 134                         String currentEntry = entry.getName();
 
 135                         File destFile = new File("ExtractDir" + File.separator + newPath + File.separator + currentEntry);
 
 136                         File destinationParent = destFile.getParentFile();
 
 138                         destinationParent.mkdirs();
 
 140                         if (!entry.isDirectory()){
 
 141                             BufferedInputStream is = new BufferedInputStream(zip
 
 142                             .getInputStream(entry));
 
 145                             byte data[] = new byte[BUFFER];
 
 147                             FileOutputStream fos = new FileOutputStream(destFile);
 
 148                             BufferedOutputStream dest = new BufferedOutputStream(fos,
 
 151                             while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
 
 152                                 dest.write(data, 0, currentByte);
 
 159                         if (currentEntry.endsWith(".zip")){
 
 160                             extractFolder(destFile.getAbsolutePath());
 
 163             } catch (IOException e) {
 
 164                         logger.error("Failed to unzip model file " + zipFile + e);
 
 169                                 } catch (Exception e) {
 
 170                                         logger.error("Exception Occured while closing the zip file"+e);
 
 176         public Map<String, String> addValuesToNewModel() {
 
 178                 Map<String, String> successMap = new HashMap<>();
 
 179                 MSAttributeObject mainClass  = null;
 
 180                 ArrayList<String> dependency = null;
 
 181                 String subAttribute = null;
 
 183                 if (!classMap.containsKey(this.newModel.getModelName())){
 
 184                         logger.error("Model Provided does not contain the service name provided in request. Unable to import new model");
 
 185                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "AddValuesToNewModel", "Unable to pull out required values, file missing service name provided in request");
 
 186                         successMap.put("error", "MISSING");
 
 189                 mainClass = classMap.get(this.newModel.getModelName());
 
 190                 String dependTemp = StringUtils.replaceEach(mainClass.getDependency(), new String[]{"[", "]", " "}, new String[]{"", "", ""});
 
 191                 this.newModel.setDependency(dependTemp);
 
 192                 if (!this.newModel.getDependency().equals("")){
 
 193                         dependency = new ArrayList<String>(Arrays.asList(dependTemp.split(",")));       
 
 194                         dependency = utils.getFullDependencyList(dependency, classMap);
 
 195                         if (!dependency.isEmpty()){
 
 196                                 for (String element : dependency){
 
 197                                         MSAttributeObject temp = new MSAttributeObject();
 
 198                                         if (classMap.containsKey(element)){
 
 199                                                 temp = classMap.get(element);
 
 200                                                 mainClass.addAllRefAttribute(temp.getRefAttribute());
 
 201                                                 mainClass.addAllAttribute(temp.getAttribute());
 
 206                 subAttribute = utils.createSubAttributes(dependency, classMap, this.newModel.getModelName());
 
 208                 this.newModel.setSub_attributes(subAttribute);
 
 209                 this.newModel.setAttributes(mainClass.getAttribute().toString().replace("{", "").replace("}", ""));
 
 210                 this.newModel.setRef_attributes(mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""));
 
 211                 this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", ""));
 
 212         this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", ""));
 
 213                 successMap.put("success", "success");
 
 218         public Map<String, String> saveImportService(){
 
 219                 String modelName = this.newModel.getModelName();
 
 220                 String imported_by = "API";
 
 221                 String version = this.newModel.getVersion();
 
 222                 Map<String, String> successMap = new HashMap<>();
 
 223                 CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
 
 224                 List<Object> result = dbConnection.getDataById(MicroServiceModels.class, "modelName:version", modelName+":"+version);
 
 225                 if(result.isEmpty()){
 
 226                         MicroServiceModels model = new MicroServiceModels();
 
 227                         model.setModelName(modelName);
 
 228                         model.setVersion(version);
 
 229                         model.setAttributes(this.newModel.getAttributes());
 
 230                         model.setAnnotation(this.newModel.getAnnotation());
 
 231                         model.setDependency(this.newModel.getDependency());
 
 232                         model.setDescription(this.newModel.getDescription());
 
 233                         model.setEnumValues(this.newModel.getEnumValues());
 
 234                         model.setRef_attributes(this.newModel.getRef_attributes());
 
 235                         model.setSub_attributes(this.newModel.getSub_attributes());
 
 236                         UserInfo userInfo = new UserInfo();
 
 237                         userInfo.setUserLoginId(imported_by);
 
 238                         userInfo.setUserName(imported_by);
 
 239                         model.setUserCreatedBy(userInfo);
 
 240                         dbConnection.save(model);
 
 241                         successMap.put("success", "success");
 
 243                         successMap.put("DBError", "EXISTS");
 
 244                         logger.error("Import new service failed.  Service already exists");