2 * Copyright 2016 Huawei Technologies Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package org.openo.nfvo.jujuvnfmadapter.common;
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;
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;
31 import net.sf.json.JSONObject;
39 * @version NFVO 0.5 Aug 30, 2016
41 public class EntityUtils {
43 private static final Logger LOG = LoggerFactory.getLogger(EntityUtils.class);
45 public static final String RESULT_CODE_KEY = "retCode";
47 public static final String MSG_KEY = "msg";
49 public static final String DATA_KEY = "data";
51 public static final String STATUS = "status";
58 private EntityUtils() {
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()));
82 * format the obj to str style as json format.
90 public static String toString(Object obj, Class<?> clazz) {
91 JSONObject jsonObj = new JSONObject();
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) : "");
98 } catch(Exception e) {
99 LOG.error("to string error:", e);
101 return jsonObj.toString();
111 public static class ExeRes {
113 public static final int SUCCESS = 0;
115 public static final int FAILURE = -1;
122 * @return Returns the code.
124 public int getCode() {
129 * @param code The code to set.
131 public void setCode(int code) {
136 * @return Returns the body.
138 public String getBody() {
143 * @param body The body to set.
145 public void setBody(String body) {
150 public String toString() {
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();
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
174 return builder.toString();
185 public static ExeRes execute(String dir, String... command) {
186 List<String> commands = new ArrayList<>(command.length);
187 for(String arg : command) {
190 return execute(dir, commands);
195 * execute local command
198 * @param dir the command path
200 * @return response msg
203 public static ExeRes execute(String dir, List<String> command) {
204 ExeRes er = new ExeRes();
205 StringBuilder sb = new StringBuilder();
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);
212 ProcessBuilder pb = new ProcessBuilder(command);
213 if(StringUtils.isNotBlank(dir)) {
214 pb.directory(new File(dir));
216 pb.redirectErrorStream(true);
217 Process p = pb.start();
219 // wait the process result
220 buildProcessResult(er, p);
222 InputStream in = p.getInputStream();
223 byte[] buffer = new byte[1024];
225 while((length = in.read(buffer)) > 0) {
226 sb.append(new String(buffer, 0, length));
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);
243 * @throws TimeoutException
244 * @throws InterruptedException
247 private static void buildProcessResult(ExeRes er, Process p) throws TimeoutException, InterruptedException {
248 Worker worker = new Worker(p);
251 worker.join(Constant.PROCESS_WAIT_MILLIS);
252 if(worker.exitValue != null) {
253 int exit = worker.exitValue;
255 er.setCode(ExeRes.FAILURE);
256 LOG.warn("the process exit non-normal");
258 er.setCode(ExeRes.SUCCESS);
261 er.setCode(ExeRes.FAILURE);
262 LOG.warn("the process execute timeout.");
263 throw new TimeoutException();
265 } catch(InterruptedException e) {
267 Thread.currentThread().interrupt();
272 private static class Worker extends Thread {
274 private final Process process;
276 private Integer exitValue;
278 private Worker(Process process) {
279 this.process = process;
290 exitValue = process.waitFor();
291 } catch(InterruptedException e) {