cd9a121ddb45c008bc93a3e2c6919c0b4d527b29
[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  * 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.onap.so.asdc.installer.bpmn;
22
23 import java.io.BufferedOutputStream;
24 import java.io.FileInputStream;
25 import java.io.FileOutputStream;
26 import java.io.IOException;
27 import java.net.URI;
28 import java.nio.file.Path;
29 import java.nio.file.Paths;
30 import java.util.Enumeration;
31 import java.util.zip.ZipEntry;
32 import java.util.zip.ZipFile;
33 import java.util.zip.ZipInputStream;
34
35 import org.apache.commons.io.IOUtils;
36 import org.apache.http.HttpEntity;
37 import org.apache.http.HttpResponse;
38 import org.apache.http.client.HttpClient;
39 import org.apache.http.client.config.RequestConfig;
40 import org.apache.http.client.methods.HttpPost;
41 import org.apache.http.entity.ContentType;
42 import org.apache.http.entity.mime.FormBodyPartBuilder;
43 import org.apache.http.entity.mime.MultipartEntityBuilder;
44 import org.apache.http.entity.mime.content.ByteArrayBody;
45 import org.apache.http.entity.mime.content.StringBody;
46 import org.apache.http.impl.client.HttpClientBuilder;
47 import org.onap.so.logger.MessageEnum;
48 import org.onap.so.logger.MsoLogger;
49 import org.springframework.beans.factory.annotation.Autowired;
50 import org.springframework.core.env.Environment;
51 import org.springframework.stereotype.Component;
52
53 @Component
54 public class BpmnInstaller {
55         protected static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.ASDC,BpmnInstaller.class);
56         private static final String BPMN_SUFFIX = ".bpmn";
57         private static final String CAMUNDA_URL = "mso.camundaURL";
58         private static final String CREATE_DEPLOYMENT_PATH = "/sobpmnengine/deployment/create";
59         
60         @Autowired
61         private Environment env;        
62         
63         public void installBpmn(String csarFilePath) {
64                 LOGGER.info("Deploying BPMN files from " + csarFilePath);               
65                 try {                   
66                         ZipInputStream csarFile = new ZipInputStream(new FileInputStream(Paths.get(csarFilePath).normalize().toString()));
67                         ZipEntry entry = csarFile.getNextEntry();               
68          
69                         while (entry != null) {                         
70                                 String name = entry.getName();
71                                 if (name.endsWith(BPMN_SUFFIX)) {
72                                         LOGGER.debug("Attempting to deploy BPMN file: " + name);
73                                         try {
74                                                 Path p = Paths.get(name);
75                                                 String fileName = p.getFileName().toString();
76                                                 extractBpmnFileFromCsar(csarFile, fileName);
77                                                 HttpResponse response = sendDeploymentRequest(fileName);
78                                                 LOGGER.debug("Response status line: " + response.getStatusLine());
79                                                 LOGGER.debug("Response entity: " + response.getEntity().toString());
80                                                 if (response.getStatusLine().getStatusCode() != 200) {
81                                                         LOGGER.debug("Failed deploying BPMN " + name);
82                                         LOGGER.error(MessageEnum.ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL,
83                                                                 name,
84                                                                 fileName,
85                                                                 "",
86                                                                 Integer.toString(response.getStatusLine().getStatusCode()), "", "", MsoLogger.ErrorCode.DataError, "ASDC BPMN deploy failed");  
87                                                 }                                               
88                                                 else {
89                                                         LOGGER.debug("Successfully deployed to Camunda: " + name);
90                                                 }
91                                         }
92                                         catch (Exception e) {
93                                                 LOGGER.debug("Exception :",e);
94                                 LOGGER.error(MessageEnum.ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL,
95                                                         name,
96                                                         "",
97                                                         "",
98                                                         e.getMessage(), "", "", MsoLogger.ErrorCode.DataError, "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,
107                                 csarFilePath,
108                                 "",
109                                 "",
110                                 ex.getMessage(), "", "", MsoLogger.ErrorCode.DataError, "ASDC reading CSAR with workflows failed");
111                 }
112                 return;
113         }       
114
115         public boolean containsWorkflows(String csarFilePath) {
116                 boolean workflowsInCsar = false;
117                 try {
118                         ZipFile zipFile = new ZipFile(csarFilePath);
119                         Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
120                         while (zipEntries.hasMoreElements()) {
121                                 String fileName = ((ZipEntry) zipEntries.nextElement()).getName();
122                                 if (fileName.endsWith(BPMN_SUFFIX)) {
123                                         workflowsInCsar = true;
124                                         break;
125                                 }                               
126                         }
127                 }
128                 catch (Exception e) {
129                         LOGGER.debug("Exception :",e);
130             LOGGER.error(MessageEnum.ASDC_ARTIFACT_CHECK_EXC,
131                                 csarFilePath,
132                                 "",
133                                 "",
134                                 e.getMessage(), "", "", MsoLogger.ErrorCode.DataError, "ASDC Unable to check CSAR entries"); 
135                 }
136                 return workflowsInCsar;
137         }
138         
139         protected HttpResponse sendDeploymentRequest(String bpmnFileName) throws Exception {
140                 HttpClient client = HttpClientBuilder.create().build(); 
141                 URI deploymentUri = new URI(this.env.getProperty(CAMUNDA_URL) + CREATE_DEPLOYMENT_PATH);
142                 HttpPost post = new HttpPost(deploymentUri);
143                 RequestConfig requestConfig =
144                                 RequestConfig.custom().setSocketTimeout(1000000).setConnectTimeout(1000).setConnectionRequestTimeout(1000).build();
145                 post.setConfig(requestConfig);        
146                 HttpEntity requestEntity = buildMimeMultipart(bpmnFileName);
147                 post.setEntity(requestEntity);
148                 return client.execute(post);
149         }
150         
151         protected HttpEntity buildMimeMultipart(String bpmnFileName) throws Exception {
152                 FileInputStream bpmnFileStream = new FileInputStream (Paths.get(System.getProperty("mso.config.path"),"ASDC", bpmnFileName).normalize().toString());
153
154                 byte[] bytesToSend = IOUtils.toByteArray(bpmnFileStream);
155                 HttpEntity requestEntity = MultipartEntityBuilder.create()
156                                 .addPart(FormBodyPartBuilder.create()
157                                                 .setName("deployment-name")
158                                                 .setBody(new StringBody("MSO Sample 1", ContentType.TEXT_PLAIN))
159                                                 .setField("Content-Disposition", String.format("form-data; name=\"%s\"", "deployment-name"))
160                                                 .build())
161                                 .addPart(FormBodyPartBuilder.create() 
162                                                 .setName("enable-duplicate-filtering")
163                                                 .setBody(new StringBody("false", ContentType.TEXT_PLAIN))
164                                                 .setField("Content-Disposition", String.format("form-data; name=\"%s\"", "enable-duplicate-filtering"))
165                                                 .build())
166                                 .addPart(FormBodyPartBuilder.create()
167                                                 .setName("deplpy-changed-only")
168                                                 .setBody(new StringBody("false", ContentType.TEXT_PLAIN))
169                                                 .setField("Content-Disposition", String.format("form-data; name=\"%s\"", "deploy-changed-only"))
170                                                 .build())
171                                 .addPart(FormBodyPartBuilder.create()
172                                                 .setName("deployment-source")  
173                                                 .setBody(new StringBody("local", ContentType.TEXT_PLAIN))
174                                                 .setField("Content-Disposition", String.format("form-data; name=\"%s\"", "deployment-source"))
175                                                 .build())
176                                 .addPart(FormBodyPartBuilder.create()
177                                                 .setName(bpmnFileName)
178                                                 .setBody(new ByteArrayBody(bytesToSend, ContentType.create("octet"), bpmnFileName))
179                                                 .setField("Content-Disposition", String.format("form-data; name=\"%s\"; filename=\"%s\"; size=%d", bpmnFileName, bpmnFileName, bytesToSend.length))
180                                                 .build())
181                                 .build();
182                 
183                 IOUtils.closeQuietly(bpmnFileStream);
184                  return requestEntity;
185         }
186         
187         /* protected void extractBpmnFileFromCsar(ZipInputStream zipIn, String fileName) throws IOException */
188         protected void extractBpmnFileFromCsar(ZipInputStream zipIn, String fileName)   {
189                 String filePath = Paths.get(System.getProperty("mso.config.path"), "ASDC", fileName).normalize().toString();
190                 /* BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath)); */
191                 try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath))){
192                 byte[] bytesIn = new byte[4096];
193                 int read = 0;
194                 while ((read = zipIn.read(bytesIn)) != -1) {
195                         outputStream.write(bytesIn, 0, read);
196                 }
197                 /* outputStream.close(); */
198                 } catch (IOException e) {
199               LOGGER.error("Unable to open file.", e);
200         }
201         }
202 }