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