2 * ============LICENSE_START=======================================================
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
23 package org.onap.so.asdc.installer.bpmn;
25 import java.io.BufferedOutputStream;
26 import java.io.FileInputStream;
27 import java.io.FileOutputStream;
28 import java.io.IOException;
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.commons.lang3.StringUtils;
38 import org.apache.http.HttpEntity;
39 import org.apache.http.HttpResponse;
40 import org.apache.http.client.HttpClient;
41 import org.apache.http.client.config.RequestConfig;
42 import org.apache.http.client.methods.HttpPost;
43 import org.apache.http.entity.ContentType;
44 import org.apache.http.entity.mime.FormBodyPartBuilder;
45 import org.apache.http.entity.mime.MultipartEntityBuilder;
46 import org.apache.http.entity.mime.content.ByteArrayBody;
47 import org.apache.http.entity.mime.content.StringBody;
48 import org.apache.http.impl.client.HttpClientBuilder;
49 import org.onap.so.asdc.client.ASDCConfiguration;
50 import org.onap.so.logger.ErrorCode;
51 import org.onap.so.logger.MessageEnum;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54 import org.springframework.beans.factory.annotation.Autowired;
55 import org.springframework.core.env.Environment;
56 import org.springframework.stereotype.Component;
59 public class BpmnInstaller {
60 protected static final Logger logger = LoggerFactory.getLogger(BpmnInstaller.class);
61 private static final String BPMN_SUFFIX = ".bpmn";
62 private static final String CAMUNDA_URL = "mso.camundaURL";
63 private static final String CREATE_DEPLOYMENT_PATH = "sobpmnengine/deployment/create";
66 private Environment env;
69 private ASDCConfiguration asdcConfig;
71 public void installBpmn(String csarFilePath) {
72 logger.info("Deploying BPMN files from {}", csarFilePath);
74 ZipInputStream csarFile =
75 new ZipInputStream(new FileInputStream(Paths.get(csarFilePath).normalize().toString()));
76 ZipEntry entry = csarFile.getNextEntry();
78 while (entry != null) {
79 String name = entry.getName();
80 if (name.endsWith(BPMN_SUFFIX)) {
81 logger.debug("Attempting to deploy BPMN file: {}", name);
83 Path p = Paths.get(name);
84 String fileName = p.getFileName().toString();
85 extractBpmnFileFromCsar(csarFile, fileName);
86 HttpResponse response = sendDeploymentRequest(fileName, "");
87 logger.debug("Response status line: {}", response.getStatusLine());
88 logger.debug("Response entity: {}", response.getEntity().toString());
89 if (response.getStatusLine().getStatusCode() != 200) {
90 logger.debug("Failed deploying BPMN {}", name);
91 logger.error("{} {} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL.toString(),
92 name, fileName, Integer.toString(response.getStatusLine().getStatusCode()),
93 ErrorCode.DataError.getValue(), "ASDC BPMN deploy failed");
95 logger.debug("Successfully deployed to Camunda: {}", name);
97 } catch (Exception e) {
98 logger.debug("Exception :", e);
99 logger.error("{} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL.toString(), name,
100 e.getMessage(), ErrorCode.DataError.getValue(), "ASDC BPMN deploy failed");
103 entry = csarFile.getNextEntry();
106 } catch (IOException ex) {
107 logger.debug("Exception :", ex);
108 logger.error("{} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL.toString(), csarFilePath,
109 ex.getMessage(), ErrorCode.DataError.getValue(), "ASDC reading CSAR with workflows failed");
114 public boolean containsWorkflows(String csarFilePath) {
115 boolean workflowsInCsar = false;
116 try (ZipFile zipFile = new ZipFile(csarFilePath)) {
117 Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
118 while (zipEntries.hasMoreElements()) {
119 String fileName = zipEntries.nextElement().getName();
120 if (fileName.endsWith(BPMN_SUFFIX)) {
121 workflowsInCsar = true;
125 } catch (Exception e) {
126 logger.debug("Exception :", e);
127 logger.error("{} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_CHECK_EXC.toString(), csarFilePath, e.getMessage(),
128 ErrorCode.DataError.getValue(), "ASDC Unable to check CSAR entries");
130 return workflowsInCsar;
133 protected HttpResponse sendDeploymentRequest(String bpmnFileName, String version) throws Exception {
134 HttpClient client = HttpClientBuilder.create().build();
135 URI deploymentUri = new URI(this.env.getProperty(CAMUNDA_URL) + CREATE_DEPLOYMENT_PATH);
136 HttpPost post = new HttpPost(deploymentUri);
137 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000000).setConnectTimeout(1000)
138 .setConnectionRequestTimeout(1000).build();
139 post.setConfig(requestConfig);
140 HttpEntity requestEntity = buildMimeMultipart(bpmnFileName, version);
141 post.setEntity(requestEntity);
142 return client.execute(post);
145 protected HttpEntity buildMimeMultipart(String bpmnFileName, String version) throws Exception {
146 FileInputStream bpmnFileStream = new FileInputStream(
147 Paths.get(getMsoConfigPath(), "ASDC", version, bpmnFileName).normalize().toString());
149 byte[] bytesToSend = IOUtils.toByteArray(bpmnFileStream);
150 HttpEntity requestEntity =
151 MultipartEntityBuilder.create()
152 .addPart(FormBodyPartBuilder.create().setName("deployment-name")
153 .setBody(new StringBody("MSO Sample 1", ContentType.TEXT_PLAIN))
154 .setField("Content-Disposition",
155 String.format("form-data; name=\"%s\"", "deployment-name"))
157 .addPart(FormBodyPartBuilder.create().setName("enable-duplicate-filtering")
158 .setBody(new StringBody("false", ContentType.TEXT_PLAIN))
159 .setField("Content-Disposition",
160 String.format("form-data; name=\"%s\"", "enable-duplicate-filtering"))
162 .addPart(FormBodyPartBuilder.create().setName("deplpy-changed-only")
163 .setBody(new StringBody("false", ContentType.TEXT_PLAIN))
164 .setField("Content-Disposition",
165 String.format("form-data; name=\"%s\"", "deploy-changed-only"))
167 .addPart(FormBodyPartBuilder.create().setName("deployment-source")
168 .setBody(new StringBody("local", ContentType.TEXT_PLAIN))
169 .setField("Content-Disposition",
170 String.format("form-data; name=\"%s\"", "deployment-source"))
173 FormBodyPartBuilder.create().setName(bpmnFileName)
174 .setBody(new ByteArrayBody(bytesToSend, ContentType.create("octet"),
176 .setField("Content-Disposition",
177 String.format("form-data; name=\"%s\"; filename=\"%s\"; size=%d",
178 bpmnFileName, bpmnFileName, bytesToSend.length))
182 IOUtils.closeQuietly(bpmnFileStream);
183 return requestEntity;
186 /* protected void extractBpmnFileFromCsar(ZipInputStream zipIn, String fileName) throws IOException */
187 protected void extractBpmnFileFromCsar(ZipInputStream zipIn, String fileName) {
188 String filePath = Paths.get(System.getProperty("mso.config.path"), "ASDC", fileName).normalize().toString();
189 /* BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath)); */
190 try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath))) {
191 byte[] bytesIn = new byte[4096];
193 while ((read = zipIn.read(bytesIn)) != -1) {
194 outputStream.write(bytesIn, 0, read);
196 /* outputStream.close(); */
197 } catch (IOException e) {
198 logger.error("Unable to open file.", e);
202 private String getMsoConfigPath() {
203 String msoConfigPath = System.getProperty("mso.config.path");
204 if (msoConfigPath == null) {
205 logger.info("Unable to find the system property mso.config.path, use the default configuration");
206 msoConfigPath = StringUtils.defaultString(asdcConfig.getPropertyOrNull("mso.config.defaultpath"));
208 logger.info("MSO config path is: {}", msoConfigPath);
209 return msoConfigPath;