[MSO-8] Update the maven dependency
[so.git] / mso-api-handlers / mso-api-handler-infra / src / main / java / org / openecomp / mso / apihandlerinfra / MsoRequest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * OPENECOMP - MSO
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
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
21 package org.openecomp.mso.apihandlerinfra;
22
23 import java.io.StringReader;
24 import java.io.StringWriter;
25 import java.io.IOException;
26 import java.sql.Timestamp;
27 import java.util.ArrayList;
28 import java.util.HashMap;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Map.Entry;
32 import java.util.StringTokenizer;
33
34 import javax.ws.rs.core.MultivaluedMap;
35 import javax.ws.rs.core.Response;
36 import javax.xml.bind.JAXBContext;
37 import javax.xml.bind.JAXBException;
38 import javax.xml.bind.Marshaller;
39 import javax.xml.transform.OutputKeys;
40 import javax.xml.transform.Transformer;
41 import javax.xml.transform.TransformerFactory;
42 import javax.xml.transform.dom.DOMSource;
43 import javax.xml.transform.stream.StreamResult;
44
45 import org.codehaus.jackson.JsonGenerationException;
46 import org.codehaus.jackson.map.JsonMappingException;
47 import org.codehaus.jackson.map.ObjectMapper;
48 import org.codehaus.jackson.map.annotate.JsonSerialize;
49 import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
50 import org.hibernate.Session;
51 import org.w3c.dom.Document;
52 import org.w3c.dom.Element;
53 import org.w3c.dom.Node;
54 import org.w3c.dom.NodeList;
55
56 import org.openecomp.mso.apihandler.common.ValidationException;
57 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.CloudConfiguration;
58 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.ModelInfo;
59 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.PolicyException;
60 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.RelatedInstance;
61 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.RelatedInstanceList;
62 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.RequestError;
63 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.RequestInfo;
64 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.RequestParameters;
65 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.ServiceException;
66 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.ServiceInstancesRequest;
67 import org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType;
68 import org.openecomp.mso.apihandlerinfra.vnfbeans.VnfInputs;
69 import org.openecomp.mso.apihandlerinfra.vnfbeans.VnfRequest;
70 import org.openecomp.mso.db.HibernateUtils;
71 import org.openecomp.mso.logger.MessageEnum;
72 import org.openecomp.mso.logger.MsoLogger;
73 import org.openecomp.mso.requestsdb.HibernateUtilsRequestsDb;
74 import org.openecomp.mso.requestsdb.InfraActiveRequests;
75 import org.openecomp.mso.requestsdb.RequestsDatabase;
76 import org.openecomp.mso.utils.UUIDChecker;
77
78 public class MsoRequest {
79
80     private String requestId;
81     private String requestXML;
82     private String requestJSON;
83     private String requestUri;
84     private VnfRequest vnfReq;
85     private RequestInfo requestInfo;
86     private ModelInfo modelInfo;
87     private CloudConfiguration cloudConfiguration ;
88     private VnfInputs vnfInputs;
89     private String vnfParams;
90     private Action action;
91     private String errorMessage;
92     private String errorCode;
93     private String httpResponse;
94     private String responseBody;
95     private RequestStatusType status;
96     private ServiceInstancesRequest sir;
97     private long startTime;
98     private long progress = Constants.PROGRESS_REQUEST_RECEIVED;
99     private String serviceInstanceType;
100     private String vnfType;
101     private String vfModuleType;
102     private String vfModuleModelName;
103     private String networkType;
104     private String asdcServiceModelVersion;
105     private String requestScope;
106     private int reqVersion;
107     private boolean aLaCarteFlag = false;
108
109     private static MsoLogger msoLogger = MsoLogger.getMsoLogger (MsoLogger.Catalog.APIH);
110     private static final String NOT_PROVIDED = "not provided";
111
112     protected HibernateUtils hibernateUtils = new HibernateUtilsRequestsDb ();
113
114     MsoRequest (String requestId) {
115         this.requestId = requestId;
116         this.startTime = System.currentTimeMillis();
117         MsoLogger.setLogContext (requestId, null);
118
119     }
120
121     MsoRequest () {
122
123         this.startTime = System.currentTimeMillis();
124         MsoLogger.setLogContext (requestId, null);
125
126     }
127
128
129     public Response buildServiceErrorResponse (int httpResponseCode,
130             MsoException exceptionType,
131             String text,
132             String messageId,
133             List<String> variables) {
134
135         this.errorCode = messageId;
136
137         if (text != null) {
138                 this.errorMessage = text;
139         }
140         else {
141                 this.errorMessage = "";
142         }
143         this.httpResponse = Integer.toString(httpResponseCode);
144         if(errorMessage.length() > 1999){
145             errorMessage = errorMessage.substring(0, 1999);
146         }
147
148         RequestError re = new RequestError();
149
150         if(exceptionType.name().equals("PolicyException")){
151
152                 PolicyException pe = new PolicyException();
153                 pe.setMessageId(messageId);
154                 pe.setText(text);
155                 if(variables != null){
156                         for(String variable: variables){
157                                 pe.getVariables().add(variable);
158                         }
159                 }
160                 re.setPolicyException(pe);
161
162         } else {
163
164                 ServiceException se = new ServiceException();
165                 se.setMessageId(messageId);
166                 se.setText(text);
167                 if(variables != null){
168                         if(variables != null){
169                                 for(String variable: variables){
170                                         se.getVariables().add(variable);
171                                 }
172                         }
173                 }
174                 re.setServiceException(se);
175         }
176
177         String requestErrorStr = null;
178
179         try{
180                 ObjectMapper mapper = new ObjectMapper();
181                 mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT);
182                 requestErrorStr = mapper.writeValueAsString(re);
183         }catch(Exception e){
184                 msoLogger.error (MessageEnum.APIH_VALIDATION_ERROR, "", "", MsoLogger.ErrorCode.DataError, "Exception in buildServiceErrorResponse writing exceptionType to string ", e);
185         }
186
187
188         return Response.status (httpResponseCode).entity(requestErrorStr).build ();
189
190     }
191
192     private int reqVersionToInt(String version){
193         if(version!=null){
194                 return Integer.parseInt(version.substring(1));
195         }else{
196                 return 0;
197         }
198     }
199
200     // Parse request JSON
201     void parse (ServiceInstancesRequest sir, HashMap<String,String> instanceIdMap, Action action, String version) throws ValidationException {
202
203         msoLogger.debug ("Validating the Service Instance request");
204
205         this.sir = sir;
206         this.action = action;
207         this.reqVersion = reqVersionToInt(version);
208         msoLogger.debug ("Incoming version is: " + version + " coverting to int: " + this.reqVersion);
209
210
211         try{
212                 ObjectMapper mapper = new ObjectMapper();
213                 //mapper.configure(Feature.WRAP_ROOT_VALUE, true);
214                 requestJSON = mapper.writeValueAsString(sir.getRequestDetails());
215
216         } catch(Exception e){
217                 throw new ValidationException ("Parse ServiceInstanceRequest to JSON string");
218         }
219
220         if(instanceIdMap != null){
221                 if(instanceIdMap.get("serviceInstanceId") != null){
222                         if (!UUIDChecker.isValidUUID (instanceIdMap.get ("serviceInstanceId"))) {
223                                 throw new ValidationException ("serviceInstanceId");
224                         }
225                         this.sir.setServiceInstanceId(instanceIdMap.get("serviceInstanceId"));
226                 }
227
228                 if(instanceIdMap.get("vnfInstanceId") != null){
229                         if (!UUIDChecker.isValidUUID (instanceIdMap.get ("vnfInstanceId"))) {
230                                 throw new ValidationException ("vnfInstanceId");
231                         }
232                         this.sir.setVnfInstanceId(instanceIdMap.get("vnfInstanceId"));
233                 }
234
235                 if(instanceIdMap.get("vfModuleInstanceId") != null){
236                         if (!UUIDChecker.isValidUUID (instanceIdMap.get ("vfModuleInstanceId"))) {
237                                 throw new ValidationException ("vfModuleInstanceId");
238                         }
239                         this.sir.setVfModuleInstanceId(instanceIdMap.get("vfModuleInstanceId"));
240                 }
241
242                 if(instanceIdMap.get("volumeGroupInstanceId") != null){
243                         if (!UUIDChecker.isValidUUID (instanceIdMap.get ("volumeGroupInstanceId"))) {
244                                 throw new ValidationException ("volumeGroupInstanceId");
245                         }
246                         this.sir.setVolumeGroupInstanceId(instanceIdMap.get("volumeGroupInstanceId"));
247                 }
248
249                 if(instanceIdMap.get("networkInstanceId") != null){
250                         if (!UUIDChecker.isValidUUID (instanceIdMap.get ("networkInstanceId"))) {
251                                 throw new ValidationException ("networkInstanceId");
252                         }
253                         this.sir.setNetworkInstanceId(instanceIdMap.get("networkInstanceId"));
254                 }
255         }
256
257         RequestParameters requestParameters = sir.getRequestDetails().getRequestParameters();
258         if(this.reqVersion >= 3){
259                 if(requestParameters!=null){
260                         this.aLaCarteFlag = sir.getRequestDetails().getRequestParameters().getALaCarte();
261                 }else{
262                         this.aLaCarteFlag = false;
263                 }
264         }else{
265                 this.aLaCarteFlag = true;
266         }
267
268                 if(requestParameters != null && (reqVersion < 3) && requestParameters.getAutoBuildVfModules()){
269                 throw new ValidationException("AutoBuildVfModule", version);
270         }
271
272         this.modelInfo = sir.getRequestDetails().getModelInfo();
273
274         if (this.modelInfo == null) {
275             throw new ValidationException ("model-info");
276         }
277
278         this.requestInfo = sir.getRequestDetails().getRequestInfo();
279
280         if (this.requestInfo == null) {
281             throw new ValidationException ("requestInfo");
282         }
283
284         if (modelInfo.getModelType () == null) {
285                 throw new ValidationException ("modelType");
286         }
287
288         this.requestScope = modelInfo.getModelType().name();
289
290         //is required for serviceInstance delete macro when aLaCarte=false (v3)
291         //create and updates except for network
292         if (empty (modelInfo.getModelInvariantId ()) && ((this.reqVersion >2 && !this.aLaCarteFlag && requestScope.equalsIgnoreCase(ModelType.service.name()) && action == Action.deleteInstance) ||
293                         !(requestScope.equalsIgnoreCase (ModelType.network.name ())) && (action == Action.createInstance || action == Action.updateInstance))) {
294                 throw new ValidationException ("modelInvariantId");
295         }
296
297         if (!empty (modelInfo.getModelInvariantId ()) && !UUIDChecker.isValidUUID (modelInfo.getModelInvariantId ())) {
298                 throw new ValidationException ("modelInvariantId format");
299         }
300
301         if (this.reqVersion <= 2 && empty (modelInfo.getModelName ()) && (action == Action.createInstance || action == Action.updateInstance || (action == Action.deleteInstance &&
302                         (requestScope.equalsIgnoreCase (ModelType.network.name ()) || requestScope.equalsIgnoreCase (ModelType.vfModule.name ()))))) {
303                 throw new ValidationException ("modelName");
304         }
305         if(this.reqVersion > 2 && empty (modelInfo.getModelName ()) && (action == Action.createInstance || action == Action.updateInstance || (action == Action.deleteInstance &&
306                         (requestScope.equalsIgnoreCase (ModelType.vfModule.name ()))))){
307                 throw new ValidationException ("modelName");
308         }
309
310         if (empty (modelInfo.getModelVersion ()) && ((this.reqVersion >2 && !this.aLaCarteFlag && requestScope.equalsIgnoreCase(ModelType.service.name()) && action == Action.deleteInstance) ||
311                         !(requestScope.equalsIgnoreCase (ModelType.network.name ())) && (action == Action.createInstance || action == Action.updateInstance))) {
312                 throw new ValidationException ("modelVersion");
313         }
314
315         if(requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action != Action.deleteInstance && empty (modelInfo.getModelCustomizationName ())) {
316                 if(this.reqVersion<=2){
317                         throw new ValidationException ("modelCustomizationName");
318                 } else if (!UUIDChecker.isValidUUID (modelInfo.getModelCustomizationId())) {
319                         throw new ValidationException ("modelCustomizationId or modelCustomizationName");
320                 }
321         }
322
323         if(this.reqVersion > 2 && (!UUIDChecker.isValidUUID (modelInfo.getModelCustomizationId())) && requestScope.equalsIgnoreCase (ModelType.network.name ())
324                         && (action == Action.updateInstance || action == Action.createInstance)){
325                 throw new ValidationException ("modelCustomizationId");
326         }
327
328         if(!empty(modelInfo.getModelNameVersionId())){
329                 modelInfo.setModelVersionId(modelInfo.getModelNameVersionId());
330         }
331         if(!empty(modelInfo.getModelVersionId())){
332                 modelInfo.setModelNameVersionId(modelInfo.getModelVersionId());
333         }
334
335         this.cloudConfiguration = sir.getRequestDetails ().getCloudConfiguration ();
336         if ( (((!this.aLaCarteFlag && requestScope.equalsIgnoreCase (ModelType.service.name ())) ||
337                         (!requestScope.equalsIgnoreCase (ModelType.service.name ())) && action != Action.updateInstance))
338                         && cloudConfiguration == null) {
339                 throw new ValidationException ("cloudConfiguration");
340         }
341
342         if (cloudConfiguration != null) {
343                 if (empty (cloudConfiguration.getLcpCloudRegionId ())) {
344                         throw new ValidationException ("lcpCloudRegionId");
345                 }
346                 if (empty (cloudConfiguration.getTenantId ())) {
347                         throw new ValidationException ("tenantId");
348                 }
349         }
350
351
352
353         if (requestScope.equalsIgnoreCase (ModelType.service.name ()) && action == Action.createInstance) {
354                 if (requestParameters == null) {
355                         throw new ValidationException ("requestParameters");
356                 }
357                 if (empty (requestParameters.getSubscriptionServiceType ())) {
358                         throw new ValidationException ("subscriptionServiceType");
359                 }
360         }
361
362         if(requestScope.equalsIgnoreCase(ModelType.service.name())){
363                 this.serviceInstanceType = modelInfo.getModelName();
364         }
365
366         if(requestScope.equalsIgnoreCase(ModelType.network.name())){
367                 this.networkType = modelInfo.getModelName();
368         }
369
370         // Verify instanceName existence and format except for macro serviceInstance
371         if (this.reqVersion < 3 && requestScope.equalsIgnoreCase (ModelType.service.name ()) && empty (requestInfo.getInstanceName ()) && action == Action.createInstance) {
372                 throw new ValidationException ("instanceName");
373         }
374
375         if (!empty (requestInfo.getInstanceName ())) {
376                 if (!requestInfo.getInstanceName ().matches (Constants.VALID_INSTANCE_NAME_FORMAT)) {
377                         throw new ValidationException ("instanceName format");
378                 }
379         }
380
381         if (empty (requestInfo.getProductFamilyId ()) && ((requestScope.equalsIgnoreCase (ModelType.vnf.name ()) && action == Action.createInstance) ||
382                         (requestScope.equalsIgnoreCase (ModelType.network.name ()) && (action == Action.createInstance || action == Action.updateInstance)))) {
383                 throw new ValidationException ("productFamilyId");
384         }
385
386         if (empty (requestInfo.getSource ())) {
387                 throw new ValidationException ("source");
388         }
389
390
391         RelatedInstanceList[] instanceList = sir.getRequestDetails().getRelatedInstanceList();
392
393         String serviceModelName = null;
394         String vnfModelName = null;
395         String asdcServiceModelVersion = null;
396         String volumeGroupId = null;
397         boolean isRelatedServiceInstancePresent = false;
398         boolean isRelatedVnfInstancePresent = false;
399
400         if (instanceList != null) {
401                 for(RelatedInstanceList relatedInstanceList : instanceList){
402                         RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
403
404                         if (relatedInstance.getModelInfo () == null) {
405                                 throw new ValidationException ("modelInfo in relatedInstance");
406                         }
407
408                         if (relatedInstance.getModelInfo ().getModelType () == null) {
409                                 throw new ValidationException ("modelType in relatedInstance");
410                         }
411
412
413                         if (!empty (relatedInstance.getInstanceName ())) {
414                         if (!relatedInstance.getInstanceName ().matches (Constants.VALID_INSTANCE_NAME_FORMAT)) {
415                                 throw new ValidationException ("instanceName format in relatedInstance");
416                         }
417                     }
418
419                         if (empty (relatedInstance.getInstanceId ())) {
420                                 throw new ValidationException ("instanceId in relatedInstance");
421                         }
422
423                         if (!UUIDChecker.isValidUUID (relatedInstance.getInstanceId ())) {
424                                 throw new ValidationException ("instanceId format in relatedInstance");
425                         }
426
427
428                         if (action != Action.deleteInstance) {
429
430                                 // ModelInvariantId is not required in volumeGroup relatedInstance
431                                 if(!(relatedInstance.getModelInfo ().getModelType ().equals(ModelType.volumeGroup)) &&
432                                         empty (relatedInstance.getModelInfo ().getModelInvariantId ())) {
433                                         throw new ValidationException ("modelInvariantId in relatedInstance");
434                                 }
435
436                                 if (!empty (relatedInstance.getModelInfo ().getModelInvariantId ()) &&
437                                                 !UUIDChecker.isValidUUID (relatedInstance.getModelInfo ().getModelInvariantId ())) {
438                                         throw new ValidationException ("modelInvariantId format in relatedInstance");
439                                 }
440
441                                 if (empty(relatedInstance.getModelInfo ().getModelName ()) &&
442                                                 !(relatedInstance.getModelInfo ().getModelType ().equals (ModelType.volumeGroup))) {
443                                         throw new ValidationException ("modelName in relatedInstance");
444                                 }
445
446                                 if (empty (relatedInstance.getModelInfo ().getModelVersion ())  &&
447                                                 !(relatedInstance.getModelInfo ().getModelType ().equals (ModelType.volumeGroup))) {
448                                         throw new ValidationException ("modelVersion in relatedInstance");
449                                 }
450                         }
451
452                         if (empty (relatedInstance.getModelInfo ().getModelCustomizationName ()) &&
453                                         relatedInstance.getModelInfo ().getModelType ().equals (ModelType.vnf)) {
454                                 throw new ValidationException ("modelCustomizationName in relatedInstance");
455                         }
456
457                         if(relatedInstance.getModelInfo().getModelType().equals(ModelType.service)) {
458                                 isRelatedServiceInstancePresent = true;
459                                 if (!relatedInstance.getInstanceId ().equals (this.sir.getServiceInstanceId ())) {
460                                         throw new ValidationException ("serviceInstanceId matching the serviceInstanceId in request URI");
461                                 }
462                                 serviceModelName = relatedInstance.getModelInfo ().getModelName ();
463                                 asdcServiceModelVersion = relatedInstance.getModelInfo().getModelVersion ();
464                         }
465                         else if(relatedInstance.getModelInfo().getModelType().equals(ModelType.vnf)) {
466                                 isRelatedVnfInstancePresent = true;
467                                 if (!relatedInstance.getInstanceId ().equals (this.sir.getVnfInstanceId ())) {
468                                         throw new ValidationException ("vnfInstanceId matching the vnfInstanceId in request URI");
469                                 }
470                                 vnfModelName = relatedInstance.getModelInfo().getModelCustomizationName();
471                         }
472                         else if(relatedInstance.getModelInfo().getModelType().equals(ModelType.volumeGroup)) {
473                                 volumeGroupId = relatedInstance.getInstanceId ();
474                         }
475                 }
476
477
478                 if(requestScope.equalsIgnoreCase (ModelType.volumeGroup.name ())) {
479                         if (!isRelatedServiceInstancePresent) {
480                                 throw new ValidationException ("related service instance for volumeGroup request");
481                         }
482                         if (!isRelatedVnfInstancePresent) {
483                                 throw new ValidationException ("related vnf instance for volumeGroup request");
484                         }
485                         this.serviceInstanceType = serviceModelName;
486                         this.vnfType = serviceModelName + "/" + vnfModelName;
487                         this.asdcServiceModelVersion = asdcServiceModelVersion;
488                 }
489                 else if(requestScope.equalsIgnoreCase(ModelType.vfModule.name ())) {
490                         if (!isRelatedServiceInstancePresent) {
491                                 throw new ValidationException ("related service instance for vfModule request");
492                         }
493                         if (!isRelatedVnfInstancePresent) {
494                                 throw new ValidationException ("related vnf instance for vfModule request");
495                         }
496                         String vfModuleModelName = modelInfo.getModelName ();
497                         this.vfModuleModelName = vfModuleModelName;
498                         this.serviceInstanceType = serviceModelName;
499                         this.vnfType = serviceModelName + "/" + vnfModelName;
500                         this.asdcServiceModelVersion = asdcServiceModelVersion;
501                         this.vfModuleType = vnfType + "::" + vfModuleModelName;
502                         this.sir.setVolumeGroupInstanceId (volumeGroupId);
503                 }
504                 else if (requestScope.equalsIgnoreCase (ModelType.vnf.name ())) {
505                         if (!isRelatedServiceInstancePresent) {
506                                 throw new ValidationException ("related service instance for vnf request");
507                         }
508                         this.vnfType = serviceModelName + "/" + sir.getRequestDetails().getModelInfo().getModelCustomizationName();
509                }
510         }
511         else if ((( requestScope.equalsIgnoreCase(ModelType.vnf.name ()) || requestScope.equalsIgnoreCase(ModelType.volumeGroup.name ()) || requestScope.equalsIgnoreCase(ModelType.vfModule.name ()) ) && (action == Action.createInstance)) ||
512                         (this.reqVersion > 2 && (requestScope.equalsIgnoreCase(ModelType.volumeGroup.name ()) || requestScope.equalsIgnoreCase(ModelType.vfModule.name ())) && action == Action.updateInstance)){
513                  msoLogger.debug ("related instance exception");
514                 throw new ValidationException ("related instances");
515         }
516
517     }
518
519     void parseOrchestration (ServiceInstancesRequest sir) throws ValidationException {
520
521         msoLogger.debug ("Validating the Orchestration request");
522
523         this.sir = sir;
524
525         try{
526                 ObjectMapper mapper = new ObjectMapper();
527                 //mapper.configure(Feature.WRAP_ROOT_VALUE, true);
528                 requestJSON = mapper.writeValueAsString(sir.getRequestDetails());
529
530         } catch(Exception e){
531                 throw new ValidationException ("Parse ServiceInstanceRequest to JSON string", e);
532         }
533
534         this.requestInfo = sir.getRequestDetails().getRequestInfo();
535
536         if (this.requestInfo == null) {
537             throw new ValidationException ("requestInfo");
538         }
539
540         if (empty (requestInfo.getSource ())) {
541                 throw new ValidationException ("source");
542         }
543         if (empty (requestInfo.getRequestorId ())) {
544                 throw new ValidationException ("requestorId");
545         }
546     }
547
548     public Map<String, List<String>> getOrchestrationFilters (MultivaluedMap<String, String> queryParams) throws ValidationException {
549
550         String queryParam = null;
551         Map<String, List<String>> orchestrationFilterParams = new HashMap<String, List<String>>();
552
553
554         for (Entry<String,List<String>> entry : queryParams.entrySet()) {
555             queryParam = entry.getKey();
556
557             try{
558                   if(queryParam.equalsIgnoreCase("filter")){
559
560                           StringTokenizer st = new StringTokenizer(entry.getValue().get(0), ":");
561
562                           int counter=0;
563                           String mapKey=null;
564                           List<String> orchestrationList = new ArrayList<String>();
565                           while (st.hasMoreElements()) {
566                                   if(counter == 0){
567                                           mapKey = st.nextElement() + "";
568                                   } else{
569                                           orchestrationList.add(st.nextElement() + "");
570                                   }
571                                  counter++;
572                           }
573                         orchestrationFilterParams.put(mapKey, orchestrationList);
574                   }
575
576             }catch(Exception e){
577                 //msoLogger.error (MessageEnum.APIH_VALIDATION_ERROR, e);
578                 throw new ValidationException ("QueryParam ServiceInfo", e);
579
580                 }
581
582         }
583
584
585         return orchestrationFilterParams;
586   }
587
588     public void createRequestRecord (Status status, Action action) {
589
590         Session session = null;
591         try {
592
593             session = hibernateUtils.getSessionFactory ().openSession ();
594             session.beginTransaction ();
595
596             if (null == sir) {
597                 sir = new ServiceInstancesRequest ();
598             }
599
600             InfraActiveRequests aq = new InfraActiveRequests ();
601             aq.setRequestId (requestId);
602
603             aq.setRequestAction(action.name());
604             aq.setAction(action.name());
605
606             Timestamp startTimeStamp = new Timestamp (System.currentTimeMillis());
607
608             aq.setStartTime (startTimeStamp);
609
610             if (requestInfo != null) {
611
612                 if(requestInfo.getSource() != null){
613                         aq.setSource(requestInfo.getSource());
614                 }
615                 if(requestInfo.getCallbackUrl() != null){
616                         aq.setCallBackUrl(requestInfo.getCallbackUrl());
617                 }
618                 if(requestInfo.getCorrelator() != null){
619                         aq.setCorrelator(requestInfo.getCorrelator());
620                 }
621
622                 if(requestInfo.getRequestorId() != null) {
623                         aq.setRequestorId(requestInfo.getRequestorId());
624                 }
625             }
626
627             if (modelInfo != null) {
628                 aq.setRequestScope(requestScope);
629             }
630
631             if (cloudConfiguration != null) {
632                 if(cloudConfiguration.getLcpCloudRegionId() != null) {
633                         aq.setAicCloudRegion(cloudConfiguration.getLcpCloudRegionId());
634                 }
635
636                 if(cloudConfiguration.getTenantId() != null) {
637                         aq.setTenantId(cloudConfiguration.getTenantId());
638                 }
639
640             }
641
642             if(sir.getServiceInstanceId() != null){
643                 aq.setServiceInstanceId(sir.getServiceInstanceId());
644             }
645
646             if(sir.getVnfInstanceId() != null){
647                 aq.setVnfId(sir.getVnfInstanceId());
648             }
649
650
651             if(ModelType.service.name().equalsIgnoreCase(requestScope)){
652                 if(requestInfo.getInstanceName() != null){
653                         aq.setServiceInstanceName(requestInfo.getInstanceName());
654                 }
655             }
656
657             if(ModelType.network.name().equalsIgnoreCase(requestScope)){
658                 aq.setNetworkName(requestInfo.getInstanceName());
659                 aq.setNetworkType(networkType);
660                 aq.setNetworkId(sir.getNetworkInstanceId());
661             }
662
663             if(ModelType.volumeGroup.name().equalsIgnoreCase(requestScope)){
664                 aq.setVolumeGroupId(sir.getVolumeGroupInstanceId());
665                 aq.setVolumeGroupName(requestInfo.getInstanceName());
666                 aq.setVnfType(vnfType);
667
668             }
669
670             if(ModelType.vfModule.name().equalsIgnoreCase(requestScope)){
671                 aq.setVfModuleName(requestInfo.getInstanceName());
672                 aq.setVfModuleModelName(modelInfo.getModelName());
673                 aq.setVfModuleId(sir.getVfModuleInstanceId());
674                 aq.setVolumeGroupId(sir.getVolumeGroupInstanceId());
675                 aq.setVnfType(vnfType);
676
677             }
678
679             if(ModelType.vnf.name().equalsIgnoreCase(requestScope)){
680                 aq.setVnfName(requestInfo.getInstanceName());
681                                 if (null != sir.getRequestDetails()) {
682                                         RelatedInstanceList[] instanceList = sir.getRequestDetails().getRelatedInstanceList();
683
684                                         if (instanceList != null) {
685
686                                                 for(RelatedInstanceList relatedInstanceList : instanceList){
687
688                                                         RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
689                                                         if(relatedInstance.getModelInfo().getModelType().equals(ModelType.service)){
690                                                                 aq.setVnfType(vnfType);
691                                                         }
692                                                 }
693                                         }
694                                 }
695             }
696
697             aq.setRequestBody (this.requestJSON);
698
699             aq.setRequestStatus (status.toString ());
700             aq.setLastModifiedBy (Constants.MODIFIED_BY_APIHANDLER);
701
702             if ((status == Status.FAILED) || (status == Status.COMPLETE)) {
703                 aq.setStatusMessage (this.errorMessage);
704                 aq.setResponseBody (this.responseBody);
705                 aq.setProgress(new Long(100));
706
707                 Timestamp endTimeStamp = new Timestamp (System.currentTimeMillis());
708                 aq.setEndTime (endTimeStamp);
709             }
710
711             msoLogger.debug ("About to insert a record");
712
713             session.save (aq);
714             session.getTransaction ().commit ();
715             session.close ();
716         } catch (Exception e) {
717                 msoLogger.error (MessageEnum.APIH_DB_INSERT_EXC, "", "", MsoLogger.ErrorCode.DataError, "Exception when creation record request", e);
718             if (session != null) {
719                 session.close ();
720             }
721             if (!status.equals (Status.FAILED)) {
722                 throw e;
723             }
724         }
725     }
726
727     public void updateFinalStatus (Status status) {
728         int result = 0;
729         try {
730             result = RequestsDatabase.updateInfraFinalStatus (requestId,
731                                                               status.toString (),
732                                                               this.errorMessage,
733                                                               this.progress,
734                                                               this.responseBody,
735                                                               Constants.MODIFIED_BY_APIHANDLER);
736         } catch (Exception e) {
737                 msoLogger.error(MessageEnum.APIH_DB_UPDATE_EXC, e.getMessage(), "", "", MsoLogger.ErrorCode.DataError, "Exception when updating record in DB");
738             msoLogger.debug ("Exception: ", e);
739         }
740     }
741
742     public Response buildResponse (int httpResponseCode, String errorCode, InfraActiveRequests inProgress) {
743         return buildResponseWithError (httpResponseCode, errorCode, inProgress, null);
744     }
745
746     public Response buildResponseWithError (int httpResponseCode,
747                                             String errorCode,
748                                             InfraActiveRequests inProgress,
749                                             String errorString) {
750
751
752
753         // Log the failed request into the MSO Requests database
754
755         return Response.status (httpResponseCode).entity (null).build ();
756
757     }
758
759     public Response buildResponseFailedValidation (int httpResponseCode, String exceptionMessage) {
760
761
762
763         return Response.status (httpResponseCode).entity (null).build ();
764     }
765
766     public String getRequestUri () {
767         return requestUri;
768     }
769
770     public void setRequestUri (String requestUri) {
771         this.requestUri = requestUri;
772     }
773
774     public VnfInputs getVnfInputs () {
775         return vnfInputs;
776     }
777
778     public RequestInfo getRequestInfo () {
779         return requestInfo;
780     }
781
782     public String getResponseBody () {
783         return responseBody;
784     }
785
786     public void setResponseBody (String responseBody) {
787         this.responseBody = responseBody;
788     }
789
790     public String getHttpResponse () {
791         return httpResponse;
792     }
793
794     public void setHttpResponse (String httpResponse) {
795         this.httpResponse = httpResponse;
796     }
797
798     public String getRequestId () {
799         return requestId;
800     }
801
802     public String getRequestXML () {
803         return requestXML;
804     }
805
806     public void setRequestXML (String requestXML) {
807         this.requestXML = requestXML;
808     }
809
810     public RequestStatusType getStatus () {
811         return status;
812     }
813
814     public String getServiceType () {
815         if (this.vnfInputs.getServiceType () != null)
816                 return this.vnfInputs.getServiceType ();
817         if (this.vnfInputs.getServiceId () != null)
818                 return this.vnfInputs.getServiceId ();
819         return null;
820     }
821
822     public void setStatus (RequestStatusType status) {
823         this.status = status;
824         switch (status) {
825         case FAILED:
826         case COMPLETE:
827                 this.progress = Constants.PROGRESS_REQUEST_COMPLETED;
828                 break;
829         case IN_PROGRESS:
830                 this.progress = Constants.PROGRESS_REQUEST_IN_PROGRESS;
831                 break;
832         }
833     }
834
835     public ModelInfo getModelInfo() {
836         return modelInfo;
837     }
838
839     public ServiceInstancesRequest getServiceInstancesRequest() {
840         return sir;
841     }
842
843     public String getServiceInstanceType () {
844         return serviceInstanceType;
845     }
846
847     public String getNetworkType () {
848         return networkType;
849     }
850
851     public String getVnfType () {
852         return vnfType;
853     }
854
855     public String getVfModuleModelName () {
856         return vfModuleModelName;
857     }
858
859     public String getVfModuleType () {
860         return vfModuleType;
861     }
862
863     public String getAsdcServiceModelVersion () {
864         return asdcServiceModelVersion;
865     }
866
867     public static String domToStr (Document doc) {
868         if (doc == null) {
869             return null;
870         }
871
872         try {
873             StringWriter sw = new StringWriter ();
874             StreamResult sr = new StreamResult (sw);
875             TransformerFactory tf = TransformerFactory.newInstance ();
876             Transformer t = tf.newTransformer ();
877             t.setOutputProperty (OutputKeys.STANDALONE, "yes");
878             NodeList nl = doc.getDocumentElement ().getChildNodes ();
879             DOMSource source = null;
880             for (int x = 0; x < nl.getLength (); x++) {
881                 Node e = nl.item (x);
882                 if (e instanceof Element) {
883                     source = new DOMSource (e);
884                     break;
885                 }
886             }
887             if (source != null) {
888                 t.transform (source, sr);
889
890                 String s = sw.toString ();
891                 return s;
892             }
893
894             return null;
895
896         } catch (Exception e) {
897             msoLogger.error (MessageEnum.APIH_DOM2STR_ERROR, "", "", MsoLogger.ErrorCode.DataError, "Exception in domToStr", e);
898         }
899         return null;
900     }
901
902     public void addBPMNSpecificInputs(String personaModelId, String personaModelVersion, Boolean isBaseVfModule,
903                         String vnfPersonaModelId, String vnfPersonaModelVersion) {
904         vnfInputs.setPersonaModelId(personaModelId);
905         vnfInputs.setPersonaModelVersion(personaModelVersion);
906         vnfInputs.setIsBaseVfModule(isBaseVfModule);
907         vnfInputs.setVnfPersonaModelId(vnfPersonaModelId);
908         vnfInputs.setVnfPersonaModelVersion(vnfPersonaModelVersion);
909
910         this.vnfReq.setVnfInputs(vnfInputs);
911
912           StringWriter stringWriter = new StringWriter ();
913           try {
914               JAXBContext jaxbContext = JAXBContext.newInstance (VnfRequest.class);
915               Marshaller jaxbMarshaller = jaxbContext.createMarshaller ();
916
917               // output pretty printed
918               jaxbMarshaller.setProperty (Marshaller.JAXB_FORMATTED_OUTPUT, true);
919
920               jaxbMarshaller.marshal (this.vnfReq, stringWriter);
921
922           } catch (JAXBException e) {
923               msoLogger.debug ("Exception: ", e);
924           }
925
926           this.requestXML = stringWriter.toString ();
927           msoLogger.debug("REQUEST XML to BPEL: " + this.requestXML);
928
929
930     }
931
932     private static boolean empty(String s) {
933           return (s == null || s.trim().isEmpty());
934     }
935
936     public String getRequestJSON() throws JsonGenerationException, JsonMappingException, IOException {
937         ObjectMapper mapper = new ObjectMapper();
938         mapper.setSerializationInclusion(Inclusion.NON_NULL);
939         //mapper.configure(Feature.WRAP_ROOT_VALUE, true);
940         msoLogger.debug ("building sir from object " + sir);
941         requestJSON = mapper.writeValueAsString(sir);
942         return requestJSON;
943     }
944
945         public boolean getALaCarteFlag() {
946                 return aLaCarteFlag;
947         }
948
949         public void setaLaCarteFlag(boolean aLaCarteFlag) {
950                 this.aLaCarteFlag = aLaCarteFlag;
951         }
952
953         public int getReqVersion() {
954                 return reqVersion;
955         }
956
957         public void setReqVersion(int reqVersion) {
958                 this.reqVersion = reqVersion;
959         }
960 }