9899c348eee09d228af452eef452a70d9900d1f3
[vfc/nfvo/driver/vnfm/gvnfm.git] / juju / juju-vnfmadapter / Juju-vnfmadapterService / service / src / main / java / org / openo / nfvo / jujuvnfmadapter / common / EntityUtils.java
1 /*
2  * Copyright 2016 Huawei Technologies Co., Ltd.
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.nfvo.jujuvnfmadapter.common;
18
19 import java.io.File;
20 import java.io.InputStream;
21 import java.lang.reflect.Field;
22 import java.util.ArrayList;
23 import java.util.List;
24 import java.util.concurrent.TimeoutException;
25
26 import org.apache.commons.lang3.StringUtils;
27 import org.openo.nfvo.jujuvnfmadapter.service.constant.Constant;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30
31 import net.sf.json.JSONObject;
32
33 /**
34  * <br/>
35  * <p>
36  * </p>
37  * 
38  * @author
39  * @version NFVO 0.5 Aug 30, 2016
40  */
41 public class EntityUtils {
42
43     private static final Logger LOG = LoggerFactory.getLogger(EntityUtils.class);
44
45     public static final String RESULT_CODE_KEY = "retCode";
46
47     public static final String MSG_KEY = "msg";
48
49     public static final String DATA_KEY = "data";
50
51     public static final String STATUS = "status";
52
53     /**
54      * Constructor<br/>
55      * <p>
56      * </p>
57      */
58     private EntityUtils() {
59         // Empty Constructor
60     }
61
62     /**
63      * <br>
64      * 
65      * @param jsonObject
66      * @param clazz
67      * @return T
68      * @throws Exception
69      */
70     @SuppressWarnings("unchecked")
71     public static <T> T toEntity(JSONObject jsonObject, Class<?> clazz) throws Exception { // NOSONAR
72         T instance = (T)clazz.newInstance();
73         Field[] fields = clazz.getDeclaredFields();
74         for(int i = 0; i < fields.length; i++) {
75             fields[i].setAccessible(true);
76             fields[i].set(instance, jsonObject.get(fields[i].getName()));
77         }
78         return instance;
79     }
80
81     /**
82      * format the obj to str style as json format.
83      * <br/>
84      * 
85      * @param obj
86      * @param clazz
87      * @return
88      * @since NFVO 0.5
89      */
90     public static String toString(Object obj, Class<?> clazz) {
91         JSONObject jsonObj = new JSONObject();
92         try {
93             Field[] fields = clazz.getDeclaredFields();
94             for(int i = 0; i < fields.length; i++) {
95                 fields[i].setAccessible(true);
96                 jsonObj.put(fields[i].getName(), obj != null ? fields[i].get(obj) : "");
97             }
98         } catch(Exception e) {
99             LOG.error("to string error:", e);
100         }
101         return jsonObj.toString();
102     }
103
104     /**
105      * <br>
106      * <p>
107      * </p>
108      * 
109      * @author
110      */
111     public static class ExeRes {
112
113         public static final int SUCCESS = 0;
114
115         public static final int FAILURE = -1;
116
117         private int code;
118
119         private String body;
120
121         /**
122          * @return Returns the code.
123          */
124         public int getCode() {
125             return code;
126         }
127
128         /**
129          * @param code The code to set.
130          */
131         public void setCode(int code) {
132             this.code = code;
133         }
134
135         /**
136          * @return Returns the body.
137          */
138         public String getBody() {
139             return body;
140         }
141
142         /**
143          * @param body The body to set.
144          */
145         public void setBody(String body) {
146             this.body = body;
147         }
148
149         @Override
150         public String toString() {
151             try {
152                 return EntityUtils.toString(this, this.getClass());
153             } catch(Exception e) {
154                 LOG.error("to string error:", e);
155                 return "code:" + this.getCode() + ",body:" + this.getBody();
156             }
157         }
158
159     }
160
161     /**
162      * <br>
163      * 
164      * @param command
165      * @return String
166      */
167     public static String formatCommand(List<String> command) {
168         StringBuilder builder = new StringBuilder();
169         if(command != null) {
170             for(String cmd : command) {
171                 builder.append(cmd).append(" "); // NOSONAR
172             }
173         }
174         return builder.toString();
175
176     }
177
178     /**
179      * <br>
180      * 
181      * @param dir
182      * @param command
183      * @return
184      */
185     public static ExeRes execute(String dir, String... command) {
186         List<String> commands = new ArrayList<>(command.length);
187         for(String arg : command) {
188             commands.add(arg);
189         }
190         return execute(dir, commands);
191
192     }
193
194     /**
195      * execute local command
196      * <br/>
197      * 
198      * @param dir the command path
199      * @param command
200      * @return response msg
201      * @since NFVO 0.5
202      */
203     public static ExeRes execute(String dir, List<String> command) {
204         ExeRes er = new ExeRes();
205         StringBuilder sb = new StringBuilder();
206         try {
207             if(SwitchController.isDebugModel()) {
208                 String resContent = new String(FileUtils.readFile(new File(JujuConfigUtil.getValue("juju_cmd_res_file")), "UTF-8"));
209                 er.setBody(resContent);
210                 return er;
211             }
212             ProcessBuilder pb = new ProcessBuilder(command);
213             if(StringUtils.isNotBlank(dir)) {
214                 pb.directory(new File(dir));
215             }
216             pb.redirectErrorStream(true);
217             Process p = pb.start();
218
219             // wait the process result
220             buildProcessResult(er, p);
221
222             InputStream in = p.getInputStream();
223             byte[] buffer = new byte[1024];
224             int length;
225             while((length = in.read(buffer)) > 0) {
226                 sb.append(new String(buffer, 0, length));
227             }
228             in.close();
229             er.setBody(sb.toString());
230         } catch(Exception e) {
231             er.setCode(ExeRes.FAILURE);
232             er.setBody(e.getMessage());
233             LOG.error("execute the command failed:{}", command, e);
234         }
235         return er;
236     }
237
238     /**
239      * <br/>
240      * 
241      * @param er
242      * @param p
243      * @throws TimeoutException
244      * @throws InterruptedException
245      * @since NFVO 0.5
246      */
247     private static void buildProcessResult(ExeRes er, Process p) throws TimeoutException, InterruptedException {
248         Worker worker = new Worker(p);
249         worker.start();
250         try {
251             worker.join(Constant.PROCESS_WAIT_MILLIS);
252             if(worker.exitValue != null) {
253                 int exit = worker.exitValue;
254                 if(exit != 0) {
255                     er.setCode(ExeRes.FAILURE);
256                     LOG.warn("the process exit non-normal");
257                 } else {
258                     er.setCode(ExeRes.SUCCESS);
259                 }
260             } else {
261                 er.setCode(ExeRes.FAILURE);
262                 LOG.warn("the process execute timeout.");
263                 throw new TimeoutException();
264             }
265         } catch(InterruptedException e) {
266             worker.interrupt();
267             Thread.currentThread().interrupt();
268             throw e;
269         }
270     }
271
272     private static class Worker extends Thread {
273
274         private final Process process;
275
276         private Integer exitValue;
277
278         private Worker(Process process) {
279             this.process = process;
280         }
281
282         /**
283          * <br/>
284          * 
285          * @since NFVO 0.5
286          */
287         @Override
288         public void run() {
289             try {
290                 exitValue = process.waitFor();
291             } catch(InterruptedException e) {
292                 return;
293             }
294         }
295
296     }
297 }