Code Smells in jujuvnfmadapter utils
[vfc/nfvo/driver/vnfm/gvnfm.git] / juju / juju-vnfmadapter / Juju-vnfmadapterService / service / src / main / java / org / onap / vfc / nfvo / vnfm / gvnfm / jujuvnfmadapter / common / LocalComandUtils.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.onap.vfc.nfvo.vnfm.gvnfm.jujuvnfmadapter.common;
18
19 import java.io.File;
20 import java.io.InputStream;
21 import java.util.ArrayList;
22 import java.util.List;
23 import java.util.concurrent.TimeoutException;
24
25 import org.apache.commons.lang3.StringUtils;
26 import org.onap.vfc.nfvo.vnfm.gvnfm.jujuvnfmadapter.service.constant.Constant;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29
30 /**
31  * For execute local command
32  * (support control overtime)
33  * <br/>
34  * <p>
35  * </p>
36  * 
37  * @author quanzhong@huawei.com
38  * @version NFVO 0.5 Sep 19, 2016
39  */
40 public class LocalComandUtils {
41     private static final Logger log = LoggerFactory.getLogger(LocalComandUtils.class);
42
43     private LocalComandUtils(){
44         
45     }
46
47     /**
48      * <br>
49      * 
50      * @param command
51      * @return String
52      */
53     public static String formatCommand(List<String> command) {
54         StringBuilder builder = new StringBuilder();
55         if(command != null) {
56             for(String cmd : command) {
57                 builder.append(cmd).append(" "); // NOSONAR
58             }
59         }
60         return builder.toString();
61
62     }
63
64     /**
65      * <br>
66      * 
67      * @param dir
68      * @param command
69      * @return
70      */
71     public static ExeRes execute(String dir, String... command) {
72         List<String> commands = new ArrayList<>(command.length);
73         for(String arg : command) {
74             commands.add(arg);
75         }
76         return execute(dir, commands);
77
78     }
79
80     /**
81      * execute local command
82      * <br/>
83      * 
84      * @param dir the command path
85      * @param command
86      * @param timeout  millis
87      * @return response msg
88      * @since NFVO 0.5
89      */
90     public static ExeRes execute(String dir, List<String> command,long timeout) {
91         ExeRes er = new ExeRes();
92         StringBuilder sb = new StringBuilder();
93         try {
94             if(SwitchController.isDebugModel()) {
95                 command.set(0, "juju.bat");
96             }
97             ProcessBuilder pb = new ProcessBuilder(command);
98             if(StringUtils.isNotBlank(dir)) {
99                 pb.directory(new File(dir));
100             }
101             pb.redirectErrorStream(true);
102             Process p = pb.start();
103
104             // wait the process result
105             buildProcessResult(er, p, timeout);
106
107             InputStream in = p.getInputStream();
108             byte[] buffer = new byte[1024];
109             int length;
110             while((length = in.read(buffer)) > 0) {
111                 sb.append(new String(buffer, 0, length));
112             }
113             in.close();
114             er.setBody(sb.toString());
115         } catch(Exception e) {
116             er.setCode(ExeRes.FAILURE);
117             er.setBody(e.getMessage());
118             log.error("execute the command failed:{}", command, e);
119         }
120         return er;
121     }
122     
123     /**
124      * execute local command
125      * <br/>
126      * 
127      * @param dir the command path
128      * @param command
129      * @return response msg
130      * @since NFVO 0.5
131      */
132     public static ExeRes execute(String dir, List<String> command) {  
133         return execute(dir,command,Constant.PROCESS_WAIT_MILLIS);
134     }
135
136     /**
137      * <br/>
138      * 
139      * @param er
140      * @param p
141      * @param timeout millis
142      * @throws TimeoutException
143      * @throws InterruptedException
144      * @since NFVO 0.5
145      */
146     private static void buildProcessResult(ExeRes er, Process p,long timeout) throws TimeoutException, InterruptedException {
147         Worker worker = new Worker(p);
148         worker.start();
149         try {
150             worker.join(timeout);
151             if(worker.exitValue != null) {
152                 int exit = worker.exitValue;
153                 if(exit != 0) {
154                     er.setCode(ExeRes.FAILURE);
155                     log.warn("the process exit non-normal");
156                 } else {
157                     er.setCode(ExeRes.SUCCESS);
158                 }
159             } else {
160                 er.setCode(ExeRes.FAILURE);
161                 log.warn("the process execute timeout.");
162                 throw new TimeoutException();
163             }
164         } catch(InterruptedException e) {
165             worker.interrupt();
166             Thread.currentThread().interrupt();
167             throw e;
168         }
169     }
170
171     /**
172      * 
173      * <br/>
174      * <p>
175      * </p>
176      * 
177      * @author          quanzhong@huawei.com
178      * @version     NFVO 0.5  Sep 19, 2016
179      */
180     private static class Worker extends Thread {
181
182         private final Process process;
183
184         private Integer exitValue;
185
186         private Worker(Process process) {
187             this.process = process;
188         }
189
190         /**
191          * <br/>
192          * 
193          * @since NFVO 0.5
194          */
195         @Override
196         public void run() {
197             try {
198                 exitValue = process.waitFor();
199             } catch(InterruptedException e) {
200                 return;
201             }
202         }
203
204     }
205
206     /**
207      * <br>
208      * <p>
209      * </p>
210      * 
211      * @author
212      */
213     public static class ExeRes {
214
215         public static final int SUCCESS = 0;
216
217         public static final int FAILURE = -1;
218
219         private int code;
220
221         private String body;
222
223         /**
224          * @return Returns the code.
225          */
226         public int getCode() {
227             return code;
228         }
229
230         /**
231          * @param code The code to set.
232          */
233         public void setCode(int code) {
234             this.code = code;
235         }
236
237         /**
238          * @return Returns the body.
239          */
240         public String getBody() {
241             return body;
242         }
243
244         /**
245          * @param body The body to set.
246          */
247         public void setBody(String body) {
248             this.body = body;
249         }
250
251         @Override
252         public String toString() {
253             try {
254                 return EntityUtils.toString(this, this.getClass());
255             } catch(Exception e) {
256                 log.error("to string error:", e);
257                 return "code:" + this.getCode() + ",body:" + this.getBody();
258             }
259         }
260
261     }
262 }