Search in sources :

Example 16 with ObjectMapper

use of org.codehaus.jackson.map.ObjectMapper in project MSEC by Tencent.

the class CarryOutReleasePlan method exec.

public JsonRPCResponseBase exec(ReleasePlan request) {
    Logger logger = Logger.getLogger(CarryOutReleasePlan.class);
    JsonRPCResponseBase resp = new JsonRPCResponseBase();
    plan_id = request.getPlan_id();
    flsn = request.getFirst_level_service_name();
    slsn = request.getSecond_level_service_name();
    logger.info(String.format("carry out plan begin\n [%s.%s][%s]\n", flsn, slsn, plan_id));
    if (flsn == null || flsn.length() < 1 || slsn == null || slsn.length() < 1 || plan_id == null || plan_id.length() < 1) {
        resp.setStatus(100);
        resp.setMessage("service name/plan id invalid!");
        return resp;
    }
    String result = checkIdentity();
    if (!result.equals("success")) {
        resp.setStatus(99);
        resp.setMessage(result);
        return resp;
    }
    DBUtil util = new DBUtil();
    if (util.getConnection() == null) {
        resp.setStatus(100);
        resp.setMessage("db connect failed!");
        return resp;
    }
    try {
        String sql = "select dest_ip_list, memo,release_type from t_release_plan where plan_id=?";
        ArrayList<Object> params = new ArrayList<Object>();
        params.add(request.getPlan_id());
        Map<String, Object> res = util.findSimpleResult(sql, params);
        if (res.get("dest_ip_list") == null) {
            resp.setStatus(100);
            resp.setMessage("query dest ip list failed.");
            return resp;
        }
        String dest_ip_list = (String) (res.get("dest_ip_list"));
        release_memo = (String) (res.get("memo"));
        release_type = (String) (res.get("release_type"));
        release_memo = plan_id.substring(4, 12) + release_memo;
        ObjectMapper objectMapper = new ObjectMapper();
        IPPortPair[] ips = objectMapper.readValue(dest_ip_list, IPPortPair[].class);
        logger.info("destination IP number;" + ips.length);
        //每一个目标ip执行耗时估计30s,
        long gap = ips.length * 60;
        long lastCarryoutTime = getLastCarryoutTime(util);
        checkTime(util, gap, lastCarryoutTime);
        logger.info("check last carry out time OK");
        //对每个IP下发安装包
        String tarFile = PackReleaseFile.getPackedFile(request.getPlan_id());
        logger.info("release package path:" + tarFile);
        getHttpResponse().setContentType("text/html");
        getHttpResponse().setCharacterEncoding("UTF-8");
        ServletOutputStream out = getHttpResponse().getOutputStream();
        safeWrite("<html>", out);
        safeWrite("<head>", out);
        safeWrite("<title>release result</title>", out);
        safeWrite("</head>", out);
        safeWrite("<body>", out);
        //这个标签用于原样输出
        safeWrite("<pre>", out);
        updatePlanStatus(util, "carrying out");
        String dev_lang = getDevLang(util, flsn, slsn);
        doRelease(tarFile, ips, out, lastCarryoutTime == 0, dev_lang, util);
        safeWrite("</pre>", out);
        safeWrite("</body>", out);
        safeWrite("</html>", out);
        //update plan status
        updatePlanStatus(util, "carry out successfully");
        try {
            out.close();
        } catch (Exception e) {
        }
        return null;
    } catch (Exception e) {
        resp.setStatus(100);
        resp.setMessage(e.getMessage());
        e.printStackTrace();
        try {
            updatePlanStatus(util, "failed to carry out");
        } catch (Exception e1) {
        }
        return resp;
    } finally {
        util.releaseConn();
    }
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) ArrayList(java.util.ArrayList) Logger(org.apache.log4j.Logger) IPPortPair(beans.request.IPPortPair) ObjectMapper(org.codehaus.jackson.map.ObjectMapper)

Example 17 with ObjectMapper

use of org.codehaus.jackson.map.ObjectMapper in project MSEC by Tencent.

the class JsonRPCServlet method service.

protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Logger logger = Logger.getLogger(JsonRPCServlet.class);
    req.setCharacterEncoding("UTF-8");
    //从http请求里获取完整的json字符串
    //json字符串是http请求的一个form字段
    String request_string = req.getParameter("request_string");
    int maxLen = request_string.length();
    if (maxLen > 10240) {
        maxLen = 10240;
    }
    logger.info("request_string:" + request_string.substring(0, maxLen));
    //ObjectManager和JSONObject两个都是 json与java类之间的转换工具
    ObjectMapper objectMapper = new ObjectMapper();
    JSONObject jsonObject = new JSONObject(request_string);
    String handleClassStr = jsonObject.getString("handleClass");
    JSONObject requestBodyObj = jsonObject.getJSONObject("requestBody");
    logger.info("requestBody:" + requestBodyObj.toString());
    try {
        //加载handleClass字段指定的类,并创建它的实例
        Class<?> clazz = Class.forName(handleClassStr);
        JsonRPCHandler handler = (JsonRPCHandler) clazz.newInstance();
        //将http的上下文信息传给该实例,以方便在业务逻辑处理的时候访问
        handler.setHttpRequest(req);
        handler.setHttpResponse(resp);
        handler.setServlet(this);
        //获取类的所有成员方法,遍历找到exec函数
        Method[] methods = clazz.getMethods();
        boolean execFound = false;
        for (int i = 0; i < methods.length; i++) {
            if (methods[i].getName().equals("exec")) {
                execFound = true;
                //获取exec的参数列表,要求只能有一个参数
                Class<?>[] paramTypes = methods[i].getParameterTypes();
                if (paramTypes.length != 1) {
                    errorResponse(resp, "handle class's exec() method's param number is not 1!");
                    return;
                }
                //将json字符串的requestBody部分映射到一个java类的实例,作为exec函数的参数
                Object exec_request = objectMapper.readValue(requestBodyObj.toString(), paramTypes[0]);
                //特殊场景下,例如文件下载等,exec 会返回null,不需要给前端返回json字符串
                try {
                    Object exec_result = methods[i].invoke(handler, exec_request);
                    if (exec_result != null) {
                        //�����ص�bean���л�Ϊjson�ַ���
                        String s = objectMapper.writeValueAsString(exec_result);
                        resp.setCharacterEncoding("UTF-8");
                        resp.setContentType("application/json; charset=utf-8");
                        PrintWriter out = resp.getWriter();
                        out.println(s);
                        maxLen = s.length();
                        if (maxLen > 10240) {
                            maxLen = 10240;
                        }
                        logger.info("response:" + s.substring(0, maxLen));
                        out.close();
                    }
                    return;
                } catch (InvocationTargetException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }
            }
        }
        if (!execFound) {
            errorResponse(resp, "handleClass has NOT method named exec()");
            return;
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        logger.error(e.getMessage());
        errorResponse(resp, "ClassNotFoundException:" + e.toString());
        return;
    } catch (InstantiationException e) {
        e.printStackTrace();
        logger.error(e.getMessage());
        errorResponse(resp, "InstantiationException:" + e.toString());
        ;
        return;
    } catch (IllegalAccessException e) {
        e.printStackTrace();
        logger.error(e.getMessage());
        errorResponse(resp, "IllegalAccessException:" + e.toString());
        return;
    }
}
Also used : Method(java.lang.reflect.Method) Logger(org.apache.log4j.Logger) InvocationTargetException(java.lang.reflect.InvocationTargetException) JSONObject(org.json.JSONObject) JSONObject(org.json.JSONObject) ObjectMapper(org.codehaus.jackson.map.ObjectMapper) PrintWriter(java.io.PrintWriter)

Example 18 with ObjectMapper

use of org.codehaus.jackson.map.ObjectMapper in project MSEC by Tencent.

the class ReleaseOnlyLibrary method CommitPlan.

private String CommitPlan(ReleasePlan plan) {
    //产生发布用的文件,并记录到数据库里
    DBUtil util = new DBUtil();
    if (util.getConnection() == null) {
        return "DB Connect Failed.";
    }
    String sql;
    List<Object> params = new ArrayList<Object>();
    try {
        ObjectMapper objectMapper = new ObjectMapper();
        String dest_ip_list_json_str = objectMapper.writeValueAsString(plan.getDest_ip_list());
        //System.out.println(dest_ip_list_json_str);
        sql = "insert into t_release_plan(plan_id, first_level_service_name,second_level_service_name," + "config_tag,idl_tag, sharedobject_tag, dest_ip_list,status,memo,release_type) values(?,?,?,?,?,?,?,'creating',?,?)";
        params.add(plan.getPlan_id());
        params.add(plan.getFirst_level_service_name());
        params.add(plan.getSecond_level_service_name());
        params.add("");
        params.add("");
        params.add("");
        params.add(dest_ip_list_json_str);
        params.add(plan.getMemo());
        params.add(plan.getRelease_type());
        int addNum = util.updateByPreparedStatement(sql, params);
        if (addNum != 1) {
            return "addNum is not 1:" + addNum;
        }
        //打包文件
        new Thread(new PackReleaseFile(plan, getServlet().getServletContext())).start();
        return "success";
    } catch (Exception e) {
        e.printStackTrace();
        return e.getMessage();
    } finally {
        util.releaseConn();
        ;
    }
}
Also used : DBUtil(ngse.org.DBUtil) ArrayList(java.util.ArrayList) ObjectMapper(org.codehaus.jackson.map.ObjectMapper)

Example 19 with ObjectMapper

use of org.codehaus.jackson.map.ObjectMapper in project MSEC by Tencent.

the class ReleaseStepsGO method CommitPlan.

private String CommitPlan(ReleasePlan plan) {
    //产生发布用的文件,并记录到数据库里
    DBUtil util = new DBUtil();
    if (util.getConnection() == null) {
        return "DB Connect Failed.";
    }
    String sql;
    List<Object> params = new ArrayList<Object>();
    try {
        ObjectMapper objectMapper = new ObjectMapper();
        String dest_ip_list_json_str = objectMapper.writeValueAsString(plan.getDest_ip_list());
        //System.out.println(dest_ip_list_json_str);
        sql = "insert into t_release_plan(plan_id, first_level_service_name,second_level_service_name," + "config_tag,idl_tag, sharedobject_tag, dest_ip_list,status,memo,release_type) values(?,?,?,?,?,?,?,'creating',?,?)";
        params.add(plan.getPlan_id());
        params.add(plan.getFirst_level_service_name());
        params.add(plan.getSecond_level_service_name());
        params.add(plan.getConfig_tag());
        params.add(plan.getIdl_tag());
        params.add(plan.getSharedobject_tag());
        params.add(dest_ip_list_json_str);
        params.add(plan.getMemo());
        params.add(plan.getRelease_type());
        int addNum = util.updateByPreparedStatement(sql, params);
        if (addNum != 1) {
            return "addNum is not 1:" + addNum;
        }
        //打包文件
        new Thread(new PackReleaseFile(plan, getServlet().getServletContext())).start();
        return "success";
    } catch (Exception e) {
        e.printStackTrace();
        return e.getMessage();
    } finally {
        util.releaseConn();
        ;
    }
}
Also used : DBUtil(ngse.org.DBUtil) ArrayList(java.util.ArrayList) ObjectMapper(org.codehaus.jackson.map.ObjectMapper)

Example 20 with ObjectMapper

use of org.codehaus.jackson.map.ObjectMapper in project MSEC by Tencent.

the class RollbackReleasePlan method exec.

public JsonRPCResponseBase exec(ReleasePlan request) {
    Logger logger = Logger.getLogger(RollbackReleasePlan.class);
    JsonRPCResponseBase resp = new JsonRPCResponseBase();
    plan_id = request.getPlan_id();
    flsn = request.getFirst_level_service_name();
    slsn = request.getSecond_level_service_name();
    String result = checkIdentity();
    if (!result.equals("success")) {
        resp.setStatus(99);
        resp.setMessage(result);
        return resp;
    }
    DBUtil util = new DBUtil();
    if (util.getConnection() == null) {
        resp.setStatus(100);
        resp.setMessage("db connect failed!");
        return resp;
    }
    try {
        String sql = "select dest_ip_list from t_release_plan where plan_id=?";
        ArrayList<Object> params = new ArrayList<Object>();
        params.add(request.getPlan_id());
        Map<String, Object> res = util.findSimpleResult(sql, params);
        if (res.get("dest_ip_list") == null) {
            resp.setStatus(100);
            resp.setMessage("query dest ip list failed.");
            return resp;
        }
        String dest_ip_list = (String) (res.get("dest_ip_list"));
        ObjectMapper objectMapper = new ObjectMapper();
        IPPortPair[] ips = objectMapper.readValue(dest_ip_list, IPPortPair[].class);
        logger.info("destination IP number;" + ips.length);
        //对每个IP执行回滚
        getHttpResponse().setContentType("text/html");
        getHttpResponse().setCharacterEncoding("UTF-8");
        ServletOutputStream out = getHttpResponse().getOutputStream();
        safeWrite("<html>", out);
        safeWrite("<head>", out);
        safeWrite("<title>release result</title>", out);
        safeWrite("</head>", out);
        safeWrite("<body>", out);
        //这个标签用于原样输出
        safeWrite("<pre>", out);
        updatePlanStatus(util, "rolling back");
        doRollback(ips, out, util);
        safeWrite("</pre>", out);
        safeWrite("</body>", out);
        safeWrite("</html>", out);
        //update plan status
        updatePlanStatus(util, "roll back successfully");
        try {
            out.close();
        } catch (Exception e) {
        }
        return null;
    } catch (Exception e) {
        resp.setStatus(100);
        resp.setMessage(e.getMessage());
        e.printStackTrace();
        try {
            updatePlanStatus(util, "failed to roll back");
        } catch (Exception e1) {
        }
        return resp;
    } finally {
        util.releaseConn();
    }
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) ArrayList(java.util.ArrayList) Logger(org.apache.log4j.Logger) IPPortPair(beans.request.IPPortPair) ObjectMapper(org.codehaus.jackson.map.ObjectMapper)

Aggregations

ObjectMapper (org.codehaus.jackson.map.ObjectMapper)356 IOException (java.io.IOException)75 Test (org.junit.Test)58 JsonNode (org.codehaus.jackson.JsonNode)47 ArrayList (java.util.ArrayList)43 HashMap (java.util.HashMap)43 Test (org.testng.annotations.Test)37 Map (java.util.Map)33 List (java.util.List)25 StringWriter (java.io.StringWriter)22 File (java.io.File)21 JSONObject (org.json.JSONObject)18 JsonMappingException (org.codehaus.jackson.map.JsonMappingException)15 Version (org.codehaus.jackson.Version)14 SimpleModule (org.codehaus.jackson.map.module.SimpleModule)14 ByteArrayInputStream (java.io.ByteArrayInputStream)13 JsonFactory (org.codehaus.jackson.JsonFactory)13 JSONObject (org.codehaus.jettison.json.JSONObject)12 ByteArrayOutputStream (java.io.ByteArrayOutputStream)11 HttpRequest (org.jboss.netty.handler.codec.http.HttpRequest)11