Removed MsoLogger class
[so.git] / asdc-controller / src / main / java / org / onap / so / asdc / installer / bpmn / BpmnInstaller.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.so.asdc.installer.bpmn;
24
25 import java.io.BufferedOutputStream;
26 import java.io.FileInputStream;
27 import java.io.FileOutputStream;
28 import java.io.IOException;
29 import java.net.URI;
30 import java.nio.file.Path;
31 import java.nio.file.Paths;
32 import java.util.Enumeration;
33 import java.util.zip.ZipEntry;
34 import java.util.zip.ZipFile;
35 import java.util.zip.ZipInputStream;
36 import org.apache.commons.io.IOUtils;
37 import org.apache.http.HttpEntity;
38 import org.apache.http.HttpResponse;
39 import org.apache.http.client.HttpClient;
40 import org.apache.http.client.config.RequestConfig;
41 import org.apache.http.client.methods.HttpPost;
42 import org.apache.http.entity.ContentType;
43 import org.apache.http.entity.mime.FormBodyPartBuilder;
44 import org.apache.http.entity.mime.MultipartEntityBuilder;
45 import org.apache.http.entity.mime.content.ByteArrayBody;
46 import org.apache.http.entity.mime.content.StringBody;
47 import org.apache.http.impl.client.HttpClientBuilder;
48 import org.onap.so.logger.ErrorCode;
49 import org.onap.so.logger.MessageEnum;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52 import org.springframework.beans.factory.annotation.Autowired;
53 import org.springframework.core.env.Environment;
54 import org.springframework.stereotype.Component;
55
56 @Component
57 public class BpmnInstaller {
58         protected static final Logger logger = LoggerFactory.getLogger(BpmnInstaller.class);
59         private static final String BPMN_SUFFIX = ".bpmn";
60         private static final String CAMUNDA_URL = "mso.camundaURL";
61         private static final String CREATE_DEPLOYMENT_PATH = "/sobpmnengine/deployment/create";
62         
63         @Autowired
64         private Environment env;        
65         
66         public void installBpmn(String csarFilePath) {
67                 logger.info("Deploying BPMN files from {}", csarFilePath);
68                 try {                   
69                         ZipInputStream csarFile = new ZipInputStream(new FileInputStream(Paths.get(csarFilePath).normalize().toString()));
70                         ZipEntry entry = csarFile.getNextEntry();               
71          
72                         while (entry != null) {                         
73                                 String name = entry.getName();
74                                 if (name.endsWith(BPMN_SUFFIX)) {
75                                         logger.debug("Attempting to deploy BPMN file: {}", name);
76                                         try {
77                                                 Path p = Paths.get(name);
78                                                 String fileName = p.getFileName().toString();
79                                                 extractBpmnFileFromCsar(csarFile, fileName);
80                                                 HttpResponse response = sendDeploymentRequest(fileName);
81                                                 logger.debug("Response status line: {}", response.getStatusLine());
82                                                 logger.debug("Response entity: {}", response.getEntity().toString());
83                                                 if (response.getStatusLine().getStatusCode() != 200) {
84                                                         logger.debug("Failed deploying BPMN {}", name);
85                                                         logger
86                                                                 .error("{} {} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL.toString(), name, fileName,
87                                                                         Integer.toString(response.getStatusLine().getStatusCode()), ErrorCode.DataError.getValue(),
88                                                                         "ASDC BPMN deploy failed");
89                                                 }                                               
90                                                 else {
91                                                         logger.debug("Successfully deployed to Camunda: {}", name);
92                                                 }
93                                         }
94                                         catch (Exception e) {
95                                                 logger.debug("Exception :", e);
96                                                 logger
97                                                         .error("{} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL.toString(), name, e.getMessage(),
98                                                                 ErrorCode.DataError.getValue(), "ASDC BPMN deploy failed");
99                                         }                                                       
100                                 }
101                                 entry = csarFile.getNextEntry();
102                 }
103                         csarFile.close();
104                 } catch (IOException ex) {
105                         logger.debug("Exception :", ex);
106                         logger.error("{} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL.toString(), csarFilePath,
107                                 ex.getMessage(), ErrorCode.DataError.getValue(), "ASDC reading CSAR with workflows failed");
108                 }
109                 return;
110         }
111
112     public boolean containsWorkflows(String csarFilePath) {
113         boolean workflowsInCsar = false;
114         try (ZipFile zipFile = new ZipFile(csarFilePath)) {
115             Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
116             while (zipEntries.hasMoreElements()) {
117                 String fileName = zipEntries.nextElement().getName();
118                 if (fileName.endsWith(BPMN_SUFFIX)) {
119                     workflowsInCsar = true;
120                     break;
121                 }
122             }
123         } catch (Exception e) {
124                                         logger.debug("Exception :", e);
125                                         logger.error("{} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_CHECK_EXC.toString(), csarFilePath, e.getMessage(),
126                                                 ErrorCode.DataError.getValue(), "ASDC Unable to check CSAR entries");
127                                 }
128         return workflowsInCsar;
129     }
130
131         protected HttpResponse sendDeploymentRequest(String bpmnFileName) throws Exception {
132                 HttpClient client = HttpClientBuilder.create().build(); 
133                 URI deploymentUri = new URI(this.env.getProperty(CAMUNDA_URL) + CREATE_DEPLOYMENT_PATH);
134                 HttpPost post = new HttpPost(deploymentUri);
135                 RequestConfig requestConfig =
136                                 RequestConfig.custom().setSocketTimeout(1000000).setConnectTimeout(1000).setConnectionRequestTimeout(1000).build();
137                 post.setConfig(requestConfig);        
138                 HttpEntity requestEntity = buildMimeMultipart(bpmnFileName);
139                 post.setEntity(requestEntity);
140                 return client.execute(post);
141         }
142         
143         protected HttpEntity buildMimeMultipart(String bpmnFileName) throws Exception {
144                 FileInputStream bpmnFileStream = new FileInputStream (Paths.get(System.getProperty("mso.config.path"),"ASDC", bpmnFileName).normalize().toString());
145
146                 byte[] bytesToSend = IOUtils.toByteArray(bpmnFileStream);
147                 HttpEntity requestEntity = MultipartEntityBuilder.create()
148                                 .addPart(FormBodyPartBuilder.create()
149                                                 .setName("deployment-name")
150                                                 .setBody(new StringBody("MSO Sample 1", ContentType.TEXT_PLAIN))
151                                                 .setField("Content-Disposition", String.format("form-data; name=\"%s\"", "deployment-name"))
152                                                 .build())
153                                 .addPart(FormBodyPartBuilder.create() 
154                                                 .setName("enable-duplicate-filtering")
155                                                 .setBody(new StringBody("false", ContentType.TEXT_PLAIN))
156                                                 .setField("Content-Disposition", String.format("form-data; name=\"%s\"", "enable-duplicate-filtering"))
157                                                 .build())
158                                 .addPart(FormBodyPartBuilder.create()
159                                                 .setName("deplpy-changed-only")
160                                                 .setBody(new StringBody("false", ContentType.TEXT_PLAIN))
161                                                 .setField("Content-Disposition", String.format("form-data; name=\"%s\"", "deploy-changed-only"))
162                                                 .build())
163                                 .addPart(FormBodyPartBuilder.create()
164                                                 .setName("deployment-source")  
165                                                 .setBody(new StringBody("local", ContentType.TEXT_PLAIN))
166                                                 .setField("Content-Disposition", String.format("form-data; name=\"%s\"", "deployment-source"))
167                                                 .build())
168                                 .addPart(FormBodyPartBuilder.create()
169                                                 .setName(bpmnFileName)
170                                                 .setBody(new ByteArrayBody(bytesToSend, ContentType.create("octet"), bpmnFileName))
171                                                 .setField("Content-Disposition", String.format("form-data; name=\"%s\"; filename=\"%s\"; size=%d", bpmnFileName, bpmnFileName, bytesToSend.length))
172                                                 .build())
173                                 .build();
174                 
175                 IOUtils.closeQuietly(bpmnFileStream);
176                  return requestEntity;
177         }
178         
179         /* protected void extractBpmnFileFromCsar(ZipInputStream zipIn, String fileName) throws IOException */
180         protected void extractBpmnFileFromCsar(ZipInputStream zipIn, String fileName)   {
181                 String filePath = Paths.get(System.getProperty("mso.config.path"), "ASDC", fileName).normalize().toString();
182                 /* BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath)); */
183                 try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath))){
184                 byte[] bytesIn = new byte[4096];
185                 int read = 0;
186                 while ((read = zipIn.read(bytesIn)) != -1) {
187                         outputStream.write(bytesIn, 0, read);
188                 }
189                 /* outputStream.close(); */
190                 } catch (IOException e) {
191               logger.error("Unable to open file.", e);
192         }
193         }
194 }