089c368d184ad3033569f48e4054217e482bbfa4
[vfc/nfvo/catalog.git] /
1 /**
2  * Copyright 2016 [ZTE] and others.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.openo.commontosca.catalog.model.plan.wso2;
18
19 import java.io.BufferedInputStream;
20 import java.io.File;
21 import java.io.FileInputStream;
22 import java.io.FileNotFoundException;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.util.Map;
26 import java.util.regex.Matcher;
27 import java.util.regex.Pattern;
28 import java.util.zip.ZipEntry;
29 import java.util.zip.ZipFile;
30 import java.util.zip.ZipInputStream;
31
32 import lombok.AllArgsConstructor;
33 import lombok.Data;
34 import lombok.NoArgsConstructor;
35
36 import org.apache.http.HttpEntity;
37 import org.apache.http.entity.ContentType;
38 import org.apache.http.entity.mime.MultipartEntityBuilder;
39 import org.glassfish.jersey.client.ClientConfig;
40 import org.openo.commontosca.catalog.common.Config;
41 import org.openo.commontosca.catalog.db.exception.CatalogResourceException;
42 import org.openo.commontosca.catalog.model.plan.wso2.entity.DeletePackageResponse;
43 import org.openo.commontosca.catalog.model.plan.wso2.entity.DeployPackageResponse;
44 import org.openo.commontosca.catalog.model.plan.wso2.entity.StartProcessRequest;
45 import org.openo.commontosca.catalog.model.plan.wso2.entity.StartProcessResponse;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 import com.eclipsesource.jaxrs.consumer.ConsumerFactory;
50 import com.google.gson.Gson;
51
52
53
54 public class Wso2ServiceConsumer {
55   public static final String WSO2_APP_URL = "/openoapi/wso2bpel/v1/package";
56   private static final Logger LOGGER = LoggerFactory.getLogger(Wso2ServiceConsumer.class);
57   
58   /**
59    * deploy package.
60    * @param zipFileLocation zip file location
61    * @param planFilePath plan file path
62    * @return DeployPackageResponse
63    * @throws CatalogResourceException e1
64    */
65   public static DeployPackageResponse deployPackage(String zipFileLocation, String planFilePath)
66       throws CatalogResourceException {
67     IpPort ipPort = getIpPort(Config.getConfigration().getMsbServerAddr());
68     if (ipPort == null) {
69       throw new CatalogResourceException("getMsbServerAddr failed.");
70     }
71     InputStream ins = null;
72     try {
73       ins = getInputStream(zipFileLocation, planFilePath);
74       RestResponse res = RestfulClient.post(
75           ipPort.getIp(), ipPort.getPort(), WSO2_APP_URL,
76           buildRequest(ins, planFilePath));
77
78       if (res.getStatusCode() == null || res.getResult() == null) {
79         throw new CatalogResourceException(
80             "Deploy Package return null. Response = " + res);
81       }
82       
83       if (200 == res.getStatusCode() || 201 == res.getStatusCode()) {
84         DeployPackageResponse response =
85             new Gson().fromJson(res.getResult(), DeployPackageResponse.class);
86         if (response.isSuccess()) {
87           return response;
88         }
89       }
90
91       throw new CatalogResourceException(
92           "Deploy Package return fail. Response = " + res.getResult());
93     } catch (FileNotFoundException e1) {
94       throw new CatalogResourceException("Deploy Package failed.", e1);
95     } finally {
96       if (ins != null) {
97         try {
98           ins.close();
99         } catch (IOException e1) {
100           LOGGER.error("inputStream close failed !");
101         }
102       }
103     }
104   }
105
106   @Data
107   @NoArgsConstructor
108   @AllArgsConstructor
109   public static class IpPort {
110     private String ip;
111     private int port;
112   }
113   
114   private static IpPort getIpPort(String addr) {
115     Pattern p = Pattern.compile("//(.*?):(.*)");
116     Matcher m = p.matcher(addr);
117     while(m.find()){
118       return new IpPort(m.group(1), Integer.valueOf(m.group(2)));
119     }
120     return null;
121   }
122
123   private static HttpEntity buildRequest(InputStream inputStream, String filePath)
124       throws FileNotFoundException {
125     MultipartEntityBuilder builder = MultipartEntityBuilder.create();
126     builder.seContentType(ContentType.MULTIPART_FORM_DATA);
127     builder.addBinaryBody("file", inputStream, ContentType.APPLICATION_OCTET_STREAM,
128         new File(filePath).getName());
129     return builder.build();
130   }
131
132   @SuppressWarnings("resource")
133   private static InputStream getInputStream(String zipFileLocation, String planFilePath)
134       throws CatalogResourceException {
135     ZipInputStream zin = null;
136     try {
137       InputStream in = new BufferedInputStream(new FileInputStream(zipFileLocation));
138       zin = new ZipInputStream(in);
139       ZipEntry ze;
140       while ((ze = zin.getNextEntry()) != null) {
141         if (planFilePath.equals(ze.getName())) {
142           ZipFile zf = new ZipFile(zipFileLocation);
143           return zf.getInputStream(ze);
144         }
145       }
146     } catch (IOException e1) {
147       throw new CatalogResourceException("Get InputStream failed. planFilePath = " + planFilePath,
148           e1);
149     } finally {
150       closeStream(zin);
151     }
152
153     throw new CatalogResourceException("Get InputStream failed. planFilePath = " + planFilePath);
154   }
155
156   private static void closeStream(ZipInputStream zin) {
157
158     if (zin != null) {
159       try {
160         zin.closeEntry();
161       } catch (IOException e1) {
162         LOGGER.error("zip inputStream close failed !");
163       }
164     }
165   }
166
167   /**
168    * delet package.
169    * @param packageName package to delete according packageName
170    * @return DeletePackageResponse
171    * @throws CatalogResourceException e1
172    */
173   public static DeletePackageResponse deletePackage(String packageName)
174       throws CatalogResourceException {
175     try {
176       ClientConfig config = new ClientConfig();
177       Iwso2RestService wso2Proxy = ConsumerFactory.createConsumer(
178           Config.getConfigration().getMsbServerAddr(), config, Iwso2RestService.class);
179       DeletePackageResponse response = wso2Proxy.deletePackage(packageName);
180       if (response.isSuccess()) {
181         return response;
182       }
183       throw new CatalogResourceException(response.getException());
184     } catch (Exception e1) {
185       throw new CatalogResourceException(
186           "Call Delete Package api failed. packageName = " + packageName, e1);
187     }
188   }
189
190
191   /**
192    * start process.
193    * @param processId process id
194    * @param params params
195    * @return StartProcessResponse
196    * @throws CatalogResourceException e1
197    */
198   public static StartProcessResponse startProcess(String processId, Map<String, Object> params)
199       throws CatalogResourceException {
200     try {
201       ClientConfig config = new ClientConfig();
202       Iwso2RestService wso2Proxy = ConsumerFactory.createConsumer(
203           Config.getConfigration().getMsbServerAddr(), config, Iwso2RestService.class);
204       StartProcessResponse response =
205           wso2Proxy.startProcess(new StartProcessRequest(processId, params));
206       if (response.isSuccess()) {
207         return response;
208       }
209       throw new CatalogResourceException(response.getException());
210     } catch (Exception e1) {
211       throw new CatalogResourceException("Call Start Process api failed.", e1);
212     }
213   }
214
215 }