Example usage for org.dom4j Document getRootElement

List of usage examples for org.dom4j Document getRootElement

Introduction

In this page you can find the example usage for org.dom4j Document getRootElement.

Prototype

Element getRootElement();

Source Link

Document

Returns the root Element for this document.

Usage

From source file:com.cloopen.rest.sdk.CCPRestSDK.java

License:Open Source License

/**
 * @description xml??map//from   ww  w .j a  va  2s  . c  o  m
 * @param xml
 * @return Map
 */
private HashMap<String, Object> xmlToMap(String xml) {
    HashMap<String, Object> map = new HashMap<String, Object>();
    Document doc = null;
    try {
        doc = DocumentHelper.parseText(xml); // XML
        Element rootElt = doc.getRootElement(); // ?
        HashMap<String, Object> hashMap2 = new HashMap<String, Object>();
        ArrayList<HashMap<String, Object>> arrayList = new ArrayList<HashMap<String, Object>>();
        for (Iterator i = rootElt.elementIterator(); i.hasNext();) {
            Element e = (Element) i.next();
            if ("statusCode".equals(e.getName()) || "statusMsg".equals(e.getName()))
                map.put(e.getName(), e.getText());
            else {
                if ("SubAccount".equals(e.getName()) || "TemplateSMS".equals(e.getName())
                        || "totalCount".equals(e.getName()) || "token".equals(e.getName())
                        || "callSid".equals(e.getName()) || "state".equals(e.getName())
                        || "downUrl".equals(e.getName())) {
                    if (!"SubAccount".equals(e.getName()) && !"TemplateSMS".equals(e.getName())) {
                        hashMap2.put(e.getName(), e.getText());
                    } else if ("SubAccount".equals(e.getName())) {

                        HashMap<String, Object> hashMap3 = new HashMap<String, Object>();
                        for (Iterator i2 = e.elementIterator(); i2.hasNext();) {
                            Element e2 = (Element) i2.next();
                            hashMap3.put(e2.getName(), e2.getText());
                        }
                        arrayList.add(hashMap3);
                        hashMap2.put("SubAccount", arrayList);
                    } else if ("TemplateSMS".equals(e.getName())) {

                        HashMap<String, Object> hashMap3 = new HashMap<String, Object>();
                        for (Iterator i2 = e.elementIterator(); i2.hasNext();) {
                            Element e2 = (Element) i2.next();
                            hashMap3.put(e2.getName(), e2.getText());
                        }
                        arrayList.add(hashMap3);
                        hashMap2.put("TemplateSMS", arrayList);
                    }
                    map.put("data", hashMap2);
                } else {

                    HashMap<String, Object> hashMap3 = new HashMap<String, Object>();
                    for (Iterator i2 = e.elementIterator(); i2.hasNext();) {
                        Element e2 = (Element) i2.next();
                        // hashMap2.put(e2.getName(),e2.getText());
                        hashMap3.put(e2.getName(), e2.getText());
                    }
                    if (hashMap3.size() != 0) {
                        hashMap2.put(e.getName(), hashMap3);
                    } else {
                        hashMap2.put(e.getName(), e.getText());
                    }
                    map.put("data", hashMap2);
                }
            }
        }
    } catch (DocumentException e) {
        e.printStackTrace();
        LoggerUtil.error(e.getMessage());
    } catch (Exception e) {
        LoggerUtil.error(e.getMessage());
        e.printStackTrace();
    }
    return map;
}

From source file:com.cn.servlet.DataInterface.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//w w  w  .  j a  va2  s  .  c  o m
 *
 * @param request servlet request
 * @param response servlet response
 * @param params
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response, String params)
        throws ServletException, IOException {
    String uri = request.getRequestURI();
    String subUri = uri.substring(uri.lastIndexOf("/") + 1, uri.lastIndexOf("."));
    String json = null;
    CommonController commonController = new CommonController();
    InterfaceController interfaceController = new InterfaceController();
    DatabaseOpt opt = new DatabaseOpt();
    //logger.info(Units.getIpAddress(request) + "accept:" + subUri + ",time:" + (new Date().getTime()));

    try {
        logger.info(subUri + ",params:" + params);
        JSONObject paramsJson = JSONObject.parseObject(params);
        //logger.info("send:" + subUri + ",time:" + paramsJson.getString("timestamp"));
        String module = paramsJson.getString("module");
        String operation = paramsJson.getString("operation");
        String rely = (paramsJson.getString("rely") == null) ? ("{}") : (paramsJson.getString("rely"));
        String target = paramsJson.getString("target");
        String datas = (paramsJson.getString("datas") == null) ? ("") : paramsJson.getString("datas");
        String update = paramsJson.getString("update");
        String add = paramsJson.getString("add");
        String delete = paramsJson.getString("del");
        String item = paramsJson.getString("item");
        String details = paramsJson.getString("details");
        String detail = paramsJson.getString("detail");
        String fileName = paramsJson.getString("fileName");
        String operateType = paramsJson.getString("type");
        String start = paramsJson.getString("start");
        String end = paramsJson.getString("end");
        int isHistory = paramsJson.getIntValue("isHistory");
        int pageIndex = paramsJson.getIntValue("pageIndex");
        int pageSize = paramsJson.getIntValue("pageSize");

        HttpSession session = request.getSession();
        String path = this.getClass().getClassLoader().getResource("/").getPath().replaceAll("%20", " ");
        String importPath = getServletContext().getRealPath("/").replace("\\", "/") + "excelFile/";

        /*??*/
        if (!"userLogin".equals(module) && (session.getAttribute("user") == null
                || session.getAttribute("loginType") == null || session.getAttribute("employee") == null)) {
            session.invalidate();
            json = Units.objectToJson(-99, "", null);
            PrintWriter out = response.getWriter();
            try {
                response.setContentType("text/html;charset=UTF-8");
                response.setHeader("Cache-Control", "no-store");
                response.setHeader("Pragma", "no-cache");
                response.setDateHeader("Expires", 0);
                out.print(json);
            } finally {
                out.close();
            }
            return;
        }

        Employee curEmployee = null;
        Customer curCustomer = null;
        if (session.getAttribute("employee") != null
                && session.getAttribute("loginType").toString().compareTo("employeeLogin") == 0) {
            curEmployee = (Employee) session.getAttribute("employee");
        }
        if (session.getAttribute("employee") != null
                && session.getAttribute("loginType").toString().compareTo("customerLogin") == 0) {
            curCustomer = (Customer) session.getAttribute("employee");
        }

        switch (module) {
        //<editor-fold desc="?">
        case "userLogin": {
            switch (operation) {
            //<editor-fold desc="">
            case "employeeLogin": {
                String whereSql = "EmployeeName = '" + paramsJson.getString("username") + "'";
                List<Object> res = commonController.dataBaseQuery("table", "com.cn.bean.", "Employee", "*",
                        whereSql, 1, 1, "EmployeeName", 1, DatabaseOpt.DATA);
                String type = paramsJson.getString("type");
                if (res != null && res.size() > 0) {
                    Employee employee = (Employee) res.get(0);
                    if (employee.getEmployeePassword().compareTo(paramsJson.getString("password")) == 0) {
                        session.setAttribute("user", paramsJson.getString("username"));
                        session.setAttribute("loginType", "employeeLogin");
                        session.setAttribute("employee", employee);
                        //session.setAttribute("customer", null);
                        String whereCase = "RoleCode in ('" + employee.getEmployeeTypeCode() + "')";
                        List<Object> roleRight = commonController.dataBaseQuery("table", "com.cn.bean.",
                                "PlatformRoleRight", "*", whereCase, Integer.MAX_VALUE, 1, "RoleCode", 0,
                                DatabaseOpt.BASE);
                        if (roleRight != null && roleRight.size() > 0) {
                            ArrayList<String> roleRightList = new ArrayList<>();
                            roleRight.stream().map((obj) -> (PlatformRoleRight) obj).forEach((right) -> {
                                roleRightList.add(right.getRightCode());
                            });

                            if (type.compareTo("pc") == 0) {
                                /*???????*/
                                String menuJson = "{";
                                SAXReader reader = new SAXReader();
                                Document document = reader.read(new File(path + "menu.xml"));
                                Element root = document.getRootElement();
                                Iterator<Element> iterator = root.elementIterator();
                                while (iterator.hasNext()) {
                                    menuJson += commonController.hasRight(iterator.next(), roleRightList);
                                }
                                if (menuJson.length() <= 1) {
                                    menuJson = null;
                                    json = Units.objectToJson(-1, "???!", menuJson);
                                } else {
                                    menuJson = menuJson.substring(0, menuJson.length() - 1) + "}";
                                    json = Units.objectToJson(0, "?!", menuJson);
                                }
                            }
                            if (type.compareTo("app") == 0) {
                                /*???????*/
                                String menuJson = "{";
                                SAXReader reader = new SAXReader();
                                Document document = reader.read(new File(path + "menu.xml"));
                                Element root = document.getRootElement();
                                Iterator<Element> iterator = root.elementIterator();
                                while (iterator.hasNext()) {
                                    menuJson += commonController.hasAppRight(iterator.next(), roleRightList);
                                }
                                if (menuJson.length() <= 1) {
                                    menuJson = null;
                                    json = Units.objectToJson(-1, "???!", menuJson);
                                } else {
                                    menuJson = menuJson.substring(0, menuJson.length() - 1) + "}";
                                    JSONObject object = new JSONObject();
                                    object.put("menuJson", menuJson);
                                    object.put("employee", employee);
                                    json = Units.objectToJson(0, "?!", object);
                                }
                            }
                        } else {
                            json = Units.objectToJson(-1, "???!", null);
                        }
                    } else {
                        json = Units.objectToJson(-1, "????!", null);
                    }
                } else {
                    json = Units.objectToJson(-1, "???!", null);
                }

                break;
            }
            //</editor-fold>

            //<editor-fold desc="?">
            case "login": {
                String type = paramsJson.getString("type");
                PlatformUserInfoController controller = new PlatformUserInfoController();
                int result = controller.userLogin(paramsJson.getString("username"),
                        paramsJson.getString("password"));
                switch (result) {
                case 0:
                    session.setAttribute("user", paramsJson.getString("username"));
                    session.setAttribute("loginType", "login");
                    //session.setAttribute("customer", null);
                    session.setAttribute("employee", null);
                    /*??*/
                    String whereCase = "UserLoginAccount = '" + paramsJson.getString("username") + "'";
                    List<Object> userRole = commonController.dataBaseQuery("table", "com.cn.bean.",
                            "PlatformUserRole", "*", whereCase, Integer.MAX_VALUE, 1, "UserLoginAccount", 0,
                            DatabaseOpt.BASE);
                    if (userRole != null) {
                        /*?????*/
                        whereCase = "RoleCode in (";
                        for (Object obj : userRole) {
                            PlatformUserRole role = (PlatformUserRole) obj;
                            whereCase += "'" + role.getRoleCode() + "',";
                        }
                        whereCase = whereCase.substring(0, whereCase.length() - 1);
                        whereCase += ")";
                        List<Object> roleRight = commonController.dataBaseQuery("table", "com.cn.bean.",
                                "PlatformRoleRight", "*", whereCase, Integer.MAX_VALUE, 1, "RoleCode", 0,
                                DatabaseOpt.BASE);
                        ArrayList<String> roleRightList = new ArrayList<>();
                        roleRight.stream().map((obj) -> (PlatformRoleRight) obj).forEach((right) -> {
                            roleRightList.add(right.getRightCode());
                        });
                        /*???????*/
                        String menuJson = "{";
                        SAXReader reader = new SAXReader();
                        Document document = reader.read(new File(path + "menu.xml"));
                        Element root = document.getRootElement();
                        Iterator<Element> iterator = root.elementIterator();
                        while (iterator.hasNext()) {
                            menuJson += commonController.hasRight(iterator.next(), roleRightList);
                        }
                        menuJson = menuJson.substring(0, menuJson.length() - 1) + "}";

                        if (type.compareTo("pc") == 0) {
                            json = Units.objectToJson(result, "?!", menuJson);
                        }
                        if (type.compareTo("app") == 0) {
                            json = Units.objectToJson(result, "?!", roleRightList);
                        }
                    } else {
                        json = Units.objectToJson(-1, "?!", null);
                    }
                    break;
                case 1:
                    json = Units.objectToJson(result, "???!", null);
                    break;
                case 2:
                    json = Units.objectToJson(result, "???!", null);
                    break;
                case -1:
                    json = Units.objectToJson(result, "!", null);
                    break;
                default:
                    json = Units.objectToJson(result, "?!", null);
                    break;
                }
                break;
            }
            //</editor-fold>

            //<editor-fold desc="">
            case "customerLogin": {
                String whereSql = "CustomerID = '" + paramsJson.getString("username") + "'";
                List<Object> res = commonController.dataBaseQuery("view", "com.cn.bean.", "Customer", "*",
                        whereSql, 1, 1, "CustomerID", 1, DatabaseOpt.DATA);
                String type = paramsJson.getString("type");
                if (res != null && res.size() > 0) {
                    Customer customer = (Customer) res.get(0);
                    if (customer.getCustomerPassword().compareTo(paramsJson.getString("password")) == 0) {
                        session.setAttribute("user", paramsJson.getString("username"));
                        session.setAttribute("loginType", "customerLogin");
                        //session.setAttribute("customer", customer);
                        session.setAttribute("employee", customer);
                        String whereCase = "RoleCode in ('" + customer.getCustomerRoleCode() + "')";
                        List<Object> roleRight = commonController.dataBaseQuery("table", "com.cn.bean.",
                                "PlatformRoleRight", "*", whereCase, Integer.MAX_VALUE, 1, "RoleCode", 0,
                                DatabaseOpt.BASE);
                        if (roleRight != null && roleRight.size() > 0) {
                            ArrayList<String> roleRightList = new ArrayList<>();
                            roleRight.stream().map((obj) -> (PlatformRoleRight) obj).forEach((right) -> {
                                roleRightList.add(right.getRightCode());
                            });

                            if (type.compareTo("pc") == 0) {
                                /*???????*/
                                String menuJson = "{";
                                SAXReader reader = new SAXReader();
                                Document document = reader.read(new File(path + "menu.xml"));
                                Element root = document.getRootElement();
                                Iterator<Element> iterator = root.elementIterator();
                                while (iterator.hasNext()) {
                                    menuJson += commonController.hasRight(iterator.next(), roleRightList);
                                }
                                if (menuJson.length() <= 1) {
                                    menuJson = null;
                                    json = Units.objectToJson(-1, "???!", menuJson);
                                } else {
                                    menuJson = menuJson.substring(0, menuJson.length() - 1) + "}";
                                    json = Units.objectToJson(0, "?!", menuJson);
                                }
                            }
                            if (type.compareTo("app") == 0) {
                                /*???????*/
                                String menuJson = "{";
                                SAXReader reader = new SAXReader();
                                Document document = reader.read(new File(path + "menu.xml"));
                                Element root = document.getRootElement();
                                Iterator<Element> iterator = root.elementIterator();
                                while (iterator.hasNext()) {
                                    menuJson += commonController.hasAppRight(iterator.next(), roleRightList);
                                }

                                if (menuJson.length() <= 1) {
                                    menuJson = null;
                                    json = Units.objectToJson(-1, "???!", menuJson);
                                } else {
                                    menuJson = menuJson.substring(0, menuJson.length() - 1) + "}";
                                    JSONObject object = new JSONObject();
                                    object.put("menuJson", menuJson);
                                    object.put("employee", customer);
                                    json = Units.objectToJson(0, "?!", object);
                                }
                            }
                        } else {
                            json = Units.objectToJson(-1, "???!", null);
                        }
                    } else {
                        json = Units.objectToJson(-1, "????!", null);
                    }
                } else {
                    json = Units.objectToJson(-1, "???!", null);
                }
                break;
            }
            //</editor-fold>
            }
            break;
        }
        //</editor-fold>

        //<editor-fold desc="?">
        case "?": {
            String oldPassword = paramsJson.getString("oldPassword");
            String newPassword = paramsJson.getString("newPassword");
            switch (session.getAttribute("loginType").toString()) {
            case "employeeLogin": {
                if (curEmployee != null && curEmployee.getEmployeePassword().compareTo(oldPassword) == 0) {
                    JSONArray updateParams = new JSONArray();
                    JSONObject setObj = new JSONObject();
                    setObj.put("employeePassword", newPassword);
                    updateParams.add(setObj);
                    JSONObject whereObj = new JSONObject();
                    whereObj.put("employeeName", curEmployee.getEmployeeName());
                    updateParams.add(whereObj);

                    ArrayList<Integer> updateResult = commonController.dataBaseOperate(
                            updateParams.toJSONString(), "com.cn.bean.", "Employee", "update",
                            DatabaseOpt.DATA);
                    if (updateResult.get(0) == 0) {
                        json = Units.objectToJson(0, "??!", null);
                    } else {
                        json = Units.objectToJson(-1, "?!", null);
                    }
                } else {
                    json = Units.objectToJson(-1, "??!", null);
                }
                break;
            }
            case "customerLogin": {
                if (curCustomer != null && curCustomer.getCustomerPassword().compareTo(oldPassword) == 0) {
                    JSONArray updateParams = new JSONArray();
                    JSONObject setObj = new JSONObject();
                    setObj.put("customerPassword", newPassword);
                    updateParams.add(setObj);
                    JSONObject whereObj = new JSONObject();
                    whereObj.put("customerID", curCustomer.getCustomerID());
                    updateParams.add(whereObj);

                    ArrayList<Integer> updateResult = commonController.dataBaseOperate(
                            updateParams.toJSONString(), "com.cn.bean.", "Customer", "update",
                            DatabaseOpt.DATA);
                    if (updateResult.get(0) == 0) {
                        json = Units.objectToJson(0, "??!", null);
                    } else {
                        json = Units.objectToJson(-1, "?!", null);
                    }
                } else {
                    json = Units.objectToJson(-1, "??!", null);
                }
                break;
            }
            case "login": {

                break;
            }
            }
            break;
        }
        //</editor-fold>

        //<editor-fold desc="?">
        case "?": {
            if (curEmployee != null && curEmployee.getEmployeeName().compareTo("?") == 0) {
                CommonOperate operate = new CommonOperate();
                json = operate.dataMoveToHistory(curEmployee.getEmployeeName());
            } else {
                json = Units.objectToJson(-1, "???", null);
            }
            break;
        }
        //</editor-fold>

        //<editor-fold desc="">
        case "": {
            List<Object> res = commonController.dataBaseQuery("table", "com.cn.bean.", "DataJZ", "*", "",
                    Integer.MAX_VALUE, 1, "JZYMonth", 1, DatabaseOpt.DATA);
            if (res != null && res.size() > 0) {
                json = Units.objectToJson(0, "", res);
            } else {
                json = Units.objectToJson(-1, "?!", null);
            }
            break;
        }
        //</editor-fold>
        /**
         * ***************************************?**************************************
         */
        //<editor-fold desc="?">
        //<editor-fold desc="">
        case "": {
            switch (operation) {
            case "create": {
                json = interfaceController.createOperate(20, "table", "com/cn/json/plan/", "com.cn.bean.plan.",
                        "DHPlan", "DHPlanID", DatabaseOpt.DATA);
                json = Units.insertStr(json, "\\\"??\\",
                        ",@DHJH_" + Units.getNowTimeNoSeparator());
                break;
            }
            case "request_table": {
                if (target.compareToIgnoreCase("supplierID") == 0) {
                    String[] keys = { "supplierID", "supplierName" };
                    String[] keysName = { "?", "??" };
                    int[] keysWidth = { 50, 50 };
                    String[] fieldsName = { "customerID", "customerName" };
                    json = interfaceController.queryOperate(target, "com.cn.bean.", "table", "Customer",
                            "CustomerID", datas, rely, true, DatabaseOpt.DATA, pageSize, pageIndex, keys,
                            keysName, keysWidth, fieldsName);
                }
                if (target.compareToIgnoreCase("partCode") == 0) {
                    String[] keys = { "partCode", "partID", "partName", "partUnit", "cfAddress" };
                    String[] keysName = { "??", "??", "???", "???",
                            "?" };
                    int[] keysWidth = { 20, 20, 20, 20, 20 };
                    String[] fieldsName = { "partCode", "partID", "partName", "partUnit", "psAddress1" };
                    json = interfaceController.queryOperate(target, "com.cn.bean.", "table", "PartBaseInfo",
                            "PartCode", datas, rely, true, DatabaseOpt.DATA, pageSize, pageIndex, keys,
                            keysName, keysWidth, fieldsName);
                }
                break;
            }
            case "request_detail": {
                json = interfaceController.queryOperate("com.cn.bean.plan.", "table", "DHPlanList", "DHPlanID",
                        datas, rely, true, DatabaseOpt.DATA, pageSize, pageIndex);
                break;
            }
            case "request_page": {
                json = interfaceController.queryOperate("com.cn.bean.plan.", "table", "DHPlan", "DHPlanID",
                        datas, rely, true, DatabaseOpt.DATA, pageSize, pageIndex);
                break;
            }
            case "submit": {
                int result = commonController.dataBaseOperate("[" + item + "]", "com.cn.bean.plan.", "DHPlan",
                        "add", DatabaseOpt.DATA).get(0);
                if (result == 0) {
                    result = commonController.dataBaseOperate(details, "com.cn.bean.plan.", "DHPlanList", "add",
                            DatabaseOpt.DATA).get(0);
                    if (result == 0) {
                        json = Units.objectToJson(0, "??!", null);
                    } else {
                        json = Units.objectToJson(-1, "!", null);
                        commonController.dataBaseOperate("[" + item + "]", "com.cn.bean.plan.", "DHPlan",
                                "delete", DatabaseOpt.DATA);
                    }
                } else {
                    json = Units.objectToJson(-1, "?!", null);
                }
                break;
            }
            }
            break;
        }
        //</editor-fold>

        //<editor-fold desc="?">
        case "?": {
            switch (operation) {
            case "create": {
                json = interfaceController.createOperate(20, "table", "com/cn/json/plan/", "com.cn.bean.plan.",
                        "SHPlan", "SHPlanID", DatabaseOpt.DATA);
                json = Units.insertStr(json, "\\\"???\\",
                        ",@SHJH_" + Units.getNowTimeNoSeparator());
                break;
            }
            case "request_table": {
                if (target.compareToIgnoreCase("dhPlanID") == 0) {
                    String[] keys = { "dhPlanID" };
                    String[] keysName = { "??" };
                    int[] keysWidth = { 100, 50 };
                    String[] fieldsName = { "dhPlanID" };
                    json = interfaceController.queryOperate(target, "com.cn.bean.plan.", "table", "DHPlan",
                            "DHPlanID", datas, rely, true, DatabaseOpt.DATA, pageSize, pageIndex, keys,
                            keysName, keysWidth, fieldsName);
                }
                if (target.compareToIgnoreCase("supplierID") == 0) {
                    String[] keys = { "supplierID", "supplierName" };
                    String[] keysName = { "?", "??" };
                    int[] keysWidth = { 50, 50 };
                    String[] fieldsName = { "customerID", "customerName" };
                    json = interfaceController.queryOperate(target, "com.cn.bean.", "table", "Customer",
                            "CustomerID", datas, rely, true, DatabaseOpt.DATA, pageSize, pageIndex, keys,
                            keysName, keysWidth, fieldsName);
                }
                if (target.compareToIgnoreCase("partCode") == 0) {
                    String[] keys = { "partCode", "partID", "partName", "partUnit", "cfAddress" };
                    String[] keysName = { "??", "??", "???", "???",
                            "?" };
                    int[] keysWidth = { 20, 20, 20, 20, 20 };
                    String[] fieldsName = { "partCode", "partID", "partName", "partUnit", "psAddress1" };
                    json = interfaceController.queryOperate(target, "com.cn.bean.", "table", "PartBaseInfo",
                            "PartCode", datas, rely, true, DatabaseOpt.DATA, pageSize, pageIndex, keys,
                            keysName, keysWidth, fieldsName);
                }
                break;
            }
            case "request_detail": {
                json = interfaceController.queryOperate("com.cn.bean.plan.", "table", "SHPlanList", "SHPlanID",
                        datas, rely, true, DatabaseOpt.DATA, pageSize, pageIndex);
                break;
            }
            case "request_page": {
                json = interfaceController.queryOperate("com.cn.bean.plan.", "table", "SHPlan", "SHPlanID",
                        datas, rely, true, DatabaseOpt.DATA, pageSize, pageIndex);
                break;
            }
            case "submit": {
                int result = commonController.dataBaseOperate("[" + item + "]", "com.cn.bean.plan.", "SHPlan",
                        "add", DatabaseOpt.DATA).get(0);
                if (result == 0) {
                    result = commonController.dataBaseOperate(details, "com.cn.bean.plan.", "SHPlanList", "add",
                            DatabaseOpt.DATA).get(0);
                    if (result == 0) {
                        json = Units.objectToJson(0, "??!", null);
                    } else {
                        json = Units.objectToJson(-1, "!", null);
                    }
                } else {
                    json = Units.objectToJson(-1, "?!", null);
                }
                break;
            }
            }
            break;
        }
        //</editor-fold>
        //</editor-fold>
        }

    } catch (Exception e) {
        logger.info(subUri);
        logger.error("?:" + e.getMessage(), e);
        json = Units.objectToJson(-1, "?!", e.toString());
    }
    //logger.info(Units.getIpAddress(request) + "response:" + subUri + ",time:" + (new Date().getTime()));

    PrintWriter out = response.getWriter();

    try {
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        out.print(json);
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:com.collabnet.ccf.core.AbstractReader.java

License:Open Source License

private void modifySyncInfo(Document syncInfo, boolean isForced) {
    Element rootElement = syncInfo.getRootElement();
    Element forcedArtifactElement = rootElement.addElement(FORCED_ARTIFACT_ELEMENT);
    forcedArtifactElement.setText(Boolean.toString(isForced));
}

From source file:com.collabnet.ccf.core.AbstractReader.java

License:Open Source License

private void modifySyncInfo(Document syncInfo, String lastArtifactModifiedTime,
        String lastArtifactModifiedVersion) {
    if (lastArtifactModifiedTime == null && lastArtifactModifiedVersion == null) {
        return;/*from ww  w . j a v a 2s.  co m*/
    }
    //Cloned syncInfo is used to create two new element - ARTIFACT_LAST_MODIFIED_DATE and ARTIFACT_LAST_MODIFIED_VERSION
    Element rootElement = syncInfo.getRootElement();
    Element artifactLastModifiedTimeElement = rootElement.addElement(ARTIFACT_LAST_MODIFIED_DATE_ELEMENT);
    artifactLastModifiedTimeElement.setText(lastArtifactModifiedTime);
    Element artifactLastModifiedVersionElement = rootElement.addElement(ARTIFACT_LAST_MODIFIED_VERSION_ELEMENT);
    artifactLastModifiedVersionElement.setText(lastArtifactModifiedVersion);
}

From source file:com.collabnet.ccf.core.EntityService.java

License:Open Source License

/**
 * Main method to handle the mapping and filtering of source artifacts to
 * target repository artifact items Also include the quarantined artifact
 * lookup code/*from ww w.  j  av  a  2  s  .  co  m*/
 * 
 * @param data
 *            input XML document in generic XML artifact format
 * @return array of generated XML documents compliant to generic XML
 *         artifact schema
 */
private Object[] processXMLDocument(Document data) {
    Element element = null;
    try {
        element = XPathUtils.getRootElement(data);
        String artifactAction = XPathUtils.getAttributeValue(element, GenericArtifactHelper.ARTIFACT_ACTION);
        if (artifactAction.equals(GenericArtifactHelper.ARTIFACT_ACTION_IGNORE)) {
            return new Object[] { data };
        }

        // get top level attributes
        String artifactType = XPathUtils.getAttributeValue(element, GenericArtifactHelper.ARTIFACT_TYPE);
        String sourceArtifactId = XPathUtils.getAttributeValue(element,
                GenericArtifactHelper.SOURCE_ARTIFACT_ID);
        String sourceSystemId = XPathUtils.getAttributeValue(element, GenericArtifactHelper.SOURCE_SYSTEM_ID);
        String sourceRepositoryId = XPathUtils.getAttributeValue(element,
                GenericArtifactHelper.SOURCE_REPOSITORY_ID);
        String targetSystemId = XPathUtils.getAttributeValue(element, GenericArtifactHelper.TARGET_SYSTEM_ID);
        String targetRepositoryId = XPathUtils.getAttributeValue(element,
                GenericArtifactHelper.TARGET_REPOSITORY_ID);
        String sourceArtifactVersion = XPathUtils.getAttributeValue(element,
                GenericArtifactHelper.SOURCE_ARTIFACT_VERSION);
        String transactionId = XPathUtils.getAttributeValue(element, GenericArtifactHelper.TRANSACTION_ID);
        String artifactMode = XPathUtils.getAttributeValue(element, GenericArtifactHelper.ARTIFACT_MODE);
        boolean isPartialUpdate = GenericArtifactHelper.ARTIFACT_MODE_CHANGED_FIELDS_ONLY.equals(artifactMode);

        boolean replayedArtifact = (transactionId != null
                && !transactionId.equals(GenericArtifact.VALUE_UNKNOWN));

        if (sourceArtifactVersion == null || sourceArtifactVersion.equals(GenericArtifact.VALUE_UNKNOWN)) {
            sourceArtifactVersion = GenericArtifactHelper.ARTIFACT_VERSION_FORCE_RESYNC;
        }

        String sourceArtifactLastModifiedDateStr = XPathUtils.getAttributeValue(element,
                GenericArtifactHelper.SOURCE_ARTIFACT_LAST_MODIFICATION_DATE);

        Date sourceArtifactLastModifiedDate = null;
        if (!sourceArtifactLastModifiedDateStr.equalsIgnoreCase(GenericArtifact.VALUE_UNKNOWN)) {
            sourceArtifactLastModifiedDate = DateUtil.parse(sourceArtifactLastModifiedDateStr);
        }
        // use the earliest date possible
        else
            sourceArtifactLastModifiedDate = new Date(0);

        long sourceArtifactVersionLong = Long.parseLong(sourceArtifactVersion);
        String targetArtifactIdFromTable = null;
        String targetArtifactVersion = null;
        if (sourceArtifactId.equalsIgnoreCase(GenericArtifact.VALUE_UNKNOWN)) {
            return new Object[] { data };
        }

        // find out whether to skip the artifact because it has been
        // quarantined
        if (!replayedArtifact && skipQuarantinedArtifact(element, sourceArtifactId, sourceSystemId,
                sourceRepositoryId, targetSystemId, targetRepositoryId, artifactType,
                sourceArtifactLastModifiedDate, sourceArtifactVersionLong, false)) {
            XPathUtils.addAttribute(element, GenericArtifactHelper.ARTIFACT_ACTION,
                    GenericArtifactHelper.ARTIFACT_ACTION_IGNORE);
            return new Object[] { data };
        }

        Object[] results = lookupTargetArtifact(element, sourceArtifactId, sourceSystemId, sourceRepositoryId,
                targetSystemId, targetRepositoryId, artifactType);

        if (results != null && results.length != 0) {
            targetArtifactIdFromTable = results[0].toString();
            Date sourceArtifactLastModifiedDateFromTable = (Date) results[1];
            String sourceArtifactVersionFromTable = results[2].toString();
            if (sourceArtifactVersionFromTable.equalsIgnoreCase(GenericArtifact.VALUE_UNKNOWN)) {
                sourceArtifactVersionFromTable = GenericArtifactHelper.ARTIFACT_VERSION_FORCE_RESYNC;
            }
            long sourceArtifactVersionLongFromTable = Long.parseLong(sourceArtifactVersionFromTable);
            // if (sourceArtifactLastModifiedDateFromTable
            // .after(sourceArtifactLastModifiedDate)
            // || sourceArtifactVersionLongFromTable >=
            // sourceArtifactVersionLong) {
            if (sourceArtifactVersionLongFromTable >= sourceArtifactVersionLong) {
                if (sourceArtifactVersionLong == -1 && sourceArtifactVersionLongFromTable == -1) {
                    log.warn(
                            "It seems as if artifact synchronization is done exclusively with a system that does not support version control for combination "
                                    + sourceArtifactId + "-" + sourceRepositoryId + "-" + sourceSystemId
                                    + targetRepositoryId + "-" + targetSystemId
                                    + " so artifact will not be skipped.");
                } else {
                    // only skip if this is not an intended artifact resync
                    // obvious resync duplicates are still filtered out.
                    // partial updates are always passed through.
                    if ((!isPartialUpdate || !isAlwaysPassPartialArtifacts())
                            && ((!artifactAction.equals(GenericArtifactHelper.ARTIFACT_ACTION_RESYNC))
                                    || ((sourceArtifactVersionLongFromTable > sourceArtifactVersionLong)
                                            && !isAlwaysPassResynchedArtifacts()))) {
                        log.warn("\nSource artifact last modified date in table "
                                + DateUtil.format(sourceArtifactLastModifiedDateFromTable)
                                + "\nSource artifact last modified date "
                                + DateUtil.format(sourceArtifactLastModifiedDate)
                                + "\nSource artifact version from table " + sourceArtifactVersionLongFromTable
                                + "\nSource artifact version " + sourceArtifactVersionLong);
                        log.warn(
                                "Seems the artifact has already been shipped in newer or same version. Skipped artifact with source artifact id "
                                        + sourceArtifactId + " and version " + sourceArtifactVersion
                                        + " for combination " + sourceArtifactId + "-" + sourceRepositoryId
                                        + "-" + sourceSystemId + targetRepositoryId + "-" + targetSystemId);

                        XPathUtils.addAttribute(element, GenericArtifactHelper.ARTIFACT_ACTION,
                                GenericArtifactHelper.ARTIFACT_ACTION_IGNORE);
                        return new Object[] { data };
                    }
                }
            }
            targetArtifactVersion = results[3].toString();
        }

        if (artifactType.equals(GenericArtifactHelper.ARTIFACT_TYPE_ATTACHMENT)) {
            String sourceParentArtifactId = XPathUtils.getAttributeValue(element,
                    GenericArtifactHelper.DEP_PARENT_SOURCE_ARTIFACT_ID);
            String sourceParentRepositoryId = XPathUtils.getAttributeValue(element,
                    GenericArtifactHelper.DEP_PARENT_SOURCE_REPOSITORY_ID);
            String targetParentRepositoryId = XPathUtils.getAttributeValue(element,
                    GenericArtifactHelper.DEP_PARENT_TARGET_REPOSITORY_ID);
            Object[] resultsDep = lookupTargetArtifact(element, sourceParentArtifactId, sourceSystemId,
                    sourceParentRepositoryId, targetSystemId, targetParentRepositoryId,
                    GenericArtifactHelper.ARTIFACT_TYPE_PLAIN_ARTIFACT);
            String targetParentArtifactId = null;
            if (resultsDep != null && resultsDep[0] != null) {
                targetParentArtifactId = resultsDep[0].toString();
            }
            if (StringUtils.isEmpty(targetParentArtifactId)) {
                if (artifactAction.equals(GenericArtifactHelper.ARTIFACT_ACTION_DELETE)) {
                    String cause = "Parent artifact " + sourceParentArtifactId + " for attachment "
                            + sourceArtifactId + " is not yet created on the target system for combination "
                            + sourceArtifactId + "-" + sourceRepositoryId + "-" + sourceSystemId + "-"
                            + targetRepositoryId + "-" + targetSystemId
                            + ". Since attachment has been marked to be deleted, ignoring the shipment ...";
                    log.warn(cause);
                    XPathUtils.addAttribute(element, GenericArtifactHelper.ARTIFACT_ACTION,
                            GenericArtifactHelper.ARTIFACT_ACTION_IGNORE);
                    return new Object[] { data };
                }
                if (!isOnlyQuarantineAttachmentIfParentInHospital()
                        || skipQuarantinedArtifact(null, sourceParentArtifactId, sourceSystemId,
                                sourceParentRepositoryId, targetSystemId, targetParentRepositoryId,
                                GenericArtifactHelper.ARTIFACT_TYPE_PLAIN_ARTIFACT, null, 0, true)) {
                    String cause = "Parent artifact " + sourceParentArtifactId + " for attachment "
                            + sourceArtifactId + " is not created on the target system for combination "
                            + sourceArtifactId + "-" + sourceRepositoryId + "-" + sourceSystemId + "-"
                            + targetRepositoryId + "-" + targetSystemId;
                    log.error(cause);
                    XPathUtils.addAttribute(element, GenericArtifactHelper.ERROR_CODE,
                            GenericArtifact.ERROR_PARENT_ARTIFACT_NOT_PRESENT);
                    throw new CCFRuntimeException(cause);
                } else {
                    String cause = "Parent artifact " + sourceParentArtifactId + " for attachment "
                            + sourceArtifactId + " is not created on the target system for combination "
                            + sourceArtifactId + "-" + sourceRepositoryId + "-" + sourceSystemId + "-"
                            + targetRepositoryId + "-" + targetSystemId
                            + ". Do not quarantine attachment since parent could not be found in hospital.";
                    log.warn(cause);
                    return null;
                }
            } else {
                XPathUtils.addAttribute(element, GenericArtifactHelper.DEP_PARENT_TARGET_ARTIFACT_ID,
                        targetParentArtifactId);
            }
        } else if (artifactType.equals(GenericArtifactHelper.ARTIFACT_TYPE_PLAIN_ARTIFACT)) {
            // now realize parent artifact lookup for ordinary artifacts
            String sourceParentArtifactId = XPathUtils.getAttributeValue(element,
                    GenericArtifactHelper.DEP_PARENT_SOURCE_ARTIFACT_ID);
            if (sourceParentArtifactId != null
                    && !sourceParentArtifactId.equals(GenericArtifact.VALUE_UNKNOWN)) {
                // looks as if dependency lookup has been required
                if (sourceParentArtifactId.equals(GenericArtifact.VALUE_NONE)) {
                    // none is always mapped to none
                    XPathUtils.addAttribute(element, GenericArtifactHelper.DEP_PARENT_TARGET_ARTIFACT_ID,
                            GenericArtifact.VALUE_NONE);
                } else if (getParentIdentityMappingDatabaseReader() == null) {
                    log.warn(
                            "Seems the artifact required advanced dependency lookup but this feature has not been configured. "
                                    + "Skipped parent lookup for artifact with source artifact id "
                                    + sourceArtifactId + " and version " + sourceArtifactVersion
                                    + " for combination " + sourceArtifactId + "-" + sourceRepositoryId + "-"
                                    + sourceSystemId + "-" + targetRepositoryId + "-" + targetSystemId);
                } else {
                    // do the actual parent id lookup
                    String sourceParentRepositoryId = XPathUtils.getAttributeValue(element,
                            GenericArtifactHelper.DEP_PARENT_SOURCE_REPOSITORY_ID);
                    Object[] resultsDep = lookupParentTargetArtifact(element, sourceParentArtifactId,
                            sourceSystemId, sourceParentRepositoryId, targetSystemId,
                            GenericArtifactHelper.ARTIFACT_TYPE_PLAIN_ARTIFACT);
                    String targetParentArtifactId = null;
                    String targetParentRepositoryId = null;
                    if (resultsDep != null && resultsDep[0] != null) {
                        targetParentArtifactId = resultsDep[0].toString();
                    }
                    if (resultsDep != null && resultsDep[4] != null) {
                        targetParentRepositoryId = resultsDep[4].toString();
                    }
                    if (StringUtils.isEmpty(targetParentArtifactId)
                            || StringUtils.isEmpty(targetParentRepositoryId)) {
                        if (getProjectMappingDatabaseReader() != null) {
                            // if it turns out that the repository the
                            // parent artifact belongs to is not mapped at
                            // all,
                            // we will proceed with a warning
                            if (!projectMappingExists(sourceSystemId, targetSystemId,
                                    sourceParentRepositoryId)) {
                                String cause = "Parent artifact " + sourceParentArtifactId + " for artifact "
                                        + sourceArtifactId
                                        + " is not yet created on the target system for combination "
                                        + sourceArtifactId + "-" + sourceRepositoryId + "-" + sourceSystemId
                                        + "-" + targetRepositoryId + "-" + targetSystemId
                                        + ". Since no project mapping exists for " + sourceParentRepositoryId
                                        + " CCF does not bail out but ignores parent dependency.";
                                log.warn(cause);
                            } else if (artifactAction.equals(GenericArtifactHelper.ARTIFACT_ACTION_DELETE)) {
                                String cause = "Parent artifact " + sourceParentArtifactId + " for artifact "
                                        + sourceArtifactId
                                        + " is not yet created on the target system for combination "
                                        + sourceArtifactId + "-" + sourceRepositoryId + "-" + sourceSystemId
                                        + "-" + targetRepositoryId + "-" + targetSystemId
                                        + ". Since artifact has been marked to be deleted, ignoring the shipment ...";
                                log.warn(cause);
                                XPathUtils.addAttribute(element, GenericArtifactHelper.ARTIFACT_ACTION,
                                        GenericArtifactHelper.ARTIFACT_ACTION_IGNORE);
                                return new Object[] { data };
                            } else {
                                String cause = "Parent artifact " + sourceParentArtifactId + " for artifact "
                                        + sourceArtifactId
                                        + " is not yet created on the target system for combination "
                                        + sourceArtifactId + "-" + sourceRepositoryId + "-" + sourceSystemId
                                        + "-" + targetRepositoryId + "-" + targetSystemId
                                        + ". Since a project mapping exists for " + sourceParentRepositoryId
                                        + " CCF bails out now.";
                                log.warn(cause);
                                XPathUtils.addAttribute(element, GenericArtifactHelper.ERROR_CODE,
                                        GenericArtifact.ERROR_PARENT_ARTIFACT_NOT_PRESENT);
                                throw new CCFRuntimeException(cause);
                            }
                        } else {
                            String cause = "Parent artifact " + sourceParentArtifactId + " for artifact "
                                    + sourceArtifactId
                                    + " is not yet created on the target system for combination "
                                    + sourceArtifactId + "-" + sourceRepositoryId + "-" + sourceSystemId + "-"
                                    + targetRepositoryId + "-" + targetSystemId
                                    + ". Since projectMappingDatabaseReader property has not been set"
                                    + "CCF does not know whether a project mapping for "
                                    + sourceParentRepositoryId + "exists and bails out.";
                            log.warn(cause);
                            XPathUtils.addAttribute(element, GenericArtifactHelper.ERROR_CODE,
                                    GenericArtifact.ERROR_PARENT_ARTIFACT_NOT_PRESENT);
                            throw new CCFRuntimeException(cause);
                        }
                    } else {
                        XPathUtils.addAttribute(element, GenericArtifactHelper.DEP_PARENT_TARGET_ARTIFACT_ID,
                                targetParentArtifactId);
                        XPathUtils.addAttribute(element, GenericArtifactHelper.DEP_PARENT_TARGET_REPOSITORY_ID,
                                targetParentRepositoryId);
                    }
                }
            }
        }

        if (targetArtifactIdFromTable != null) {
            XPathUtils.addAttribute(element, GenericArtifactHelper.TARGET_ARTIFACT_ID,
                    targetArtifactIdFromTable);
            XPathUtils.addAttribute(element, GenericArtifactHelper.TARGET_ARTIFACT_VERSION,
                    targetArtifactVersion);
            if (artifactAction.equals(GenericArtifactHelper.ARTIFACT_ACTION_UNKNOWN)) {
                XPathUtils.addAttribute(element, GenericArtifactHelper.ARTIFACT_ACTION,
                        GenericArtifactHelper.ARTIFACT_ACTION_UPDATE);
            } else if (artifactAction.equals(GenericArtifactHelper.ARTIFACT_ACTION_CREATE)) {
                String cause = "The artifact action is marked as " + artifactAction
                        + ".\nBut the Entity Service found a target artifact id " + targetArtifactIdFromTable
                        + " for source artifact id " + sourceArtifactId;
                log.warn(cause);
                XPathUtils.addAttribute(element, GenericArtifactHelper.ARTIFACT_ACTION,
                        GenericArtifactHelper.ARTIFACT_ACTION_UPDATE);
            }
        } else {
            if (artifactAction.equals(GenericArtifactHelper.ARTIFACT_ACTION_UNKNOWN)) {
                XPathUtils.addAttribute(element, GenericArtifactHelper.ARTIFACT_ACTION,
                        GenericArtifactHelper.ARTIFACT_ACTION_CREATE);
            } else if (artifactAction.equals(GenericArtifactHelper.ARTIFACT_ACTION_UPDATE)) {
                String cause = "The artifact action is marked as " + artifactAction
                        + ".\nBut the Entity Service could not find a target artifact id for source artifact id "
                        + sourceArtifactId + ". Marking the artifact to create";
                log.warn(cause);
                XPathUtils.addAttribute(element, GenericArtifactHelper.ARTIFACT_ACTION,
                        GenericArtifactHelper.ARTIFACT_ACTION_CREATE);
            } else if (artifactAction.equals(GenericArtifactHelper.ARTIFACT_ACTION_DELETE)) {
                String cause = "The artifact action is marked as " + artifactAction
                        + ".\nBut the Entity Service could not find a target artifact id for source artifact id "
                        + sourceArtifactId + ". Ignoring the artifact ...";
                log.warn(cause);
                XPathUtils.addAttribute(element, GenericArtifactHelper.ARTIFACT_ACTION,
                        GenericArtifactHelper.ARTIFACT_ACTION_IGNORE);
                return new Object[] { data };
            } else if (artifactAction.equals(GenericArtifactHelper.ARTIFACT_ACTION_RESYNC)) {
                String cause = "The artifact action is marked as " + artifactAction
                        + ".\nBut the Entity Service could not find a target artifact id for source artifact id "
                        + sourceArtifactId + ". Discarding the artifact.";
                log.warn(cause);
                XPathUtils.addAttribute(element, GenericArtifactHelper.ARTIFACT_ACTION,
                        GenericArtifactHelper.ARTIFACT_ACTION_IGNORE);
                return new Object[] { data };
            }
        }
    } catch (GenericArtifactParsingException e) {
        String cause = "Problem occured while parsing the Document to extract specific attributes";
        log.error(cause, e);
        XPathUtils.addAttribute(data.getRootElement(), GenericArtifactHelper.ERROR_CODE,
                GenericArtifact.ERROR_GENERIC_ARTIFACT_PARSING);
        throw new CCFRuntimeException(cause, e);
    }

    Object[] result = { data };
    return result;
}

From source file:com.collabnet.ccf.core.EntityService2.java

License:Open Source License

/**
 * Main method to handle the mapping and filtering of source artifacts to
 * target repository artifact items Also include the quarantined artifact
 * lookup code/*from  ww  w  .j av a 2 s. c  o  m*/
 * 
 * @param data
 *            input XML document in generic XML artifact format
 * @return array of generated XML documents compliant to generic XML
 *         artifact schema
 */
private Object[] processXMLDocument(Document data) {
    Element element = null;
    try {
        element = XPathUtils.getRootElement(data);
        String artifactAction = XPathUtils.getAttributeValue(element, GenericArtifactHelper.ARTIFACT_ACTION);
        if (artifactAction.equals(GenericArtifactHelper.ARTIFACT_ACTION_IGNORE)) {
            return new Object[] { data };
        }

        /*
         * CCF 2.x needs an id for the repository mapping and for the
         * repository mapping direction Those are stored in the source
         * system kind and target system kind top level attributes. These
         * top level attributes have not been used in CCF 1.x but have
         * already been mapped so that CCF 1.x mappings will continue to
         * work with CCF 2.x without any modifications.
         */
        // FIXME Do we have to parse these ids before passing them to the DB layer?
        String repositoryMappingDirectionId = XPathUtils.getAttributeValue(element,
                GenericArtifactHelper.SOURCE_SYSTEM_KIND);
        String repositoryMappingId = XPathUtils.getAttributeValue(element,
                GenericArtifactHelper.TARGET_SYSTEM_KIND);

        // get top level attributes
        String artifactType = XPathUtils.getAttributeValue(element, GenericArtifactHelper.ARTIFACT_TYPE);
        String sourceArtifactId = XPathUtils.getAttributeValue(element,
                GenericArtifactHelper.SOURCE_ARTIFACT_ID);
        String sourceSystemId = XPathUtils.getAttributeValue(element, GenericArtifactHelper.SOURCE_SYSTEM_ID);
        String sourceRepositoryId = XPathUtils.getAttributeValue(element,
                GenericArtifactHelper.SOURCE_REPOSITORY_ID);
        String targetSystemId = XPathUtils.getAttributeValue(element, GenericArtifactHelper.TARGET_SYSTEM_ID);
        String targetRepositoryId = XPathUtils.getAttributeValue(element,
                GenericArtifactHelper.TARGET_REPOSITORY_ID);
        String sourceArtifactVersion = XPathUtils.getAttributeValue(element,
                GenericArtifactHelper.SOURCE_ARTIFACT_VERSION);
        String transactionId = XPathUtils.getAttributeValue(element, GenericArtifactHelper.TRANSACTION_ID);
        String artifactMode = XPathUtils.getAttributeValue(element, GenericArtifactHelper.ARTIFACT_MODE);
        boolean isPartialUpdate = GenericArtifactHelper.ARTIFACT_MODE_CHANGED_FIELDS_ONLY.equals(artifactMode);

        boolean replayedArtifact = (transactionId != null
                && !transactionId.equals(GenericArtifact.VALUE_UNKNOWN));

        if (sourceArtifactVersion == null || sourceArtifactVersion.equals(GenericArtifact.VALUE_UNKNOWN)) {
            sourceArtifactVersion = GenericArtifactHelper.ARTIFACT_VERSION_FORCE_RESYNC;
        }

        String sourceArtifactLastModifiedDateStr = XPathUtils.getAttributeValue(element,
                GenericArtifactHelper.SOURCE_ARTIFACT_LAST_MODIFICATION_DATE);

        Date sourceArtifactLastModifiedDate = null;
        if (!sourceArtifactLastModifiedDateStr.equalsIgnoreCase(GenericArtifact.VALUE_UNKNOWN)) {
            sourceArtifactLastModifiedDate = DateUtil.parse(sourceArtifactLastModifiedDateStr);
        }
        // use the earliest date possible
        else
            sourceArtifactLastModifiedDate = new Date(0);

        long sourceArtifactVersionLong = Long.parseLong(sourceArtifactVersion);
        String targetArtifactIdFromTable = null;
        String targetArtifactVersion = null;
        if (sourceArtifactId.equalsIgnoreCase(GenericArtifact.VALUE_UNKNOWN)) {
            return new Object[] { data };
        }

        // find out whether to skip the artifact because it has been
        // quarantined
        if (!replayedArtifact
                && skipQuarantinedArtifact(element, sourceArtifactId, sourceSystemId, sourceRepositoryId,
                        targetSystemId, targetRepositoryId, artifactType, sourceArtifactLastModifiedDate,
                        sourceArtifactVersionLong, false, repositoryMappingDirectionId)) {
            XPathUtils.addAttribute(element, GenericArtifactHelper.ARTIFACT_ACTION,
                    GenericArtifactHelper.ARTIFACT_ACTION_IGNORE);
            return new Object[] { data };
        }

        if (rmdDryModeHandler.isDryRunEqualsBeforeTransformation(repositoryMappingDirectionId)) {
            String cause = "Storing in hospital as dryrun mode is enabled for the repository mapping direction id: "
                    + repositoryMappingDirectionId;
            XPathUtils.addAttribute(element, GenericArtifactHelper.ERROR_CODE,
                    GenericArtifact.ERROR_IN_DRY_RUN_MODE);
            log.warn(cause);
            throw new CCFRuntimeException(cause);
        }

        Object[] results = lookupTargetArtifact(element, sourceArtifactId, sourceSystemId, sourceRepositoryId,
                targetSystemId, targetRepositoryId, artifactType, repositoryMappingId);

        if (results != null && results.length != 0) {
            targetArtifactIdFromTable = results[0].toString();
            Date sourceArtifactLastModifiedDateFromTable = (Date) results[1];
            String sourceArtifactVersionFromTable = results[2].toString();
            if (sourceArtifactVersionFromTable.equalsIgnoreCase(GenericArtifact.VALUE_UNKNOWN)) {
                sourceArtifactVersionFromTable = GenericArtifactHelper.ARTIFACT_VERSION_FORCE_RESYNC;
            }
            long sourceArtifactVersionLongFromTable = Long.parseLong(sourceArtifactVersionFromTable);
            // if (sourceArtifactLastModifiedDateFromTable
            // .after(sourceArtifactLastModifiedDate)
            // || sourceArtifactVersionLongFromTable >=
            // sourceArtifactVersionLong) {
            if (sourceArtifactVersionLongFromTable >= sourceArtifactVersionLong) {
                if (sourceArtifactVersionLong == -1 && sourceArtifactVersionLongFromTable == -1) {
                    log.warn(
                            "It seems as if artifact synchronization is done exclusively with a system that does not support version control for combination "
                                    + sourceArtifactId + "-" + sourceRepositoryId + "-" + sourceSystemId
                                    + targetRepositoryId + "-" + targetSystemId
                                    + " so artifact will not be skipped.");
                } else {
                    // only skip if this is not an intended artifact resync
                    // obvious resync duplicates are still filtered out.
                    // partial updates are always passed through.
                    if ((!isPartialUpdate || !isAlwaysPassPartialArtifacts())
                            && ((!artifactAction.equals(GenericArtifactHelper.ARTIFACT_ACTION_RESYNC))
                                    || ((sourceArtifactVersionLongFromTable > sourceArtifactVersionLong)
                                            && !isAlwaysPassResynchedArtifacts()))) {
                        log.warn("\nSource artifact last modified date in table "
                                + DateUtil.format(sourceArtifactLastModifiedDateFromTable)
                                + "\nSource artifact last modified date "
                                + DateUtil.format(sourceArtifactLastModifiedDate)
                                + "\nSource artifact version from table " + sourceArtifactVersionLongFromTable
                                + "\nSource artifact version " + sourceArtifactVersionLong);
                        log.warn(
                                "Seems the artifact has already been shipped in newer or same version. Skipped artifact with source artifact id "
                                        + sourceArtifactId + " and version " + sourceArtifactVersion
                                        + " for combination " + sourceArtifactId + "-" + sourceRepositoryId
                                        + "-" + sourceSystemId + targetRepositoryId + "-" + targetSystemId);

                        XPathUtils.addAttribute(element, GenericArtifactHelper.ARTIFACT_ACTION,
                                GenericArtifactHelper.ARTIFACT_ACTION_IGNORE);
                        return new Object[] { data };
                    }
                }
            }
            targetArtifactVersion = results[3].toString();
        }

        if (artifactType.equals(GenericArtifactHelper.ARTIFACT_TYPE_ATTACHMENT)) {
            String sourceParentArtifactId = XPathUtils.getAttributeValue(element,
                    GenericArtifactHelper.DEP_PARENT_SOURCE_ARTIFACT_ID);
            String sourceParentRepositoryId = XPathUtils.getAttributeValue(element,
                    GenericArtifactHelper.DEP_PARENT_SOURCE_REPOSITORY_ID);
            String targetParentRepositoryId = XPathUtils.getAttributeValue(element,
                    GenericArtifactHelper.DEP_PARENT_TARGET_REPOSITORY_ID);
            Object[] resultsDep = lookupTargetArtifact(element, sourceParentArtifactId, sourceSystemId,
                    sourceParentRepositoryId, targetSystemId, targetParentRepositoryId,
                    GenericArtifactHelper.ARTIFACT_TYPE_PLAIN_ARTIFACT, repositoryMappingId);
            String targetParentArtifactId = null;
            if (resultsDep != null && resultsDep[0] != null) {
                targetParentArtifactId = resultsDep[0].toString();
            }
            if (StringUtils.isEmpty(targetParentArtifactId)) {
                if (artifactAction.equals(GenericArtifactHelper.ARTIFACT_ACTION_DELETE)) {
                    String cause = "Parent artifact " + sourceParentArtifactId + " for attachment "
                            + sourceArtifactId + " is not yet created on the target system for combination "
                            + sourceArtifactId + "-" + sourceRepositoryId + "-" + sourceSystemId + "-"
                            + targetRepositoryId + "-" + targetSystemId
                            + ". Since attachment has been marked to be deleted, ignoring the shipment ...";
                    log.warn(cause);
                    XPathUtils.addAttribute(element, GenericArtifactHelper.ARTIFACT_ACTION,
                            GenericArtifactHelper.ARTIFACT_ACTION_IGNORE);
                    return new Object[] { data };
                }
                if (!isOnlyQuarantineAttachmentIfParentInHospital() || skipQuarantinedArtifact(null,
                        sourceParentArtifactId, sourceSystemId, sourceParentRepositoryId, targetSystemId,
                        targetParentRepositoryId, GenericArtifactHelper.ARTIFACT_TYPE_PLAIN_ARTIFACT, null, 0,
                        true, repositoryMappingDirectionId)) {
                    String cause = "Parent artifact " + sourceParentArtifactId + " for attachment "
                            + sourceArtifactId + " is not created on the target system for combination "
                            + sourceArtifactId + "-" + sourceRepositoryId + "-" + sourceSystemId + "-"
                            + targetRepositoryId + "-" + targetSystemId;
                    log.error(cause);
                    XPathUtils.addAttribute(element, GenericArtifactHelper.ERROR_CODE,
                            GenericArtifact.ERROR_PARENT_ARTIFACT_NOT_PRESENT);
                    throw new CCFRuntimeException(cause);
                } else {
                    String cause = "Parent artifact " + sourceParentArtifactId + " for attachment "
                            + sourceArtifactId + " is not created on the target system for combination "
                            + sourceArtifactId + "-" + sourceRepositoryId + "-" + sourceSystemId + "-"
                            + targetRepositoryId + "-" + targetSystemId
                            + ". Do not quarantine attachment since parent could not be found in hospital.";
                    log.warn(cause);
                    return null;
                }
            } else {
                XPathUtils.addAttribute(element, GenericArtifactHelper.DEP_PARENT_TARGET_ARTIFACT_ID,
                        targetParentArtifactId);
            }
        } else if (artifactType.equals(GenericArtifactHelper.ARTIFACT_TYPE_PLAIN_ARTIFACT)) {
            // now realize parent artifact lookup for ordinary artifacts
            String sourceParentArtifactId = XPathUtils.getAttributeValue(element,
                    GenericArtifactHelper.DEP_PARENT_SOURCE_ARTIFACT_ID);
            if (sourceParentArtifactId != null
                    && !sourceParentArtifactId.equals(GenericArtifact.VALUE_UNKNOWN)) {
                // looks as if dependency lookup has been required
                if (sourceParentArtifactId.equals(GenericArtifact.VALUE_NONE)) {
                    // none is always mapped to none
                    XPathUtils.addAttribute(element, GenericArtifactHelper.DEP_PARENT_TARGET_ARTIFACT_ID,
                            GenericArtifact.VALUE_NONE);
                } else if (getParentIdentityMappingDatabaseReader() == null) {
                    log.warn(
                            "Seems the artifact required advanced dependency lookup but this feature has not been configured. "
                                    + "Skipped parent lookup for artifact with source artifact id "
                                    + sourceArtifactId + " and version " + sourceArtifactVersion
                                    + " for combination " + sourceArtifactId + "-" + sourceRepositoryId + "-"
                                    + sourceSystemId + "-" + targetRepositoryId + "-" + targetSystemId);
                } else {
                    // do the actual parent id lookup
                    String sourceParentRepositoryId = XPathUtils.getAttributeValue(element,
                            GenericArtifactHelper.DEP_PARENT_SOURCE_REPOSITORY_ID);
                    Object[] resultsDep = lookupParentTargetArtifact(element, sourceParentArtifactId,
                            sourceSystemId, sourceParentRepositoryId, targetSystemId,
                            GenericArtifactHelper.ARTIFACT_TYPE_PLAIN_ARTIFACT);
                    String targetParentArtifactId = null;
                    String targetParentRepositoryId = null;
                    if (resultsDep != null && resultsDep[0] != null) {
                        targetParentArtifactId = resultsDep[0].toString();
                    }
                    if (resultsDep != null && resultsDep[4] != null) {
                        targetParentRepositoryId = resultsDep[4].toString();
                    }
                    if (StringUtils.isEmpty(targetParentArtifactId)
                            || StringUtils.isEmpty(targetParentRepositoryId)) {
                        if (getProjectMappingDatabaseReader() != null) {
                            // if it turns out that the repository the
                            // parent artifact belongs to is not mapped at
                            // all,
                            // we will proceed with a warning
                            if (!projectMappingExists(sourceSystemId, targetSystemId,
                                    sourceParentRepositoryId)) {
                                String cause = "Parent artifact " + sourceParentArtifactId + " for artifact "
                                        + sourceArtifactId
                                        + " is not yet created on the target system for combination "
                                        + sourceArtifactId + "-" + sourceRepositoryId + "-" + sourceSystemId
                                        + "-" + targetRepositoryId + "-" + targetSystemId
                                        + ". Since no project mapping exists for " + sourceParentRepositoryId
                                        + " CCF does not bail out but ignores parent dependency.";
                                log.warn(cause);
                            } else if (artifactAction.equals(GenericArtifactHelper.ARTIFACT_ACTION_DELETE)) {
                                String cause = "Parent artifact " + sourceParentArtifactId + " for artifact "
                                        + sourceArtifactId
                                        + " is not yet created on the target system for combination "
                                        + sourceArtifactId + "-" + sourceRepositoryId + "-" + sourceSystemId
                                        + "-" + targetRepositoryId + "-" + targetSystemId
                                        + ". Since artifact has been marked to be deleted, ignoring the shipment ...";
                                log.warn(cause);
                                XPathUtils.addAttribute(element, GenericArtifactHelper.ARTIFACT_ACTION,
                                        GenericArtifactHelper.ARTIFACT_ACTION_IGNORE);
                                return new Object[] { data };
                            } else {
                                String cause = "Parent artifact " + sourceParentArtifactId + " for artifact "
                                        + sourceArtifactId
                                        + " is not yet created on the target system for combination "
                                        + sourceArtifactId + "-" + sourceRepositoryId + "-" + sourceSystemId
                                        + "-" + targetRepositoryId + "-" + targetSystemId
                                        + ". Since a project mapping exists for " + sourceParentRepositoryId
                                        + " CCF bails out now.";
                                log.warn(cause);
                                XPathUtils.addAttribute(element, GenericArtifactHelper.ERROR_CODE,
                                        GenericArtifact.ERROR_PARENT_ARTIFACT_NOT_PRESENT);
                                throw new CCFRuntimeException(cause);
                            }
                        } else {
                            String cause = "Parent artifact " + sourceParentArtifactId + " for artifact "
                                    + sourceArtifactId
                                    + " is not yet created on the target system for combination "
                                    + sourceArtifactId + "-" + sourceRepositoryId + "-" + sourceSystemId + "-"
                                    + targetRepositoryId + "-" + targetSystemId
                                    + ". Since projectMappingDatabaseReader property has not been set"
                                    + "CCF does not know whether a project mapping for "
                                    + sourceParentRepositoryId + "exists and bails out.";
                            log.warn(cause);
                            XPathUtils.addAttribute(element, GenericArtifactHelper.ERROR_CODE,
                                    GenericArtifact.ERROR_PARENT_ARTIFACT_NOT_PRESENT);
                            throw new CCFRuntimeException(cause);
                        }
                    } else {
                        XPathUtils.addAttribute(element, GenericArtifactHelper.DEP_PARENT_TARGET_ARTIFACT_ID,
                                targetParentArtifactId);
                        XPathUtils.addAttribute(element, GenericArtifactHelper.DEP_PARENT_TARGET_REPOSITORY_ID,
                                targetParentRepositoryId);
                    }
                }
            }
        }

        if (targetArtifactIdFromTable != null) {
            XPathUtils.addAttribute(element, GenericArtifactHelper.TARGET_ARTIFACT_ID,
                    targetArtifactIdFromTable);
            XPathUtils.addAttribute(element, GenericArtifactHelper.TARGET_ARTIFACT_VERSION,
                    targetArtifactVersion);
            if (artifactAction.equals(GenericArtifactHelper.ARTIFACT_ACTION_UNKNOWN)) {
                XPathUtils.addAttribute(element, GenericArtifactHelper.ARTIFACT_ACTION,
                        GenericArtifactHelper.ARTIFACT_ACTION_UPDATE);
            } else if (artifactAction.equals(GenericArtifactHelper.ARTIFACT_ACTION_CREATE)) {
                String cause = "The artifact action is marked as " + artifactAction
                        + ".\nBut the Entity Service found a target artifact id " + targetArtifactIdFromTable
                        + " for source artifact id " + sourceArtifactId;
                log.warn(cause);
                XPathUtils.addAttribute(element, GenericArtifactHelper.ARTIFACT_ACTION,
                        GenericArtifactHelper.ARTIFACT_ACTION_UPDATE);
            }
        } else {
            if (artifactAction.equals(GenericArtifactHelper.ARTIFACT_ACTION_UNKNOWN)) {
                XPathUtils.addAttribute(element, GenericArtifactHelper.ARTIFACT_ACTION,
                        GenericArtifactHelper.ARTIFACT_ACTION_CREATE);
            } else if (artifactAction.equals(GenericArtifactHelper.ARTIFACT_ACTION_UPDATE)) {
                String cause = "The artifact action is marked as " + artifactAction
                        + ".\nBut the Entity Service could not find a target artifact id for source artifact id "
                        + sourceArtifactId + ". Marking the artifact to create";
                log.warn(cause);
                XPathUtils.addAttribute(element, GenericArtifactHelper.ARTIFACT_ACTION,
                        GenericArtifactHelper.ARTIFACT_ACTION_CREATE);
            } else if (artifactAction.equals(GenericArtifactHelper.ARTIFACT_ACTION_DELETE)) {
                String cause = "The artifact action is marked as " + artifactAction
                        + ".\nBut the Entity Service could not find a target artifact id for source artifact id "
                        + sourceArtifactId + ". Ignoring the artifact ...";
                log.warn(cause);
                XPathUtils.addAttribute(element, GenericArtifactHelper.ARTIFACT_ACTION,
                        GenericArtifactHelper.ARTIFACT_ACTION_IGNORE);
                return new Object[] { data };
            } else if (artifactAction.equals(GenericArtifactHelper.ARTIFACT_ACTION_RESYNC)) {
                String cause = "The artifact action is marked as " + artifactAction
                        + ".\nBut the Entity Service could not find a target artifact id for source artifact id "
                        + sourceArtifactId + ". Discarding the artifact.";
                log.warn(cause);
                XPathUtils.addAttribute(element, GenericArtifactHelper.ARTIFACT_ACTION,
                        GenericArtifactHelper.ARTIFACT_ACTION_IGNORE);
                return new Object[] { data };
            }
        }
    } catch (GenericArtifactParsingException e) {
        String cause = "Problem occured while parsing the Document to extract specific attributes";
        log.error(cause, e);
        XPathUtils.addAttribute(data.getRootElement(), GenericArtifactHelper.ERROR_CODE,
                GenericArtifact.ERROR_GENERIC_ARTIFACT_PARSING);
        throw new CCFRuntimeException(cause, e);
    }

    Object[] result = { data };
    return result;
}

From source file:com.collabnet.ccf.core.ga.GenericArtifactHelper.java

License:Open Source License

/**
 * Extracts the artifact-root-element out of a Dom4J XML document
 * //  w w w  . java2  s.com
 * @param document
 *            XML document in question
 * @return generic artifact root-element
 * @throws GenericArtifactParsingException
 *             thrown if document is not compliant to the generic artifact
 *             schema
 */
private static Element getRootElement(Document document) throws GenericArtifactParsingException {
    Element rootElement = document.getRootElement();
    if (!ARTIFACT_ROOT_ELEMENT_NAME.equals(rootElement.getName()))
        throw new GenericArtifactParsingException("Root-element of XML document is not named "
                + ARTIFACT_ROOT_ELEMENT_NAME + "but " + rootElement.getName());
    if (!CCF_ARTIFACT_NAMESPACE.equals(rootElement.getNamespaceURI()))
        throw new GenericArtifactParsingException("Namespace-URI of root-element of XML document is not named "
                + CCF_ARTIFACT_NAMESPACE + "but " + rootElement.getNamespaceURI());
    return rootElement;
}

From source file:com.collabnet.ccf.core.hospital.CCFExceptionToOrderedMapConvertor.java

License:Open Source License

/**
 * Converts the <code>record</code> into an <code>IOrderedMap</code> .
 * /*from   www.  ja v  a2s .c  om*/
 * @param record
 *            Object which should be a MessageException instance
 * @return an IOrderedMap representation of the MessageException contents
 */
protected Object convert(Object record) {
    try {
        boolean quarantineException = true;

        // we have to set these columns due to an SQL incompatibility issue
        // with
        // these fields
        setFixedColName(FIXED);
        setReprocessedColName(REPROCESSED);

        // log.warn("Artifact reached ambulance");
        // first of all we pass the record in our parent method
        Object preprocessedMap = super.convert(record);
        if (preprocessedMap == null || (!(preprocessedMap instanceof IOrderedMap))) {
            return preprocessedMap;
        }
        IOrderedMap map = (IOrderedMap) preprocessedMap;

        // remove entities with wrong data type (string instead of boolean)
        map.remove(FIXED);
        map.remove(REPROCESSED);

        map.put(FIXED, false);
        map.put(REPROCESSED, false);

        MessageException messageException = (MessageException) record;
        map.put(exceptionMessageColName, messageException.getException().getMessage());

        Throwable cause = messageException.getException().getCause();
        if (cause != null) {
            map.put(causeExceptionClassColName, cause.getClass().getName());
            map.put(causeExceptionMessageColName, cause.getMessage());
        } else {
            map.put(causeExceptionClassColName, NO_CAUSE_EXCEPTION);
            map.put(causeExceptionMessageColName, NO_CAUSE_EXCEPTION);
        }

        Exception exception = messageException.getException();
        StringBuffer stackTraceBuf = new StringBuffer();
        StackTraceElement[] stackTrace = exception.getStackTrace();
        for (int i = 0; i < stackTrace.length; i++) {
            stackTraceBuf.append(stackTrace[i]);
            stackTraceBuf.append("\n");
        }
        /* Append cause exception stack trace */
        if (cause != null) {
            stackTraceBuf.append("\n\n");
            stackTrace = cause.getStackTrace();
            for (int i = 0; i < stackTrace.length; i++) {
                stackTraceBuf.append(stackTrace[i]);
                stackTraceBuf.append("\n");
            }
        }
        map.put(stackTraceColName, stackTraceBuf.toString());

        String adaptorName = null == adaptor ? "Unknown" : adaptor.getId();
        map.put(adaptorColName, adaptorName);

        Object data = messageException.getData();
        String dataType = null;
        if (data != null) {
            dataType = data.getClass().getName();
        }
        map.put(dataTypeColName, dataType);
        Element element = null;
        Document dataDoc = null;
        if (data instanceof Document) {
            dataDoc = (Document) data;
            element = dataDoc.getRootElement();
        }
        if (element != null) {
            try {
                GenericArtifact ga = GenericArtifactHelper.createGenericArtifactJavaObject(dataDoc);

                String sourceArtifactId = ga.getSourceArtifactId();
                String sourceSystemId = ga.getSourceSystemId();
                String sourceSystemKind = ga.getSourceSystemKind();
                String sourceRepositoryId = ga.getSourceRepositoryId();
                String sourceRepositoryKind = ga.getSourceRepositoryKind();

                String targetArtifactId = ga.getTargetArtifactId();
                String targetSystemId = ga.getTargetSystemId();
                String targetSystemKind = ga.getTargetSystemKind();
                String targetRepositoryId = ga.getTargetRepositoryId();
                String targetRepositoryKind = ga.getTargetRepositoryKind();

                String artifactErrorCode = ga.getErrorCode();

                String sourceArtifactLastModifiedDateString = ga.getSourceArtifactLastModifiedDate();
                String targetArtifactLastModifiedDateString = ga.getTargetArtifactLastModifiedDate();
                String sourceArtifactVersion = ga.getSourceArtifactVersion();
                String targetArtifactVersion = ga.getTargetArtifactVersion();

                String artifactType = XPathUtils.getAttributeValue(element,
                        GenericArtifactHelper.ARTIFACT_TYPE);

                Date sourceLastModifiedDate = null;
                if (!sourceArtifactLastModifiedDateString.equalsIgnoreCase(GenericArtifact.VALUE_UNKNOWN)) {
                    sourceLastModifiedDate = DateUtil.parse(sourceArtifactLastModifiedDateString);
                } else {
                    // use the earliest date possible
                    sourceLastModifiedDate = new Date(0);
                }
                if (sourceLastModifiedDate == null) {
                    sourceLastModifiedDate = new Date(0);
                }
                java.sql.Timestamp sourceTime = new Timestamp(sourceLastModifiedDate.getTime());

                java.util.Date targetLastModifiedDate = null;
                if (!targetArtifactLastModifiedDateString.equalsIgnoreCase(GenericArtifact.VALUE_UNKNOWN)) {
                    targetLastModifiedDate = DateUtil.parse(targetArtifactLastModifiedDateString);
                } else {
                    // use the earliest date possible
                    targetLastModifiedDate = new Date(0);
                }
                java.sql.Timestamp targetTime = new Timestamp(targetLastModifiedDate.getTime());

                // TODO Should we allow to set different column names for
                // these
                // properties?
                map.put(SOURCE_SYSTEM_ID, sourceSystemId);
                map.put(SOURCE_REPOSITORY_ID, sourceRepositoryId);
                map.put(TARGET_SYSTEM_ID, targetSystemId);
                map.put(TARGET_REPOSITORY_ID, targetRepositoryId);
                map.put(SOURCE_SYSTEM_KIND, sourceSystemKind);
                map.put(SOURCE_REPOSITORY_KIND, sourceRepositoryKind);
                map.put(TARGET_SYSTEM_KIND, targetSystemKind);
                map.put(TARGET_REPOSITORY_KIND, targetRepositoryKind);
                map.put(SOURCE_ARTIFACT_ID, sourceArtifactId);
                map.put(TARGET_ARTIFACT_ID, targetArtifactId);
                map.put(ERROR_CODE, artifactErrorCode);
                map.put(SOURCE_LAST_MODIFICATION_TIME, sourceTime);
                map.put(TARGET_LAST_MODIFICATION_TIME, targetTime);
                map.put(SOURCE_ARTIFACT_VERSION, sourceArtifactVersion);
                map.put(TARGET_ARTIFACT_VERSION, targetArtifactVersion);
                map.put(ARTIFACT_TYPE, artifactType);
                //log.info("Removing invalid XML characters if any before we proceed ...");
                map.put(GENERICARTIFACT, removeInvalidXmlCharacters(dataDoc.asXML()));

                // these attributes will be considered for CCF 2.x only
                map.put(DESCRIPTION, "This hospital entry has been inserted by CCF Core.");
                map.put(REPOSITORY_MAPPING_DIRECTION, sourceSystemKind);
                map.put(VERSION, 0);

            } catch (GenericArtifactParsingException e) {
                // log
                // .warn(
                // "The data that reached the hospital is not a valid Generic Artifact"
                // );
                if (isOnlyQuarantineGenericArtifacts()) {
                    quarantineException = false;
                }
                map.put(SOURCE_SYSTEM_ID, null);
                map.put(SOURCE_REPOSITORY_ID, null);
                map.put(TARGET_SYSTEM_ID, null);
                map.put(TARGET_REPOSITORY_ID, null);
                map.put(SOURCE_SYSTEM_KIND, null);
                map.put(SOURCE_REPOSITORY_KIND, null);
                map.put(TARGET_SYSTEM_KIND, null);
                map.put(TARGET_REPOSITORY_KIND, null);
                map.put(SOURCE_ARTIFACT_ID, null);
                map.put(TARGET_ARTIFACT_ID, null);
                //log.info("Removing invalid XML characters if any before we proceed ...");
                map.put(GENERICARTIFACT, removeInvalidXmlCharacters(dataDoc.asXML()));
                map.put(ERROR_CODE, null);
                map.put(SOURCE_LAST_MODIFICATION_TIME, null);
                map.put(TARGET_LAST_MODIFICATION_TIME, null);
                map.put(SOURCE_ARTIFACT_VERSION, null);
                map.put(TARGET_ARTIFACT_VERSION, null);
                map.put(ARTIFACT_TYPE, null);
            }
        } else {
            if (isOnlyQuarantineGenericArtifacts()) {
                quarantineException = false;
            }
            map.put(SOURCE_SYSTEM_ID, null);
            map.put(SOURCE_REPOSITORY_ID, null);
            map.put(TARGET_SYSTEM_ID, null);
            map.put(TARGET_REPOSITORY_ID, null);
            map.put(SOURCE_SYSTEM_KIND, null);
            map.put(SOURCE_REPOSITORY_KIND, null);
            map.put(TARGET_SYSTEM_KIND, null);
            map.put(TARGET_REPOSITORY_KIND, null);
            map.put(SOURCE_ARTIFACT_ID, null);
            map.put(TARGET_ARTIFACT_ID, null);
            map.put(GENERICARTIFACT, null);
            map.put(ERROR_CODE, null);
            map.put(SOURCE_LAST_MODIFICATION_TIME, null);
            map.put(TARGET_LAST_MODIFICATION_TIME, null);
            map.put(SOURCE_ARTIFACT_VERSION, null);
            map.put(TARGET_ARTIFACT_VERSION, null);
            map.put(ARTIFACT_TYPE, null);
        }

        if (quarantineException) {
            // TODO Do we have to care about the fact that the substituted
            // values
            // could potentially contain the place holders again?
            String logMessage = logMessageTemplate;
            for (Object key : map.keys()) {
                Object value = map.get(key);
                logMessage = logMessage.replace("<" + key.toString() + ">",
                        value == null ? "undefined" : value.toString());
            }
            log.error(logMessage);
            return map;
        } else {
            StringBuffer errorMessage = new StringBuffer();
            errorMessage.append("Exception caught that is not going to be quarantined. Characteristics:\n");
            for (Object key : map.keys()) {
                errorMessage.append(key.toString() + ": " + map.get(key) + "\n");
            }
            log.warn(errorMessage.toString());
            return null;
        }
    } catch (Exception e) {
        log.error("While trying to quarantine an exception, an exception occured", e);
        return null;
    }
}

From source file:com.collabnet.ccf.core.transformer.DynamicXsltProcessor.java

License:Open Source License

/**
 * Apply the transform to the record. The record can be either a XML string
 * or a dom4j document object//from www .  j  a va2s  .c  o  m
 * 
 * @param record
 *            the message record
 * 
 * @return a String[] with one String resulting from the transform
 * 
 * @throws ProcessingException
 *             if the record type is not supported
 */
public Object[] process(Object record) throws ProcessingException {
    if (record == null)
        return null;

    Document document = null;
    Element element = null;

    if (record instanceof Document) {
        document = (Document) record;
        element = document.getRootElement();
        try {
            String artifactAction = XPathUtils.getAttributeValue(element,
                    GenericArtifactHelper.ARTIFACT_ACTION);
            String transactionId = XPathUtils.getAttributeValue(element, GenericArtifactHelper.TRANSACTION_ID);
            String errorCode = XPathUtils.getAttributeValue(element, GenericArtifactHelper.ERROR_CODE);
            // pass artifacts with ignore action
            if (artifactAction != null && artifactAction.equals(GenericArtifactHelper.ARTIFACT_ACTION_IGNORE)) {
                return new Object[] { document };
            }
            // do not transform artifacts to be replayed (unless specific
            // error code is set)
            if (transactionId != null && !transactionId.equals(GenericArtifact.VALUE_UNKNOWN)
                    && !transactionId.equals("forcedUpdate")) {
                if (errorCode == null
                        || !errorCode.equals(GenericArtifact.ERROR_REPLAYED_WITH_TRANSFORMATION)) {
                    return new Object[] { document };
                }
            }
        } catch (GenericArtifactParsingException e) {
            // do nothing, this artifact does not seem to be a generic
            // artifact
        }

        // now transform document
        String fileName = null;
        List<Transformer> transform = null;

        // only derive file name automatically if xslt dir is set
        if (!StringUtils.isEmpty(this.xsltDir)) {
            Document result = document;
            for (ScriptProcessor scriptProcessor : scriptProcessors) {
                fileName = deriveFilename(element, scriptProcessor);
                // do not do anything if file name == null
                if (fileName != null) {
                    transform = lookupTransformer(result.getRootElement(), xsltDir + fileName);
                    result = (Document) transform(result, transform, result.getRootElement())[0];
                    if (log.isDebugEnabled()) {
                        log.debug("(Intermediate) transformation result: " + result.asXML());
                    }
                }
            }
            // make sure users did not tamper with immutable top level
            // attributes
            restoreImmutableTopLevelAttributes(element, result.getRootElement());
            return new Document[] { result };
        } else {
            fileName = xsltFile;
            transform = lookupTransformer(element, fileName);
            return transform(document, transform, element);
        }
    }

    // if we get this far then we cannot process the record
    String cause = "Invalid record (type: " + record.getClass().toString() + "). Cannot apply transform";
    log.error(cause);
    throw new CCFRuntimeException(cause);
}

From source file:com.collabnet.ccf.core.transformer.DynamicXsltProcessor.java

License:Open Source License

/**
 * Tries to load the XSLT from the file defined in the properties
 * /*w w w .  j a  v a  2s  . c om*/
 * @throws ValidationException
 *             if the XSLT file is not defined in the properties, the file
 *             cannot be found or there was an error parsing it
 */
private List<Transformer> loadXSLT(File xsltFile, Element element) {
    List<Transformer> transformerList = new ArrayList<Transformer>();
    if (xsltFile == null) {
        String cause = "xsltFile property not set";
        log.error(cause);
        XPathUtils.addAttribute(element, GenericArtifactHelper.ERROR_CODE,
                GenericArtifact.ERROR_TRANSFORMER_FILE);
        throw new CCFRuntimeException(cause);
    }

    try {
        Source source = null;
        if (isOnlyAllowWhiteListedJavaFunctionCalls()) {
            SAXReader reader = new SAXReader();
            Document originalDocument = reader.read(xsltFile);
            Document clonedDocument = (Document) originalDocument.clone();
            Element clonedRootElement = clonedDocument.getRootElement();
            // replace white listed Java functions in XPath expressions with
            // "."
            for (String functionCall : getWhiteListedJavaFunctionCalls()) {
                List<Element> nodes = findFunctionCalls(clonedRootElement, functionCall);
                for (Element e : nodes) {
                    e.addAttribute("select", ".");
                }
            }
            Transformer secureTransform = secureFactory.newTransformer(new DocumentSource(clonedDocument));
            secureTransform.setErrorListener(new XsltValidationErrorListener());
            log.debug("Loaded sanitized version of XSLT [" + xsltFile + "] successfully");
            transformerList.add(secureTransform);
            source = new DocumentSource(originalDocument);
        } else {
            source = new StreamSource(xsltFile);
        }
        Transformer transform = factory.newTransformer(source);
        log.debug("Loaded original XSLT [" + xsltFile + "] successfully");
        transformerList.add(transform);
    } catch (Exception e) {
        String cause = "Failed to load XSLT: [" + xsltFile + " ]" + e.getMessage();
        log.error(cause, e);
        XPathUtils.addAttribute(element, GenericArtifactHelper.ERROR_CODE,
                GenericArtifact.ERROR_TRANSFORMER_FILE);
        throw new CCFRuntimeException(cause, e);
    }

    return transformerList;
}