Update css file name in conf.py
[policy/engine.git] / ONAP-PDP-REST / src / main / java / org / onap / policy / pdp / rest / api / services / PolicyEngineImportService.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-PDP-REST
4  * ================================================================================
5  * Copyright (C) 2017-2019 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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20 package org.onap.policy.pdp.rest.api.services;
21
22 import java.io.BufferedInputStream;
23 import java.io.File;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.util.UUID;
27
28 import org.onap.policy.api.ImportParameters;
29 import org.onap.policy.api.PolicyException;
30 import org.onap.policy.api.ImportParameters.IMPORT_TYPE;
31 import org.onap.policy.common.logging.flexlogger.FlexLogger;
32 import org.onap.policy.common.logging.flexlogger.Logger;
33 import org.onap.policy.utils.PolicyUtils;
34 import org.onap.policy.xacml.api.XACMLErrorConstants;
35 import org.springframework.http.HttpStatus;
36 import org.springframework.web.multipart.MultipartFile;
37
38 public class PolicyEngineImportService {
39     private static Logger LOGGER = FlexLogger.getLogger(PolicyEngineImportService.class.getName());
40     
41     private String importResponse = null;
42     private HttpStatus status = HttpStatus.BAD_REQUEST;
43     private String message = null;
44     private ImportParameters importParameters = null;
45     private MultipartFile file = null;
46
47     public PolicyEngineImportService(String importParametersJson,
48             MultipartFile file,
49             String requestID) {
50         try {
51             this.importParameters = PolicyUtils.jsonStringToObject(importParametersJson, ImportParameters.class);
52         } catch (Exception e) {
53             importResponse = XACMLErrorConstants.ERROR_DATA_ISSUE + e;
54             status = HttpStatus.BAD_REQUEST;
55             // This needs to stop here in case if there a issue here. Avoiding Null pointer exceptions. 
56             return; 
57         }
58         this.file = file;
59         if(importParameters.getRequestID()==null){
60             UUID requestUUID = null;
61             if (requestID != null && !requestID.isEmpty()) {
62                 try {
63                     requestUUID = UUID.fromString(requestID);
64                 } catch (IllegalArgumentException e) {
65                     requestUUID = UUID.randomUUID();
66                     LOGGER.info("Generated Random UUID: " + requestUUID.toString(), e);
67                 }
68             }else{
69                 requestUUID = UUID.randomUUID();
70                 LOGGER.info("Generated Random UUID: " + requestUUID.toString());
71             }
72             this.importParameters.setRequestID(requestUUID);
73         }
74         try{
75             run();
76             specialCheck();
77         }catch(PolicyException e){
78             importResponse = XACMLErrorConstants.ERROR_DATA_ISSUE + e;
79             status = HttpStatus.BAD_REQUEST;
80         }
81         
82         // Save the imported file
83         if (!file.isEmpty() && status.equals(HttpStatus.OK) ) {
84             String filePath = null;
85             try {
86                  String uploadsDir = System.getProperty("msToscaModel.home");
87                  if(uploadsDir != null) {
88                      if(! new File(uploadsDir).exists()){
89                          new File(uploadsDir).mkdir();
90                      }
91                      String orgName = file.getOriginalFilename();
92                      filePath = uploadsDir + orgName;
93                      File dest = new File(filePath);
94                      file.transferTo(dest);
95                  }
96              }catch(Exception e){
97                  LOGGER.error("Operation: policyEngineImport : " + e.getMessage() + ". " + filePath + " is not a valid file path.");
98              } 
99          }      
100     }
101
102     private void specialCheck() {
103         if(importResponse==null || importResponse.contains("PE200")){
104             status = HttpStatus.INTERNAL_SERVER_ERROR;
105         }else if(importResponse.contains("BAD REQUEST") || importResponse.contains("PE300")){
106             status = HttpStatus.BAD_REQUEST;
107         }
108     }
109
110     private void run() throws PolicyException{
111         // Check Validation. 
112         if(!getValidation()){
113             LOGGER.error(message);
114             throw new PolicyException(message);
115         }
116         // Get Result. 
117         try{
118             status = HttpStatus.OK;
119             importResponse = processResult();
120         }catch (Exception e){
121             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
122             status = HttpStatus.BAD_REQUEST;
123             throw new PolicyException(e);
124         }
125     }
126
127     private String processResult() throws PolicyException{
128         String response = null;
129         InputStream targetStream = null;
130         String fileName = file.getOriginalFilename();
131         switch (importParameters.getServiceType()){
132                 case MICROSERVICE:
133                 case OPTIMIZATION:
134                         if (fileName.endsWith(".yml") || fileName.endsWith(".xmi") ||  fileName.endsWith(".zip")){
135                     try {
136                         targetStream = new BufferedInputStream(file.getInputStream());
137                     } catch (IOException e) {
138                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in reading in the file provided";
139                         LOGGER.error(response  + e);
140                         return response;
141                     }
142                 }else{
143                     response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect File Type Given. Please use a file of type .xmi or .zip.";
144                     LOGGER.error(response);     
145                     return response;
146                 }
147                         break;
148                 case BRMSPARAM:
149                         if (fileName.endsWith(".drl")){
150                     try {
151                         targetStream = new BufferedInputStream(file.getInputStream());
152                     } catch (IOException e) {
153                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in reading in the file provided";
154                         LOGGER.error(response  + e);
155                         return response;
156                     }
157                 }else{
158                     response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect File Type Given. Please use a file of type .drl";
159                     LOGGER.error(response);     
160                     return response;
161                 }
162                         break;
163                 default:
164                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect ServiceType Given. ";
165                         LOGGER.error(response);     
166                         return response;
167         }
168         String[] parameters = new String[] {"importService=" + importParameters.getServiceType(), "serviceName=" 
169                 + importParameters.getServiceName(), "fileName=" + fileName, "version=" + importParameters.getVersion(), "description=" + importParameters.getDescription()};
170         PAPServices papServices = new PAPServices();
171         response =  (String) papServices.callPAP(targetStream, parameters, importParameters.getRequestID(), "importMS");
172         return response;
173     }
174
175     private boolean getValidation() {
176         if(importParameters==null){
177             message = XACMLErrorConstants.ERROR_DATA_ISSUE + " no Import Parameters given. ";
178             return false;
179         }
180         if(importParameters.getServiceName()==null || importParameters.getServiceName().trim().isEmpty()){
181             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing service name value.";
182             return false;
183         }
184         if(importParameters.getServiceType()==null || importParameters.getServiceType().toString().trim().isEmpty()){
185             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing service Type value.";
186             return false;
187         }
188         if((IMPORT_TYPE.MICROSERVICE.equals(importParameters.getServiceType()) || IMPORT_TYPE.OPTIMIZATION.equals(importParameters.getServiceType()))
189                         && (importParameters.getVersion()==null || importParameters.getVersion().trim().isEmpty())){
190             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing version value.";
191             return false;
192         }
193         if(file==null || file.isEmpty()){
194             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing File.";
195             return false;
196         }
197         return true;
198     }
199
200     public String getResult() {
201         return importResponse;
202     }
203
204     public HttpStatus getResponseCode() {
205         return status;
206     }
207
208 }