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