Example usage for org.w3c.dom Element getAttributes

List of usage examples for org.w3c.dom Element getAttributes

Introduction

In this page you can find the example usage for org.w3c.dom Element getAttributes.

Prototype

public NamedNodeMap getAttributes();

Source Link

Document

A NamedNodeMap containing the attributes of this node (if it is an Element) or null otherwise.

Usage

From source file:com.portfolio.data.provider.MysqlDataProvider.java

@Override
public Object postUser(String in, int userId) throws Exception {
    if (!credential.isAdmin(userId))
        throw new RestWebApplicationException(Status.FORBIDDEN, "No admin right");

    String result = null;/*from   w w  w . j a  va  2s  . co m*/
    String login = null;
    String firstname = null;
    String lastname = null;
    String label = null;
    String password = null;
    String active = "1";
    Integer uuid = 0;
    Integer newId = 0;

    //On prepare les requetes SQL
    PreparedStatement stInsert;
    String sqlInsert;

    //On recupere le body
    Document doc = DomUtils.xmlString2Document(in, new StringBuffer());
    Element etu = doc.getDocumentElement();

    //On verifie le bon format
    if (etu.getNodeName().equals("user")) {
        //On recupere les attributs
        try {
            if (etu.getAttributes().getNamedItem("uid") != null) {
                login = etu.getAttributes().getNamedItem("uid").getNodeValue();

                if (getMysqlUserUid(login) != null) {
                    uuid = Integer.parseInt(getMysqlUserUid(login));
                }
            }
        } catch (Exception ex) {
        }

        try {
            if (etu.getAttributes().getNamedItem("firstname") != null) {
                firstname = etu.getAttributes().getNamedItem("firstname").getNodeValue();
            }
        } catch (Exception ex) {
        }

        try {
            if (etu.getAttributes().getNamedItem("lastname") != null) {
                lastname = etu.getAttributes().getNamedItem("lastname").getNodeValue();
            }
        } catch (Exception ex) {
        }

        try {
            if (etu.getAttributes().getNamedItem("label") != null) {
                label = etu.getAttributes().getNamedItem("label").getNodeValue();
            }
        } catch (Exception ex) {
        }

        try {
            if (etu.getAttributes().getNamedItem("password") != null) {
                password = etu.getAttributes().getNamedItem("password").getNodeValue();
            }
        } catch (Exception ex) {
        }
        try {
            if (etu.getAttributes().getNamedItem("active") != null) {
                active = etu.getAttributes().getNamedItem("active").getNodeValue();
            }
        } catch (Exception ex) {
        }

    } else {
        result = "Erreur lors de la recuperation des attributs de l'utilisateur dans le XML";
    }

    //On ajoute l'utilisateur dans la base de donnees
    if (etu.getAttributes().getNamedItem("firstname") != null
            && etu.getAttributes().getNamedItem("lastname") != null
            && etu.getAttributes().getNamedItem("label") == null) {

        sqlInsert = "REPLACE INTO credential(userid, login, display_firstname, display_lastname, password, active) VALUES (?, ?, ?, ?, UNHEX(SHA1(?)),?)";
        stInsert = connection.prepareStatement(sqlInsert, Statement.RETURN_GENERATED_KEYS);
        if (dbserveur.equals("oracle")) {
            sqlInsert = "MERGE INTO credential d USING (SELECT ? userid,? login,? display_firstname,? display_lastname,crypt(?) password,? active FROM DUAL) s ON (d.userid=s.userid) WHEN MATCHED THEN UPDATE SET d.login=s.login, d.display_firstname = s.display_firstname, d.display_lastname = s.display_lastname, d.password = s.password, d.active = s.active WHEN NOT MATCHED THEN INSERT (d.userid, d.login, d.display_firstname, d.display_lastname, d.password, d.active) VALUES (s.userid, s.login, s.display_firstname, s.display_lastname, s.password, s.active)";
            stInsert = connection.prepareStatement(sqlInsert, new String[] { "userid" });
        }
        stInsert.setInt(1, uuid);
        stInsert.setString(2, login);
        stInsert.setString(3, firstname);
        stInsert.setString(4, lastname);
        stInsert.setString(5, password);
        stInsert.setString(6, active);
        stInsert.executeUpdate();
    } else {
        sqlInsert = "REPLACE INTO credential(userid, login, display_firstname, display_lastname, password, active) VALUES (?, ?, ?, ?, UNHEX(SHA1(?)),?)";
        stInsert = connection.prepareStatement(sqlInsert, Statement.RETURN_GENERATED_KEYS);
        if (dbserveur.equals("oracle")) {
            sqlInsert = "MERGE INTO credential d USING (SELECT ? userid,? login,? display_firstname,? display_lastname,crypt(?) password,? active FROM DUAL) s ON (d.userid=s.userid) WHEN MATCHED THEN UPDATE SET d.login=s.login, d.display_firstname = s.display_firstname, d.display_lastname = s.display_lastname, d.password = s.password, d.active = s.active WHEN NOT MATCHED THEN INSERT (d.userid, d.login, d.display_firstname, d.display_lastname, d.password, d.active) VALUES (s.userid, s.login, s.display_firstname, s.display_lastname, s.password, s.active)";
            stInsert = connection.prepareStatement(sqlInsert, new String[] { "userid" });
        }
        stInsert.setInt(1, uuid);
        stInsert.setString(2, login);
        stInsert.setString(3, " ");
        stInsert.setString(4, label);
        stInsert.setString(5, password);
        stInsert.setString(6, active);
        stInsert.executeUpdate();
    }

    ResultSet rs = stInsert.getGeneratedKeys();
    if (rs.next()) {
        newId = rs.getInt(1);
    }

    //On renvoie le body pour qu'il soit stock dans le log
    result = "<user ";
    result += DomUtils.getXmlAttributeOutput("uid", login) + " ";
    result += DomUtils.getXmlAttributeOutput("firstname", firstname) + " ";
    result += DomUtils.getXmlAttributeOutput("lastname", lastname) + " ";
    result += DomUtils.getXmlAttributeOutput("label", label) + " ";
    result += DomUtils.getXmlAttributeOutput("password", password) + " ";
    result += DomUtils.getXmlAttributeOutputInt("uuid", newId) + " ";
    result += ">";
    result += "</user>";

    return result;
}

From source file:com.portfolio.data.provider.MysqlDataProvider.java

/*****************************/

@Override//w w w  . ja v  a2 s .c o  m
public String postMacroOnNode(int userId, String nodeUuid, String macroName) {
    String val = "erreur";
    String sql = "";
    PreparedStatement st;
    /// SELECT grid, role, RD,WR,DL,AD,types_id,rules_id FROM rule_table rt LEFT JOIN group_right_info gri ON rt.role=gri.label LEFT JOIN node n ON n.portfolio_id=gri.portfolio_id WHERE rule_id=1 AND n.node_uuid=uuid2bin('d48cafa1-5180-4c83-9e22-5d4d45bbf6e2');
    /// SELECT grid,bin2uuid(id),RD,WR,DL,SB,AD,types_id,rules_id FROM group_rights WHERE id=uuid2bin('d48cafa1-5180-4c83-9e22-5d4d45bbf6e2');

    // If admin
    // and reset is called

    try {
        /// Pour retrouver les enfants du noeud et affecter les droits
        if (dbserveur.equals("mysql")) {
            sql = "CREATE TEMPORARY TABLE t_struc_nodeid(" + "uuid binary(16) UNIQUE NOT NULL, "
                    + "t_level INT) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
            st = connection.prepareStatement(sql);
            st.execute();
            st.close();
        } else if (dbserveur.equals("oracle")) {
            String v_sql = "CREATE GLOBAL TEMPORARY TABLE t_struc_nodeid(" + "uuid RAW(16) NOT NULL, "
                    + "t_level NUMBER(10,0)"
                    + ",  CONSTRAINT t_struc_nodeid_UK_uuid UNIQUE (uuid)) ON COMMIT PRESERVE ROWS";
            sql = "{call create_or_empty_table('t_struc_nodeid','" + v_sql + "')}";
            CallableStatement ocs = connection.prepareCall(sql);
            ocs.execute();
            ocs.close();
        }

        // En double car on ne peut pas faire d'update/select d'une mme table temporaire
        if (dbserveur.equals("mysql")) {
            sql = "CREATE TEMPORARY TABLE t_struc_nodeid_2(" + "uuid binary(16) UNIQUE NOT NULL, "
                    + "t_level INT) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
            st = connection.prepareStatement(sql);
            st.execute();
            st.close();
        } else if (dbserveur.equals("oracle")) {
            String v_sql = "CREATE GLOBAL TEMPORARY TABLE t_struc_nodeid_2(" + "uuid RAW(16) NOT NULL, "
                    + "t_level NUMBER(10,0)"
                    + ",  CONSTRAINT t_struc_nodeid_2_UK_uuid UNIQUE (uuid)) ON COMMIT PRESERVE ROWS";
            sql = "{call create_or_empty_table('t_struc_nodeid_2','" + v_sql + "')}";
            CallableStatement ocs = connection.prepareCall(sql);
            ocs.execute();
            ocs.close();
        }

        /// Dans la table temporaire on retrouve les noeuds concerns
        /// (assure une convergence de la rcursion et limite le nombre de lignes dans la recherche)
        /// Init table
        sql = "INSERT INTO t_struc_nodeid(uuid, t_level) " + "SELECT n.node_uuid, 0 " + "FROM node n "
                + "WHERE n.node_uuid=uuid2bin(?)";
        st = connection.prepareStatement(sql);
        st.setString(1, nodeUuid);
        st.executeUpdate();
        st.close();

        //         /*
        /// On boucle, rcursion par niveau
        int level = 0;
        int added = 1;
        if (dbserveur.equals("mysql")) {
            sql = "INSERT IGNORE INTO t_struc_nodeid_2(uuid, t_level) ";
        } else if (dbserveur.equals("oracle")) {
            sql = "INSERT /*+ ignore_row_on_dupkey_index(t_struc_nodeid_2,t_struc_nodeid_2_UK_uuid)*/ INTO t_struc_nodeid_2(uuid, t_level) ";
        }
        sql += "SELECT n.node_uuid, ? "
                + "FROM node n WHERE n.node_parent_uuid IN (SELECT uuid FROM t_struc_nodeid t "
                + "WHERE t.t_level=?)";

        String sqlTemp = null;
        if (dbserveur.equals("mysql")) {
            sqlTemp = "INSERT IGNORE INTO t_struc_nodeid SELECT * FROM t_struc_nodeid_2;";
        } else if (dbserveur.equals("oracle")) {
            sqlTemp = "INSERT INTO t_struc_nodeid SELECT * FROM t_struc_nodeid_2";
        }
        PreparedStatement stTemp = connection.prepareStatement(sqlTemp);

        st = connection.prepareStatement(sql);
        while (added != 0) {
            st.setInt(1, level + 1);
            st.setInt(2, level);
            st.executeUpdate();
            added = stTemp.executeUpdate(); // On s'arrte quand rien  t ajout
            level = level + 1; // Prochaine tape
        }
        st.close();
        stTemp.close();
        //*/

        /// Selection du grid de l'utilisateur
        sql = "SELECT gr.grid, gi.label " + "FROM group_rights gr, group_info gi, group_user gu "
                + "WHERE gr.grid=gi.grid AND gi.gid=gu.gid AND gu.userid=? AND gr.id=uuid2bin(?) AND NOT gi.label=\"all\"";
        st = connection.prepareStatement(sql);
        st.setInt(1, userId);
        st.setString(2, nodeUuid);
        ResultSet res = st.executeQuery();
        /// res.getFetchSize() retourne 0, mme avec un bon rsultat
        int grid = 0;
        String grlabl = "";
        if (res.next()) {
            grid = res.getInt("grid");
            grlabl = res.getString("label");
        }
        res.close();
        st.close();

        // Fetch metadata
        sql = "SELECT metadata_wad FROM node WHERE node_uuid=uuid2bin(?)";
        st = connection.prepareStatement(sql);
        st.setString(1, nodeUuid);
        res = st.executeQuery();
        String meta = "";
        if (res.next())
            meta = res.getString("metadata_wad");
        res.close();
        st.close();

        // Parse it, for the amount of manipulation we do, it will be simpler than find/replace
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        meta = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><metadata-wad " + meta + "></metadata-wad>";
        System.out.println("ACTION OUT: " + meta);
        InputSource is = new InputSource(new StringReader(meta));
        Document doc = documentBuilder.parse(is);
        Element rootMeta = doc.getDocumentElement();
        boolean doUpdate = true;

        NamedNodeMap metaAttr = rootMeta.getAttributes();
        if ("reset".equals(macroName) && credential.isAdmin(userId)) {
            /// if reset and admin
            // Call specific function to process current temporary table
            resetRights();
        } else if ("show".equals(macroName) || "hide".equals(macroName)) {
            /// FIXME: Could only change the needed rights
            // Check if current group can show stuff
            String roles = metaAttr.getNamedItem("showroles").getNodeValue();
            if (roles.contains(grlabl)) // Can activate it
            {
                String showto = metaAttr.getNamedItem("showtoroles").getNodeValue();
                showto = showto.replace(" ", "\",\"");
                showto = "(\"" + showto + "\")";

                //// Il faut qu'il y a un showtorole
                if (!"(\"\")".equals(showto)) {
                    // Update rights
                    /// Ajoute/remplace les droits
                    // FIXME: Je crois que quelque chose manque
                    sql = "INSERT INTO group_rights(grid, id, RD, WR, DL, AD, types_id, rules_id) "
                            + "SELECT gr.grid, gr.id, ?, 0, 0, 0, NULL, NULL "
                            + "FROM group_right_info gri, group_rights gr " + "WHERE gri.label IN " + showto
                            + " AND gri.grid=gr.grid AND gr.id IN (SELECT uuid FROM t_struc_nodeid) "
                            + "ON DUPLICATE KEY UPDATE RD=?, WR=gr.WR, DL=gr.DL, AD=gr.AD, types_id=gr.types_id, rules_id=gr.rules_id";

                    if (dbserveur.equals("oracle")) {
                        sql = "MERGE INTO group_rights d USING (SELECT gr.grid, gr.id, ? RD, 0 WR, 0 DL, 0 AD, NULL types_id, NULL rules_id FROM group_right_info gri, group_rights gr WHERE gri.label IN "
                                + showto
                                + " AND gri.grid=gr.grid AND gr.id IN (SELECT uuid FROM t_struc_nodeid)) s WHEN MATCHED THEN UPDATE SET d.RD=?, d.WR=gr.WR, d.DL=gr.DL, d.AD=gr.AD, d.types_id=gr.types_id, d.rules_id=gr.rules_id WHEN NOT MATCHED THEN INSERT (d.grid, d.id, d.RD, d.WR, d.DL, d.AD, d.types_id, d.rules_id) VALUES (s.grid, s.id, s.RD, s.WR, s.DL, s.AD, s.types_id, s.rules_id)";
                    }
                    st = connection.prepareStatement(sql);
                    if ("hide".equals(macroName)) {
                        st.setInt(1, 0);
                        st.setInt(2, 0);
                    } else if ("show".equals(macroName)) {
                        st.setInt(1, 1);
                        st.setInt(2, 1);
                    }
                    //            st.setString(2, showto);
                    st.executeUpdate();
                    st.close();

                    Node isPriv = metaAttr.getNamedItem("private");
                    // Update local string
                    if ("hide".equals(macroName))
                        isPriv.setNodeValue("Y");
                    else if ("show".equals(macroName))
                        isPriv.setNodeValue("N");
                }
            }

            // Update DB
            if (doUpdate) {
                meta = DomUtils.getNodeAttributesString(rootMeta);
                System.out.println("META: " + meta);

                sql = "UPDATE node SET metadata_wad=? WHERE node_uuid=uuid2bin(?)";
                st = connection.prepareStatement(sql);
                st.setString(1, meta);
                st.setString(2, nodeUuid);
                st.executeUpdate();
            }

        } else if ("submit".equals(macroName)) {
            System.out.println("ACTION: " + macroName + " grid: " + grid + " -> uuid: " + nodeUuid);
            // Update rights
            /// Ajoute/remplace les droits
            // FIXME: Je crois que quelque chose manque
            sql = "INSERT INTO group_rights(grid, id, RD, WR, DL, AD, SB, types_id, rules_id) "
                    + "SELECT gr.grid, gr.id, 1, 0, 0, 0, 0, NULL, NULL " + "FROM group_rights gr "
                    + "WHERE gr.id IN (SELECT uuid FROM t_struc_nodeid) "
                    + "ON DUPLICATE KEY UPDATE RD=1, WR=0, DL=0, AD=0, SB=0, types_id=null, rules_id=null";

            if (dbserveur.equals("oracle")) {
                sql = "MERGE INTO group_rights d USING (SELECT gr.grid, gr.id, 1 RD, 0 WR, 0 DL, 0 AD, 0 SB, NULL types_id, NULL rules_id FROM group_rights gr WHERE gr.id IN (SELECT uuid FROM t_struc_nodeid)) s WHEN MATCHED THEN UPDATE SET d.RD=1, d.WR=0, d.DL=0, d.AD=0, d.SB=0, d.types_id=s.types_id, d.rules_id=s.rules_id WHEN NOT MATCHED THEN INSERT (d.grid, d.id, d.RD, d.WR, d.DL, d.AD, d.SB, d.types_id, d.rules_id) VALUES (s.grid, s.id, s.RD, s.WR, s.DL, s.AD, s.SB, s.types_id, s.rules_id)";
            }
            st = connection.prepareStatement(sql);
            st.executeUpdate();
            st.close();

            /// Vrifie le showtoroles
            String showto = metaAttr.getNamedItem("showtoroles").getNodeValue();
            showto = showto.replace(" ", "\",\"");
            showto = "(\"" + showto + "\")";

            //// Il faut qu'il y a un showtorole
            System.out.println("SHOWTO: " + showto);
            if (!"(\"\")".equals(showto)) {
                System.out.println("SHOWING TO: " + showto);
                // Update rights
                /// Ajoute/remplace les droits
                // FIXME: Je crois que quelque chose manque
                sql = "INSERT INTO group_rights(grid, id, RD, WR, DL, AD, types_id, rules_id) "
                        + "SELECT gri.grid, gr.id, 1, 0, 0, 0, NULL, NULL "
                        + "FROM group_right_info gri, group_rights gr " + "WHERE gri.label IN " + showto + " "
                        + "AND gri.portfolio_id=(" + "SELECT portfolio_id FROM node "
                        + "WHERE node_uuid=uuid2bin(?)) " + "AND gr.id IN (SELECT uuid FROM t_struc_nodeid) "
                        + "ON DUPLICATE KEY UPDATE RD=1, WR=gr.WR, DL=gr.DL, AD=gr.AD, types_id=gr.types_id, rules_id=gr.rules_id";

                if (dbserveur.equals("oracle")) {
                    sql = "MERGE INTO group_rights d USING (SELECT gri.grid, n.node_uuid, rt.RD, rt.WR, rt.DL, rt.AD, rt.types_id, rt.rules_id FROM rule_table rt LEFT JOIN group_right_info gri ON rt.role=gri.label LEFT JOIN node n ON n.portfolio_id=gri.portfolio_id WHERE rt.rule_id=? AND n.node_uuid IN (SELECT uuid FROM t_struc_nodeid)) s ON (d.grid = s.grid AND d.id = s.id) WHEN MATCHED THEN UPDATE SET d.RD=rt.RD, d.WR=rt.WR, d.DL=rt.DL, d.AD=rt.AD, d.types_id=rt.types_id, d.rules_id=rt.rules_id WHEN NOT MATCHED THEN INSERT (d.grid, d.id, d.RD, d.WR, d.DL, d.AD, d.types_id, d.rules_id) VALUES (s.grid, s.id, s.RD, s.WR, s.DL, s.AD, s.types_id, s.rules_id)";
                }
                st = connection.prepareStatement(sql);
                st.setString(1, nodeUuid);
                st.executeUpdate();
                st.close();

                //               Node isPriv = metaAttr.getNamedItem("private");
                //               isPriv.setNodeValue("Y");
            }
        }

        val = "OK";
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            // Les 'pooled connection' ne se ferment pas vraiment. On nettoie manuellement les tables temporaires...
            if (dbserveur.equals("mysql")) {
                sql = "DROP TEMPORARY TABLE IF EXISTS t_struc_nodeid, t_struc_nodeid_2";
                st = connection.prepareStatement(sql);
                st.execute();
                st.close();
            }

            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    return val;
}

From source file:com.portfolio.data.provider.MysqlDataProvider.java

public String resetRights() {
    try {/*from  ww w  .ja v  a  2s  .  c  om*/
        /// temp class
        class right {
            int rd = 0;
            int wr = 0;
            int dl = 0;
            int sb = 0;
            int ad = 0;
            String types = "";
            String rules = "";
            String notify = "";
        }
        ;

        class groupright {
            right getGroup(String label) {
                right r = rights.get(label.trim());
                if (r == null) {
                    r = new right();
                    rights.put(label, r);
                }
                return r;
            }

            void setNotify(String roles) {
                Iterator<right> iter = rights.values().iterator();
                while (iter.hasNext()) {
                    right r = iter.next();
                    r.notify = roles.trim();
                }
            }

            HashMap<String, right> rights = new HashMap<String, right>();
        }
        ;

        class resolver {
            groupright getUuid(String uuid) {
                groupright gr = resolve.get(uuid);
                if (gr == null) {
                    gr = new groupright();
                    resolve.put(uuid, gr);
                }
                return gr;
            };

            HashMap<String, groupright> resolve = new HashMap<String, groupright>();
            HashMap<String, Integer> groups = new HashMap<String, Integer>();
        }
        ;

        resolver resolve = new resolver();

        /// t_struc is already populated with the uuid we have to reset
        String sql = "SELECT bin2uuid(n.node_uuid) AS uuid, bin2uuid(n.portfolio_id) AS puuid, n.metadata, n.metadata_wad, n.metadata_epm "
                + "FROM t_struc t, node n WHERE t.uuid=n.node_uuid";
        PreparedStatement st = connection.prepareStatement(sql);
        ResultSet res = st.executeQuery();

        DocumentBuilder documentBuilder;
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        while (res.next()) // TODO Maybe pre-process into temp table
        {
            String uuid = res.getString("uuid");
            String meta = res.getString("metadata_wad");
            String nodeString = "<?xml version='1.0' encoding='UTF-8' standalone='no'?><transfer " + meta
                    + "/>";

            groupright role = resolve.getUuid(uuid);

            try {
                /// parse meta
                InputSource is = new InputSource(new StringReader(nodeString));
                Document doc = documentBuilder.parse(is);

                /// Process attributes
                Element attribNode = doc.getDocumentElement();
                NamedNodeMap attribMap = attribNode.getAttributes();

                String nodeRole;
                Node att = attribMap.getNamedItem("access");
                if (att != null) {
                    //if(access.equalsIgnoreCase("public") || access.contains("public"))
                    //   credential.postGroupRight("all",uuid,Credential.READ,portfolioUuid,userId);
                }
                att = attribMap.getNamedItem("seenoderoles");
                if (att != null) {
                    StringTokenizer tokens = new StringTokenizer(att.getNodeValue(), " ");
                    while (tokens.hasMoreElements()) {
                        nodeRole = tokens.nextElement().toString();

                        right r = role.getGroup(nodeRole);
                        r.rd = 1;

                        resolve.groups.put(nodeRole, 0);
                    }
                }
                att = attribMap.getNamedItem("showtoroles");
                if (att != null) {
                    StringTokenizer tokens = new StringTokenizer(att.getNodeValue(), " ");
                    while (tokens.hasMoreElements()) {
                        nodeRole = tokens.nextElement().toString();

                        right r = role.getGroup(nodeRole);
                        r.rd = 0;

                        resolve.groups.put(nodeRole, 0);
                    }
                }
                att = attribMap.getNamedItem("delnoderoles");
                if (att != null) {
                    StringTokenizer tokens = new StringTokenizer(att.getNodeValue(), " ");
                    while (tokens.hasMoreElements()) {

                        nodeRole = tokens.nextElement().toString();
                        right r = role.getGroup(nodeRole);
                        r.dl = 1;

                        resolve.groups.put(nodeRole, 0);
                    }
                }
                att = attribMap.getNamedItem("editnoderoles");
                if (att != null) {
                    StringTokenizer tokens = new StringTokenizer(att.getNodeValue(), " ");
                    while (tokens.hasMoreElements()) {
                        nodeRole = tokens.nextElement().toString();
                        right r = role.getGroup(nodeRole);
                        r.wr = 1;

                        resolve.groups.put(nodeRole, 0);
                    }
                }
                att = attribMap.getNamedItem("submitnoderoles");
                if (att != null) {
                    StringTokenizer tokens = new StringTokenizer(att.getNodeValue(), " ");
                    while (tokens.hasMoreElements()) {
                        nodeRole = tokens.nextElement().toString();
                        right r = role.getGroup(nodeRole);
                        r.sb = 1;

                        resolve.groups.put(nodeRole, 0);
                    }
                }
                att = attribMap.getNamedItem("seeresroles");
                if (att != null) {
                    StringTokenizer tokens = new StringTokenizer(att.getNodeValue(), " ");
                    while (tokens.hasMoreElements()) {
                        nodeRole = tokens.nextElement().toString();
                        right r = role.getGroup(nodeRole);
                        r.rd = 1;

                        resolve.groups.put(nodeRole, 0);
                    }
                }
                att = attribMap.getNamedItem("delresroles");
                if (att != null) {
                    StringTokenizer tokens = new StringTokenizer(att.getNodeValue(), " ");
                    while (tokens.hasMoreElements()) {
                        nodeRole = tokens.nextElement().toString();
                        right r = role.getGroup(nodeRole);
                        r.dl = 1;

                        resolve.groups.put(nodeRole, 0);
                    }
                }
                att = attribMap.getNamedItem("editresroles");
                if (att != null) {
                    StringTokenizer tokens = new StringTokenizer(att.getNodeValue(), " ");
                    while (tokens.hasMoreElements()) {
                        nodeRole = tokens.nextElement().toString();
                        right r = role.getGroup(nodeRole);
                        r.wr = 1;

                        resolve.groups.put(nodeRole, 0);
                    }
                }
                att = attribMap.getNamedItem("submitresroles");
                if (att != null) {
                    StringTokenizer tokens = new StringTokenizer(att.getNodeValue(), " ");
                    while (tokens.hasMoreElements()) {
                        nodeRole = tokens.nextElement().toString();
                        right r = role.getGroup(nodeRole);
                        r.sb = 1;

                        resolve.groups.put(nodeRole, 0);
                    }
                }
                Node actionroles = attribMap.getNamedItem("actionroles");
                if (actionroles != null) {
                    /// Format pour l'instant: actionroles="sender:1,2;responsable:4"
                    StringTokenizer tokens = new StringTokenizer(actionroles.getNodeValue(), ";");
                    while (tokens.hasMoreElements()) {
                        nodeRole = tokens.nextElement().toString();
                        StringTokenizer data = new StringTokenizer(nodeRole, ":");
                        String nrole = data.nextElement().toString();
                        String actions = data.nextElement().toString().trim();
                        right r = role.getGroup(nrole);
                        r.rules = actions;

                        resolve.groups.put(nrole, 0);
                    }
                }
                Node menuroles = attribMap.getNamedItem("menuroles");
                if (menuroles != null) {
                    /// Pour les diffrents items du menu
                    StringTokenizer menuline = new StringTokenizer(menuroles.getNodeValue(), ";");

                    while (menuline.hasMoreTokens()) {
                        String line = menuline.nextToken();
                        /// Format pour l'instant: mi6-parts,mission,Ajouter une mission,secret_agent
                        StringTokenizer tokens = new StringTokenizer(line, ",");
                        String menurolename = null;
                        for (int t = 0; t < 4; ++t)
                            menurolename = tokens.nextToken();

                        if (menurolename != null)
                            resolve.groups.put(menurolename.trim(), 0);
                    }
                }
                Node notifyroles = attribMap.getNamedItem("notifyroles");
                if (notifyroles != null) {
                    /// Format pour l'instant: notifyroles="sender responsable"
                    StringTokenizer tokens = new StringTokenizer(notifyroles.getNodeValue(), " ");
                    String merge = "";
                    if (tokens.hasMoreElements())
                        merge = tokens.nextElement().toString().trim();
                    while (tokens.hasMoreElements())
                        merge += "," + tokens.nextElement().toString().trim();
                    role.setNotify(merge);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        res.close();
        st.close();

        connection.setAutoCommit(false);

        /// On insre les donnes pr-compil
        //         Iterator<String> entries = resolve.groups.keySet().iterator();

        /// Ajout des droits des noeuds FIXME
        // portfolio, group name, id -> rights
        String updateRight = "UPDATE group_rights gr, group_right_info gri SET gr.RD=?, gr.WR=?, gr.DL=?, gr.SB=?, gr.AD=?, gr.types_id=?, gr.rules_id=?, gr.notify_roles=? "
                + "WHERE gri.grid=gr.grid AND gri.label=? AND gr.id=uuid2bin(?)";
        st = connection.prepareStatement(updateRight);

        Iterator<Entry<String, groupright>> rights = resolve.resolve.entrySet().iterator();
        while (rights.hasNext()) {
            Entry<String, groupright> entry = rights.next();
            String uuid = entry.getKey();
            groupright gr = entry.getValue();

            Iterator<Entry<String, right>> rightiter = gr.rights.entrySet().iterator();
            while (rightiter.hasNext()) {
                Entry<String, right> rightelem = rightiter.next();
                String group = rightelem.getKey();
                //               int grid = resolve.groups.get(group);
                right rightval = rightelem.getValue();
                st.setInt(1, rightval.rd);
                st.setInt(2, rightval.wr);
                st.setInt(3, rightval.dl);
                st.setInt(4, rightval.sb);
                st.setInt(5, rightval.ad);
                st.setString(6, rightval.types);
                st.setString(7, rightval.rules);
                st.setString(8, rightval.notify);
                st.setString(9, group);
                st.setString(10, uuid);

                st.execute();
            }
        }
    } catch (Exception e) {
        try {
            if (connection.getAutoCommit() == false)
                connection.rollback();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
        e.printStackTrace();
    } finally {
        try {
            connection.setAutoCommit(true);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    return null;
}

From source file:com.portfolio.data.provider.MysqlDataProvider.java

@Override
public Object postImportNode(MimeType inMimeType, String destUuid, String tag, String code, int userId,
        int groupId) throws Exception {
    if ("".equals(tag) || tag == null || "".equals(code) || code == null)
        return "erreur";

    String sql = "";
    PreparedStatement st;//ww w  . j  av  a2  s  . c o m
    String createdUuid = "erreur";

    /*
    long start = System.currentTimeMillis();
    long t1=0; long t2=0; long t3=0; long t4=0; long t5=0;
    long t6=0; long t7=0; long t8=0; long t9=0; long t10=0;
    long t11=0; long t12=0; long t13=0; long t14=0; long t15=0;
    long t16=0; long t17=0; long t18=0; long t19=0; long t20=0;
    long t21=0; long t22=0;
    long end=0;
    //*/

    try {
        /// On retrouve le uuid du noeud de base dont le tag est inclus dans le code et est actif
        sql = "SELECT bin2uuid(n2.node_uuid) AS nUuid, bin2uuid(n2.portfolio_id) AS pUuid " + "FROM node n1 "
                + "LEFT JOIN node n2 ON n1.portfolio_id=n2.portfolio_id "
                + "LEFT JOIN portfolio p ON p.portfolio_id=n2.portfolio_id "
                + "WHERE n2.semantictag=? AND n1.code=? " + "AND p.active =1";
        st = connection.prepareStatement(sql);
        st.setString(1, tag);
        st.setString(2, code);
        ResultSet res = st.executeQuery();
        String baseUuid = "";
        String pUuid = "";
        if (res.next()) // On prend le premier, trs chic pour l'utilisateur...
        {
            baseUuid = res.getString("nUuid");
            pUuid = res.getString("pUuid");
        } else
            return "Selection non existante.";

        //         t1 = System.currentTimeMillis();

        ///// Cration des tables temporaires
        /// Pour la copie de la structure
        if (dbserveur.equals("mysql")) {
            sql = "CREATE TEMPORARY TABLE t_data_node(" + "new_uuid binary(16) NOT NULL, " + /// Pour la copie d'une nouvelle structure
                    "node_uuid binary(16)  NOT NULL, " + "node_parent_uuid binary(16) DEFAULT NULL, " +
                    //                  "node_children_uuid blob, " +
                    "node_order int(12) NOT NULL, " +
                    //                  "metadata text NOT NULL, " +
                    //                  "metadata_wad text NOT NULL, " +
                    //                  "metadata_epm text NOT NULL, " +
                    "res_node_uuid binary(16) DEFAULT NULL, " + "res_res_node_uuid binary(16) DEFAULT NULL, "
                    + "res_context_node_uuid binary(16)  DEFAULT NULL, " + "shared_res int(1) NOT NULL, "
                    + "shared_node int(1) NOT NULL, " + "shared_node_res int(1) NOT NULL, "
                    + "shared_res_uuid BINARY(16)  NULL, " + "shared_node_uuid BINARY(16) NULL, "
                    + "shared_node_res_uuid BINARY(16) NULL, " + "asm_type varchar(50) DEFAULT NULL, "
                    + "xsi_type varchar(50)  DEFAULT NULL, " + "semtag varchar(250) DEFAULT NULL, "
                    + "semantictag varchar(250) DEFAULT NULL, " + "label varchar(250)  DEFAULT NULL, "
                    + "code varchar(250)  DEFAULT NULL, " + "descr varchar(250)  DEFAULT NULL, "
                    + "format varchar(30) DEFAULT NULL, " + "modif_user_id int(12) NOT NULL, "
                    + "modif_date timestamp NULL DEFAULT NULL, "
                    + "portfolio_id binary(16) DEFAULT NULL) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
            st = connection.prepareStatement(sql);
            st.execute();
            st.close();
        } else if (dbserveur.equals("oracle")) {
            String v_sql = "CREATE GLOBAL TEMPORARY TABLE t_data_node(" + "new_uuid RAW(16) NOT NULL, " + /// Pour la copie d'une nouvelle structure
                    "node_uuid RAW(16)  NOT NULL, " + "node_parent_uuid RAW(16) DEFAULT NULL, " +
                    //                      "node_children_uuid CLOB, " +
                    "node_order NUMBER(12) NOT NULL, " +
                    //                      "metadata CLOB DEFAULT NULL, " +
                    //                      "metadata_wad CLOB DEFAULT NULL, " +
                    //                      "metadata_epm CLOB DEFAULT NULL, " +
                    "res_node_uuid RAW(16) DEFAULT NULL, " + "res_res_node_uuid RAW(16) DEFAULT NULL, "
                    + "res_context_node_uuid RAW(16)  DEFAULT NULL, " + "shared_res NUMBER(1) NOT NULL, "
                    + "shared_node NUMBER(1) NOT NULL, " + "shared_node_res NUMBER(1) NOT NULL, "
                    + "shared_res_uuid RAW(16) DEFAULT NULL, " + "shared_node_uuid RAW(16) DEFAULT NULL, "
                    + "shared_node_res_uuid RAW(16) DEFAULT NULL, "
                    + "asm_type VARCHAR2(50 CHAR) DEFAULT NULL, " + "xsi_type VARCHAR2(50 CHAR)  DEFAULT NULL, "
                    + "semtag VARCHAR2(250 CHAR) DEFAULT NULL, "
                    + "semantictag VARCHAR2(250 CHAR) DEFAULT NULL, "
                    + "label VARCHAR2(250 CHAR)  DEFAULT NULL, " + "code VARCHAR2(250 CHAR)  DEFAULT NULL, "
                    + "descr VARCHAR2(250 CHAR)  DEFAULT NULL, " + "format VARCHAR2(30 CHAR) DEFAULT NULL, "
                    + "modif_user_id NUMBER(12) NOT NULL, " + "modif_date timestamp DEFAULT NULL, "
                    + "portfolio_id RAW(16) DEFAULT NULL) ON COMMIT PRESERVE ROWS";
            sql = "{call create_or_empty_table('t_data_node','" + v_sql + "')}";
            CallableStatement ocs = connection.prepareCall(sql);
            ocs.execute();
            ocs.close();
        }

        //         t2 = System.currentTimeMillis();

        /// Pour la copie des donnes
        if (dbserveur.equals("mysql")) {
            sql = "CREATE TEMPORARY TABLE t_res_node(" + "new_uuid binary(16) NOT NULL, " + /// Pour la copie d'une nouvelle structure
                    "node_uuid binary(16) NOT NULL, " + "xsi_type varchar(50) DEFAULT NULL, " +
                    //                  "content text, " +
                    "user_id int(11) DEFAULT NULL, " + "modif_user_id int(12) NOT NULL, "
                    + "modif_date timestamp NULL DEFAULT NULL) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
            st = connection.prepareStatement(sql);
            st.execute();
            st.close();
        } else if (dbserveur.equals("oracle")) {
            String v_sql = "CREATE GLOBAL TEMPORARY TABLE t_res_node(" + "new_uuid RAW(16) NOT NULL, " + /// Pour la copie d'une nouvelle structure
                    "node_uuid RAW(16) NOT NULL, " + "xsi_type VARCHAR2(50 CHAR) DEFAULT NULL, " +
                    //                      "content CLOB, " +
                    "user_id NUMBER(11) DEFAULT NULL, " + "modif_user_id NUMBER(12) NOT NULL, "
                    + "modif_date timestamp DEFAULT NULL) ON COMMIT PRESERVE ROWS";
            sql = "{call create_or_empty_table('t_res_node','" + v_sql + "')}";
            CallableStatement ocs = connection.prepareCall(sql);
            ocs.execute();
            ocs.close();
        }

        //         t3 = System.currentTimeMillis();

        /// Pour le filtrage de la structure
        if (dbserveur.equals("mysql")) {
            sql = "CREATE TEMPORARY TABLE t_struc(" + "node_order int(12) NOT NULL, "
                    + "new_uuid binary(16) NOT NULL, " + "uuid binary(16) UNIQUE NOT NULL, "
                    + "node_parent_uuid binary(16) NOT NULL, "
                    + "t_level INT) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
            st = connection.prepareStatement(sql);
            st.execute();
            st.close();
        } else if (dbserveur.equals("oracle")) {
            String v_sql = "CREATE GLOBAL TEMPORARY TABLE t_struc(" + "node_order NUMBER(12) NOT NULL, "
                    + "new_uuid RAW(16) NOT NULL, " + "uuid RAW(16) NOT NULL, " + "node_parent_uuid RAW(16), "
                    + "t_level NUMBER(10,0)"
                    + ",  CONSTRAINT t_struc_UK_uuid UNIQUE (uuid)) ON COMMIT PRESERVE ROWS";
            sql = "{call create_or_empty_table('t_struc','" + v_sql + "')}";
            CallableStatement ocs = connection.prepareCall(sql);
            ocs.execute();
            ocs.close();
        }

        //         t4 = System.currentTimeMillis();

        // En double car on ne peut pas faire d'update/select d'une mme table temporaire
        if (dbserveur.equals("mysql")) {
            sql = "CREATE TEMPORARY TABLE t_struc_2(" + "node_order int(12) NOT NULL, "
                    + "new_uuid binary(16) NOT NULL, " + "uuid binary(16) UNIQUE NOT NULL, "
                    + "node_parent_uuid binary(16) NOT NULL, "
                    + "t_level INT) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
            st = connection.prepareStatement(sql);
            st.execute();
            st.close();
        } else if (dbserveur.equals("oracle")) {
            String v_sql = "CREATE GLOBAL TEMPORARY TABLE t_struc_2(" + "node_order NUMBER(12) NOT NULL, "
                    + "new_uuid RAW(16) NOT NULL, " + "uuid RAW(16) NOT NULL, " + "node_parent_uuid RAW(16), "
                    + "t_level NUMBER(10,0)"
                    + ",  CONSTRAINT t_struc_2_UK_uuid UNIQUE (uuid)) ON COMMIT PRESERVE ROWS";
            sql = "{call create_or_empty_table('t_struc_2','" + v_sql + "')}";
            CallableStatement ocs = connection.prepareCall(sql);
            ocs.execute();
            ocs.close();
        }

        //         t5 = System.currentTimeMillis();

        /// Copie de la structure
        sql = "INSERT INTO t_data_node(new_uuid, node_uuid, node_parent_uuid, node_order, res_node_uuid, res_res_node_uuid, res_context_node_uuid , shared_res, shared_node, shared_node_res, shared_res_uuid, shared_node_uuid, shared_node_res_uuid, asm_type, xsi_type, semtag, semantictag, label, code, descr, format, modif_user_id, modif_date, portfolio_id) ";
        if (dbserveur.equals("mysql")) {
            sql += "SELECT uuid2bin(UUID()), ";
        } else if (dbserveur.equals("oracle")) {
            sql += "SELECT sys_guid(), ";
        }
        sql += "node_uuid, node_parent_uuid, node_order, res_node_uuid, res_res_node_uuid, res_context_node_uuid , shared_res, shared_node, shared_node_res, shared_res_uuid, shared_node_uuid, shared_node_res_uuid, asm_type, xsi_type, semtag, semantictag, label, code, descr, format, modif_user_id, modif_date, portfolio_id "
                + "FROM node n " + "WHERE portfolio_id=uuid2bin(?)";
        st = connection.prepareStatement(sql);
        st.setString(1, pUuid);
        st.executeUpdate();
        st.close();

        //         t6 = System.currentTimeMillis();

        /// Dans la table temporaire on retrouve les noeuds concerns
        /// (assure une convergence de la rcursion et limite le nombre de lignes dans la recherche)
        /// Init table
        sql = "INSERT INTO t_struc(node_order, new_uuid, uuid, node_parent_uuid, t_level) "
                + "SELECT d.node_order, d.new_uuid, d.node_uuid, uuid2bin(?), 0 " + "FROM t_data_node d "
                + "WHERE d.node_uuid=uuid2bin(?)";
        st = connection.prepareStatement(sql);
        st.setString(1, destUuid); // Pour le branchement avec la structure de destination
        st.setString(2, baseUuid);
        st.executeUpdate();
        st.close();

        //         t7 = System.currentTimeMillis();

        /// On boucle, sera toujours <=  "nombre de noeud du portfolio"
        int level = 0;
        int added = 1;
        if (dbserveur.equals("mysql")) {
            sql = "INSERT IGNORE INTO t_struc_2(node_order, new_uuid, uuid, node_parent_uuid, t_level) ";
        } else if (dbserveur.equals("oracle")) {
            sql = "INSERT /*+ ignore_row_on_dupkey_index(t_struc_2,t_struc_2_UK_uuid)*/ INTO t_struc_2(node_order, new_uuid, uuid, node_parent_uuid, t_level) ";
        }
        sql += "SELECT d.node_order, d.new_uuid, d.node_uuid, d.node_parent_uuid, ? "
                + "FROM t_data_node d WHERE d.node_parent_uuid IN (SELECT uuid FROM t_struc t "
                + "WHERE t.t_level=?)";

        String sqlTemp = null;
        if (dbserveur.equals("mysql")) {
            sqlTemp = "INSERT IGNORE INTO t_struc SELECT * FROM t_struc_2;";
        } else if (dbserveur.equals("oracle")) {
            sqlTemp = "INSERT /*+ ignore_row_on_dupkey_index(t_struc,t_struc_UK_uuid)*/ INTO t_struc SELECT * FROM t_struc_2";
        }
        PreparedStatement stTemp = connection.prepareStatement(sqlTemp);

        st = connection.prepareStatement(sql);
        while (added != 0) {
            st.setInt(1, level + 1);
            st.setInt(2, level);
            st.executeUpdate();
            added = stTemp.executeUpdate(); // On s'arrte quand rien  t ajout
            level = level + 1; // Prochaine tape
        }
        st.close();
        stTemp.close();

        //         t8 = System.currentTimeMillis();

        /// On retire les lments null, a pose problme par la suite
        if (dbserveur.equals("mysql")) {
            sql = "DELETE FROM t_struc WHERE new_uuid=0x0000000000000000000000000000000";
        } else if (dbserveur.equals("oracle")) {
            sql = "DELETE FROM t_struc WHERE new_uuid='00000000000000000000000000000000'";
        }
        st = connection.prepareStatement(sql);
        st.executeUpdate();
        st.close();

        //         t9 = System.currentTimeMillis();

        /// On filtre les donnes dont on a pas besoin
        sql = "DELETE FROM t_data_node WHERE node_uuid NOT IN (SELECT uuid FROM t_struc)";
        st = connection.prepareStatement(sql);
        st.executeUpdate();
        st.close();

        //         t10 = System.currentTimeMillis();

        ///// FIXME TODO: Vrifier les droits sur les donnes restantes

        /// Copie des donnes non partags (shared=0)
        sql = "INSERT INTO t_res_node(new_uuid, node_uuid, xsi_type, user_id, modif_user_id, modif_date) ";
        if (dbserveur.equals("mysql")) {
            sql += "SELECT uuid2bin(UUID()), ";
        } else if (dbserveur.equals("oracle")) {
            sql += "SELECT sys_guid(), ";
        }
        sql += "r.node_uuid, r.xsi_type, r.user_id, r.modif_user_id, r.modif_date "
                + "FROM t_data_node d, resource_table r " + "WHERE (d.res_node_uuid=r.node_uuid "
                + "OR res_res_node_uuid=r.node_uuid " + "OR res_context_node_uuid=r.node_uuid) "
                + "AND (shared_res=0 OR shared_node=0 OR shared_node_res=0)";
        st = connection.prepareStatement(sql);
        st.executeUpdate();
        st.close();

        //         t11 = System.currentTimeMillis();

        /// Rsolution des nouveaux uuid avec les parents
        // Avec la structure
        sql = "UPDATE t_data_node t "
                + "SET t.node_parent_uuid = (SELECT new_uuid FROM t_struc s WHERE s.uuid=t.node_parent_uuid)";
        st = connection.prepareStatement(sql);
        st.executeUpdate();
        st.close();

        //         t12 = System.currentTimeMillis();

        // Avec les ressources
        sql = "UPDATE t_data_node t "
                + "SET t.res_node_uuid = (SELECT new_uuid FROM t_res_node r WHERE r.node_uuid= t.res_node_uuid)";
        st = connection.prepareStatement(sql);
        st.executeUpdate();
        st.close();

        //         t13 = System.currentTimeMillis();

        sql = "UPDATE t_data_node t "
                + "SET t.res_res_node_uuid = (SELECT new_uuid FROM t_res_node r WHERE r.node_uuid= t.res_res_node_uuid)";
        st = connection.prepareStatement(sql);
        st.executeUpdate();
        st.close();

        //         t14 = System.currentTimeMillis();

        sql = "UPDATE t_data_node t "
                + "SET t.res_context_node_uuid = (SELECT new_uuid FROM t_res_node r WHERE r.node_uuid=t.res_context_node_uuid)";
        st = connection.prepareStatement(sql);
        st.executeUpdate();
        st.close();

        //         t15 = System.currentTimeMillis();

        /// Mise  jour du parent de la nouvelle copie ainsi que l'ordre
        sql = "UPDATE t_data_node " + "SET node_parent_uuid=uuid2bin(?), "
                + "node_order=(SELECT COUNT(node_parent_uuid) FROM node WHERE node_parent_uuid=uuid2bin(?)) "
                + "WHERE node_uuid=uuid2bin(?)";
        st = connection.prepareStatement(sql);
        st.setString(1, destUuid);
        st.setString(2, destUuid);
        st.setString(3, baseUuid);
        st.executeUpdate();
        st.close();

        //         t16 = System.currentTimeMillis();

        // Mise  jour de l'appartenance au portfolio de destination
        sql = "UPDATE t_data_node "
                + "SET portfolio_id=(SELECT portfolio_id FROM node WHERE node_uuid=uuid2bin(?))";
        st = connection.prepareStatement(sql);
        st.setString(1, destUuid);
        st.executeUpdate();
        st.close();

        //         t17 = System.currentTimeMillis();

        /// On copie tout dans les vrai tables
        connection.setAutoCommit(false);

        /// Structure
        sql = "INSERT INTO node(node_uuid, node_parent_uuid, node_order, metadata, metadata_wad, metadata_epm, res_node_uuid, res_res_node_uuid, res_context_node_uuid, shared_res, shared_node, shared_node_res, shared_res_uuid, shared_node_uuid, shared_node_res_uuid, asm_type, xsi_type, semtag, semantictag, label, code, descr, format, modif_user_id, modif_date, portfolio_id) "
                + "SELECT t.new_uuid, t.node_parent_uuid, t.node_order, n.metadata, n.metadata_wad, n.metadata_epm, t.res_node_uuid, t.res_res_node_uuid, t.res_context_node_uuid, t.shared_res, t.shared_node, t.shared_node_res, t.shared_res_uuid, t.shared_node_uuid, t.shared_node_res_uuid, t.asm_type, t.xsi_type, t.semtag, t.semantictag, t.label, t.code, t.descr, t.format, t.modif_user_id, t.modif_date, t.portfolio_id "
                + "FROM t_data_node t LEFT JOIN node n ON t.node_uuid=n.node_uuid";
        st = connection.prepareStatement(sql);
        st.executeUpdate();
        st.close();

        //         t18 = System.currentTimeMillis();

        /// Resources
        sql = "INSERT INTO resource_table(node_uuid, xsi_type, content, user_id, modif_user_id, modif_date) "
                + "SELECT t.new_uuid, r.xsi_type, r.content, r.user_id, r.modif_user_id, r.modif_date "
                + "FROM t_res_node t LEFT JOIN resource_table r ON t.node_uuid=r.node_uuid";
        st = connection.prepareStatement(sql);
        st.executeUpdate();
        st.close();

        //         t19 = System.currentTimeMillis();

        /// Mise  jour de la liste des enfants
        if (dbserveur.equals("mysql")) {
            sql = "UPDATE node d, (" + "SELECT p.node_parent_uuid, "
                    + "GROUP_CONCAT(bin2uuid(p.new_uuid) ORDER BY p.node_order) AS value "
                    + "FROM t_data_node p GROUP BY p.node_parent_uuid) tmp "
                    + "SET d.node_children_uuid=tmp.value " + "WHERE tmp.node_parent_uuid=d.node_uuid";
        } else if (dbserveur.equals("oracle")) {
            sql = "UPDATE node d SET d.node_children_uuid=(SELECT value FROM (SELECT p.node_parent_uuid, LISTAGG(bin2uuid(p.new_uuid), ',') WITHIN GROUP (ORDER BY p.node_order) AS value FROM t_data_node p GROUP BY p.node_parent_uuid) tmp WHERE tmp.node_parent_uuid=d.node_uuid) WHERE EXISTS (SELECT 1 FROM t_data_node WHERE node_parent_uuid=d.node_uuid)";
        }
        st = connection.prepareStatement(sql);
        st.execute();
        st.close();

        //         t20 = System.currentTimeMillis();

        /// Ajout de l'enfant dans la structure originelle
        if (dbserveur.equals("mysql")) {
            sql = "UPDATE node n1, ("
                    + "SELECT GROUP_CONCAT(bin2uuid(n2.node_uuid) ORDER BY n2.node_order) AS value "
                    + "FROM node n2 " + "WHERE n2.node_parent_uuid=uuid2bin(?) "
                    + "GROUP BY n2.node_parent_uuid) tmp " + "SET n1.node_children_uuid=tmp.value "
                    + "WHERE n1.node_uuid=uuid2bin(?)";
        } else if (dbserveur.equals("oracle")) {
            sql = "UPDATE node SET node_children_uuid=(SELECT LISTAGG(bin2uuid(n2.node_uuid), ',') WITHIN GROUP (ORDER BY n2.node_order) AS value FROM node n2 WHERE n2.node_parent_uuid=uuid2bin(?) GROUP BY n2.node_parent_uuid) WHERE node_uuid=uuid2bin(?)";
        }
        st = connection.prepareStatement(sql);
        st.setString(1, destUuid);
        st.setString(2, destUuid);
        st.executeUpdate();
        st.close();

        //         t21 = System.currentTimeMillis();

        /// Parsage des droits des noeuds et initialisation dans la BD
        // Login
        sql = "SELECT login FROM credential c WHERE c.userid=?";
        st = connection.prepareStatement(sql);
        st.setInt(1, userId);
        res = st.executeQuery();

        String login = "";
        if (res.next())
            login = res.getString("login");

        // Selection des metadonnes
        sql = "SELECT bin2uuid(t.new_uuid) AS uuid, bin2uuid(t.portfolio_id) AS puuid, n.metadata, n.metadata_wad, n.metadata_epm "
                + "FROM t_data_node t LEFT JOIN node n ON t.node_uuid=n.node_uuid";
        st = connection.prepareStatement(sql);
        res = st.executeQuery();

        while (res.next()) {
            String uuid = res.getString("uuid");
            String portfolioUuid = res.getString("puuid");
            // Process et remplacement de 'user' par la personne en cours
            String meta = res.getString("metadata_wad");

            if (meta.contains("user")) {
                meta = meta.replaceAll("user", login);

                //// FIXME: should be done before with t_data_node
                /// Replace metadata
                sql = "UPDATE node SET metadata_wad=? WHERE node_uuid=uuid2bin(?)";
                st = connection.prepareStatement(sql);
                st.setString(1, meta);
                st.setString(2, uuid);
                st.executeUpdate();
                st.close();

                /// Ensure specific user group exist
                getRoleByNode(1, destUuid, login);
            }

            String nodeString = "<?xml version='1.0' encoding='UTF-8' standalone='no'?><transfer " + meta
                    + "/>";
            try {
                /// Ensure we can parse it correctly
                DocumentBuilder documentBuilder;
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                documentBuilder = documentBuilderFactory.newDocumentBuilder();
                InputSource is = new InputSource(new StringReader(nodeString));
                Document doc = documentBuilder.parse(is);

                /// Process attributes
                Element attribNode = doc.getDocumentElement();
                NamedNodeMap attribMap = attribNode.getAttributes();

                /// FIXME:  amliorer pour faciliter le changement des droits
                String nodeRole;
                Node att = attribMap.getNamedItem("access");
                if (att != null) {
                    //if(access.equalsIgnoreCase("public") || access.contains("public"))
                    //   credential.postGroupRight("all",uuid,Credential.READ,portfolioUuid,userId);
                }
                att = attribMap.getNamedItem("seenoderoles");
                if (att != null) {
                    StringTokenizer tokens = new StringTokenizer(att.getNodeValue(), " ");
                    while (tokens.hasMoreElements()) {
                        nodeRole = tokens.nextElement().toString();
                        credential.postGroupRight(nodeRole, uuid, Credential.READ, portfolioUuid, userId);
                    }
                }
                att = attribMap.getNamedItem("delnoderoles");
                if (att != null) {
                    StringTokenizer tokens = new StringTokenizer(att.getNodeValue(), " ");
                    while (tokens.hasMoreElements()) {
                        nodeRole = tokens.nextElement().toString();
                        credential.postGroupRight(nodeRole, uuid, Credential.DELETE, portfolioUuid, userId);
                    }
                }
                att = attribMap.getNamedItem("editnoderoles");
                if (att != null) {
                    StringTokenizer tokens = new StringTokenizer(att.getNodeValue(), " ");
                    while (tokens.hasMoreElements()) {
                        nodeRole = tokens.nextElement().toString();
                        credential.postGroupRight(nodeRole, uuid, Credential.WRITE, portfolioUuid, userId);
                    }
                }
                att = attribMap.getNamedItem("submitroles");
                if (att != null) {
                    StringTokenizer tokens = new StringTokenizer(att.getNodeValue(), " ");
                    while (tokens.hasMoreElements()) {
                        nodeRole = tokens.nextElement().toString();
                        credential.postGroupRight(nodeRole, uuid, Credential.SUBMIT, portfolioUuid, userId);
                    }
                }
                att = attribMap.getNamedItem("seeresroles");
                if (att != null) {
                    StringTokenizer tokens = new StringTokenizer(att.getNodeValue(), " ");
                    while (tokens.hasMoreElements()) {
                        nodeRole = tokens.nextElement().toString();
                        credential.postGroupRight(nodeRole, uuid, Credential.READ, portfolioUuid, userId);
                    }
                }
                att = attribMap.getNamedItem("delresroles");
                if (att != null) {
                    StringTokenizer tokens = new StringTokenizer(att.getNodeValue(), " ");
                    while (tokens.hasMoreElements()) {
                        nodeRole = tokens.nextElement().toString();
                        credential.postGroupRight(nodeRole, uuid, Credential.DELETE, portfolioUuid, userId);
                    }
                }
                att = attribMap.getNamedItem("editresroles");
                if (att != null) {
                    StringTokenizer tokens = new StringTokenizer(att.getNodeValue(), " ");
                    while (tokens.hasMoreElements()) {
                        nodeRole = tokens.nextElement().toString();
                        credential.postGroupRight(nodeRole, uuid, Credential.WRITE, portfolioUuid, userId);
                    }
                }
                att = attribMap.getNamedItem("submitresroles");
                if (att != null) {
                    StringTokenizer tokens = new StringTokenizer(att.getNodeValue(), " ");
                    while (tokens.hasMoreElements()) {
                        nodeRole = tokens.nextElement().toString();
                        credential.postGroupRight(nodeRole, uuid, Credential.SUBMIT, portfolioUuid, userId);
                    }
                }
                Node actionroles = attribMap.getNamedItem("actionroles");
                if (actionroles != null) {
                    /// Format pour l'instant: actionroles="sender:1,2;responsable:4"
                    StringTokenizer tokens = new StringTokenizer(actionroles.getNodeValue(), ";");
                    while (tokens.hasMoreElements()) {
                        nodeRole = tokens.nextElement().toString();
                        StringTokenizer data = new StringTokenizer(nodeRole, ":");
                        String role = data.nextElement().toString();
                        String actions = data.nextElement().toString();
                        credential.postGroupRight(role, uuid, actions, portfolioUuid, userId);
                    }
                }

                Node notifyroles = attribMap.getNamedItem("notifyroles");
                if (notifyroles != null) {
                    /// Format pour l'instant: actionroles="sender:1,2;responsable:4"
                    StringTokenizer tokens = new StringTokenizer(notifyroles.getNodeValue(), " ");
                    String merge = "";
                    if (tokens.hasMoreElements())
                        merge = tokens.nextElement().toString();
                    while (tokens.hasMoreElements())
                        merge += "," + tokens.nextElement().toString();
                    postNotifyRoles(userId, portfolioUuid, uuid, merge);
                }

                meta = res.getString("metadata");
                nodeString = "<?xml version='1.0' encoding='UTF-8' standalone='no'?><transfer " + meta + "/>";
                is = new InputSource(new StringReader(nodeString));
                doc = documentBuilder.parse(is);
                attribNode = doc.getDocumentElement();
                attribMap = attribNode.getAttributes();

                try {
                    String publicatt = attribMap.getNamedItem("public").getNodeValue();
                    if ("Y".equals(publicatt))
                        setPublicState(userId, portfolioUuid, true);
                    else if ("N".equals(publicatt))
                        setPublicState(userId, portfolioUuid, false);
                } catch (Exception ex) {
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        res.close();
        st.close();

        /*
        /// Ajout des droits des noeuds
        sql = "INSERT INTO group_rights(grid, id, RD, WR, DL, SB, AD, types_id, rules_id) " +
              "SELECT g.grid, r.new_uuid, r.RD, r.WR, r.DL, r.SB, r.AD, r.types_id, r.rules_id " +
              "FROM " +
              "(SELECT gri.grid, gri.label " +
              "FROM node n " +
              "LEFT JOIN group_right_info gri ON n.portfolio_id=gri.portfolio_id " +
              "WHERE n.node_uuid=uuid2bin(?)) AS g," +  // Retrouve les groupes de destination via le noeud de destination
              "(SELECT gri.label, s.new_uuid, gr.RD, gr.WR, gr.DL, gr.SB, gr.AD, gr.types_id, gr.rules_id " +
              "FROM t_struc s, group_rights gr, group_right_info gri " +
              "WHERE s.uuid=gr.id AND gr.grid=gri.grid) AS r " + // Prend la liste des droits actuel des noeuds dupliqus
              "WHERE g.label=r.label"; // On croise le nouveau 'grid' avec le 'grid' d'origine via le label
        st = connection.prepareStatement(sql);
        st.setString(1, destUuid);
        st.executeUpdate();
        st.close();
                
        //         t22 = System.currentTimeMillis();
                
        /// Ajout des droits des resources
        // Apparement inutile si l'on s'en occupe qu'au niveau du contexte...
        sql = "INSERT INTO group_rights(grid, id, RD, WR, DL, SB, AD, types_id, rules_id) " +
              "SELECT gr.grid, r.new_uuid, gr.RD, gr.WR, gr.DL, gr.SB, gr.AD, gr.types_id, gr.rules_id " +
              "FROM t_res_node r " +
              "LEFT JOIN group_rights gr ON r.node_uuid=gr.id " +
              "LEFT JOIN group_info gi ON gr.grid=gi.grid " +
              "WHERE gi.gid=?";
        st = connection.prepareStatement(sql);
        st.setInt(1, groupId);
        st.executeUpdate();
        st.close();
        //*/

        //         end = System.currentTimeMillis();

        /// On rcupre le uuid cr
        sql = "SELECT bin2uuid(new_uuid) FROM t_data_node WHERE node_uuid=uuid2bin(?)";
        st = connection.prepareStatement(sql);
        st.setString(1, baseUuid);
        res = st.executeQuery();
        if (res.next())
            createdUuid = res.getString(1);
        res.close();
        st.close();
    } catch (Exception e) {
        try {
            createdUuid = "erreur: " + e.getMessage();
            if (connection.getAutoCommit() == false)
                connection.rollback();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
        e.printStackTrace();
    } finally {
        try {
            connection.setAutoCommit(true);
            // Les 'pooled connection' ne se ferment pas vraiment. On nettoie manuellement les tables temporaires...
            if (dbserveur.equals("mysql")) {
                sql = "DROP TEMPORARY TABLE IF EXISTS t_data_node, t_res_node, t_struc, t_struc_2";
                st = connection.prepareStatement(sql);
                st.execute();
                st.close();
            }

            touchPortfolio(destUuid, null);

            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /*
    System.out.println("---- Portfolio ---");
    System.out.println("d0-1: "+(t1-start));
    System.out.println("d1-2: "+(t2-t1));
    System.out.println("d2-3: "+(t3-t2));
    System.out.println("d3-4: "+(t4-t3));
    System.out.println("d4-5: "+(t5-t4));
    System.out.println("d5-6: "+(t6-t5));
    System.out.println("d6-7: "+(t7-t6));
    System.out.println("d7-8: "+(t8-t7));
    System.out.println("d8-9: "+(t9-t8));
    System.out.println("d9-10: "+(t10-t9));
    System.out.println("d10-11: "+(t11-t10));
    System.out.println("d11-12: "+(t12-t11));
    System.out.println("d12-13: "+(t13-t12));
    System.out.println("d13-14: "+(t14-t13));
    System.out.println("d14-15: "+(t15-t14));
    System.out.println("d15-16: "+(t16-t15));
    System.out.println("d16-17: "+(t17-t16));
    System.out.println("d17-18: "+(t18-t17));
    System.out.println("d18-19: "+(t19-t18));
    System.out.println("d19-20: "+(t20-t19));
    System.out.println("d20-21: "+(t21-t20));
    System.out.println("d21-22: "+(t22-t21));
    System.out.println("d22-23: "+(end-t22));
    System.out.println("------------------");
    //*/

    return createdUuid;
}

From source file:com.portfolio.data.provider.MysqlDataProvider.java

@Override
public String putInfUser(int userId, int userid2, String in) throws SQLException {
    String result1 = null;/* w  ww  . java  2 s  . c o m*/
    Integer id = 0;
    String password = null;
    String email = null;
    String username = null;
    String firstname = null;
    String lastname = null;
    String active = null;
    String is_admin = null;
    String is_designer = null;

    //On prepare les requetes SQL
    PreparedStatement st;
    String sql;

    //On recupere le body
    Document doc;
    Element infUser = null;
    try {
        doc = DomUtils.xmlString2Document(in, new StringBuffer());
        infUser = doc.getDocumentElement();
    } catch (Exception e) {
        e.printStackTrace();
    }

    NodeList children = null;

    children = infUser.getChildNodes();

    //      if(infUser.getNodeName().equals("users"))
    //      {
    //         for(int i=0;i<children.getLength();i++)
    //         {
    if (infUser.getNodeName().equals("user")) {
        //On recupere les attributs

        if (infUser.getAttributes().getNamedItem("id") != null) {
            id = Integer.parseInt(infUser.getAttributes().getNamedItem("id").getNodeValue());
        } else {
            id = null;
        }
        NodeList children2 = null;
        children2 = infUser.getChildNodes();
        for (int y = 0; y < children2.getLength(); y++) {
            if (children2.item(y).getNodeName().equals("username")) {
                username = DomUtils.getInnerXml(children2.item(y));

                sql = "UPDATE credential SET login = ? WHERE  userid = ?";

                st = connection.prepareStatement(sql);
                st.setString(1, username);
                st.setInt(2, userid2);
                st.executeUpdate();
            }
            if (children2.item(y).getNodeName().equals("password")) {
                password = DomUtils.getInnerXml(children2.item(y));

                sql = "UPDATE credential SET password = UNHEX(SHA1(?)) WHERE  userid = ?";
                if (dbserveur.equals("oracle")) {
                    sql = "UPDATE credential SET password = crypt(?) WHERE  userid = ?";
                }

                st = connection.prepareStatement(sql);
                st.setString(1, password);
                st.setInt(2, userid2);
                st.executeUpdate();
            }
            if (children2.item(y).getNodeName().equals("firstname")) {
                firstname = DomUtils.getInnerXml(children2.item(y));

                sql = "UPDATE credential SET display_firstname = ? WHERE  userid = ?";

                st = connection.prepareStatement(sql);
                st.setString(1, firstname);
                st.setInt(2, userid2);
                st.executeUpdate();
            }
            if (children2.item(y).getNodeName().equals("lastname")) {
                lastname = DomUtils.getInnerXml(children2.item(y));

                sql = "UPDATE credential SET display_lastname = ? WHERE  userid = ?";

                st = connection.prepareStatement(sql);
                st.setString(1, lastname);
                st.setInt(2, userid2);
                st.executeUpdate();
            }
            if (children2.item(y).getNodeName().equals("email")) {
                email = DomUtils.getInnerXml(children2.item(y));

                sql = "UPDATE credential SET email = ? WHERE  userid = ?";

                st = connection.prepareStatement(sql);
                st.setString(1, email);
                st.setInt(2, userid2);
                st.executeUpdate();
            }
            if (children2.item(y).getNodeName().equals("admin")) {
                is_admin = DomUtils.getInnerXml(children2.item(y));

                int is_adminInt = Integer.parseInt(is_admin);

                sql = "UPDATE credential SET is_admin = ? WHERE  userid = ?";

                st = connection.prepareStatement(sql);
                st.setInt(1, is_adminInt);
                st.setInt(2, userid2);
                st.executeUpdate();
            }
            //            /*
            if (children2.item(y).getNodeName().equals("designer")) {
                is_designer = DomUtils.getInnerXml(children2.item(y));

                int is_designerInt = Integer.parseInt(is_designer);

                sql = "UPDATE credential SET is_designer = ? WHERE  userid = ?";

                st = connection.prepareStatement(sql);
                st.setInt(1, is_designerInt);
                st.setInt(2, userid2);
                st.executeUpdate();
            }
            //*/
            if (children2.item(y).getNodeName().equals("active")) {
                active = DomUtils.getInnerXml(children2.item(y));

                int activeInt = Integer.parseInt(active);

                sql = "UPDATE credential SET active = ? WHERE  userid = ?";

                st = connection.prepareStatement(sql);
                st.setInt(1, activeInt);
                st.setInt(2, userid2);
                st.executeUpdate();
            }
        }
    }
    //         }

    //      }else{
    //         result = "Erreur lors de la recuperation des attributs du groupe dans le XML";
    //      }

    //         try {
    //
    //           sql = "UPDATE credential SET login = ?, display_firstname = ?, display_lastname = ?, password = ?, email = ? WHERE  userid = ?";
    //
    //            st = connection.prepareStatement(sql);
    //            st.setString(1, username);
    //            st.setString(2, firstname);
    //            st.setString(3, lastname);
    //            st.setString(4, password);
    //            st.setString(5, email);
    //            st.setInt(6, userid2);
    //
    //            st.executeUpdate();
    //
    //         } catch (SQLException e) {
    //            // TODO Auto-generated catch block
    //            e.printStackTrace();
    //         }
    //      result1 = "<users>";
    //
    //         result1 += "<user ";
    //         result1 += DomUtils.getXmlAttributeOutputInt("id", id)+" ";
    //         result1 += ">";
    //         result1 += DomUtils.getXmlElementOutput("password", password)+" ";
    //         result1 += DomUtils.getXmlElementOutput("email", password)+" ";
    //         result1 += "</user>";
    //      result1 += "</users>";

    result1 = "" + userid2;

    return result1;
}

From source file:com.portfolio.data.provider.MysqlDataProvider.java

@Override
public Object postInstanciatePortfolio(MimeType inMimeType, String portfolioUuid, String srcCode,
        String newCode, int userId, int groupId, boolean copyshared, String portfGroupName) throws Exception {
    String sql = "";
    PreparedStatement st;/*  ww  w .ja va  2  s. c  om*/
    String newPortfolioUuid = UUID.randomUUID().toString();

    try {
        /// Find source code
        if (srcCode != null) {
            /// Find back portfolio uuid from source code
            sql = "SELECT bin2uuid(portfolio_id) AS uuid FROM node WHERE code=?";
            st = connection.prepareStatement(sql);
            st.setString(1, srcCode);
            ResultSet res = st.executeQuery();
            if (res.next())
                portfolioUuid = res.getString("uuid");
        }

        if (portfolioUuid == null)
            return "";

        ///// Cration des tables temporaires
        /// Pour la copie de la structure
        if (dbserveur.equals("mysql")) {
            sql = "CREATE TEMPORARY TABLE t_data(" + "new_uuid binary(16) NOT NULL, " + /// Pour la copie d'une nouvelle structure
                    "node_uuid binary(16)  NOT NULL, " + "node_parent_uuid binary(16) DEFAULT NULL, "
                    + "node_children_uuid blob, " + "node_order int(12) NOT NULL, " + "metadata text NOT NULL, "
                    + "metadata_wad text NOT NULL, " + "metadata_epm text NOT NULL, "
                    + "res_node_uuid binary(16) DEFAULT NULL, " + "res_res_node_uuid binary(16) DEFAULT NULL, "
                    + "res_context_node_uuid binary(16)  DEFAULT NULL, " + "shared_res int(1) NOT NULL, "
                    + "shared_node int(1) NOT NULL, " + "shared_node_res int(1) NOT NULL, "
                    + "shared_res_uuid BINARY(16)  NULL, " + "shared_node_uuid BINARY(16) NULL, "
                    + "shared_node_res_uuid BINARY(16) NULL, " + "asm_type varchar(50) DEFAULT NULL, "
                    + "xsi_type varchar(50)  DEFAULT NULL, " + "semtag varchar(250) DEFAULT NULL, "
                    + "semantictag varchar(250) DEFAULT NULL, " + "label varchar(250)  DEFAULT NULL, "
                    + "code varchar(250)  DEFAULT NULL, " + "descr varchar(250)  DEFAULT NULL, "
                    + "format varchar(30) DEFAULT NULL, " + "modif_user_id int(12) NOT NULL, "
                    + "modif_date timestamp NULL DEFAULT NULL, "
                    + "portfolio_id binary(16) DEFAULT NULL) DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
            st = connection.prepareStatement(sql);
            st.execute();
            st.close();
        } else if (dbserveur.equals("oracle")) {
            String v_sql = "CREATE GLOBAL TEMPORARY TABLE t_data(" + "new_uuid RAW(16) NOT NULL, " + /// Pour la copie d'une nouvelle structure
                    "node_uuid RAW(16)  NOT NULL, " + "node_parent_uuid RAW(16) DEFAULT NULL, "
                    + "node_children_uuid CLOB, " + "node_order NUMBER(12) NOT NULL, "
                    + "metadata CLOB DEFAULT NULL, " + "metadata_wad CLOB DEFAULT NULL, "
                    + "metadata_epm CLOB DEFAULT NULL, " + "res_node_uuid RAW(16) DEFAULT NULL, "
                    + "res_res_node_uuid RAW(16) DEFAULT NULL, "
                    + "res_context_node_uuid RAW(16)  DEFAULT NULL, " + "shared_res NUMBER(1) NOT NULL, "
                    + "shared_node NUMBER(1) NOT NULL, " + "shared_node_res NUMBER(1) NOT NULL, "
                    + "shared_res_uuid RAW(16) DEFAULT NULL, " + "shared_node_uuid RAW(16) DEFAULT NULL, "
                    + "shared_node_res_uuid RAW(16) DEFAULT NULL, "
                    + "asm_type VARCHAR2(50 CHAR) DEFAULT NULL, " + "xsi_type VARCHAR2(50 CHAR)  DEFAULT NULL, "
                    + "semtag VARCHAR2(250 CHAR) DEFAULT NULL, "
                    + "semantictag VARCHAR2(250 CHAR) DEFAULT NULL, "
                    + "label VARCHAR2(250 CHAR)  DEFAULT NULL, " + "code VARCHAR2(250 CHAR)  DEFAULT NULL, "
                    + "descr VARCHAR2(250 CHAR)  DEFAULT NULL, " + "format VARCHAR2(30 CHAR) DEFAULT NULL, "
                    + "modif_user_id NUMBER(12) NOT NULL, " + "modif_date timestamp DEFAULT NULL, "
                    + "portfolio_id RAW(16) DEFAULT NULL) ON COMMIT PRESERVE ROWS";
            sql = "{call create_or_empty_table('t_data','" + v_sql + "')}";
            CallableStatement ocs = connection.prepareCall(sql);
            ocs.execute();
            ocs.close();
        }

        /// Pour la copie des donnes
        if (dbserveur.equals("mysql")) {
            sql = "CREATE TEMPORARY TABLE t_res(" + "new_uuid binary(16) NOT NULL, " + /// Pour la copie d'une nouvelle structure
                    "node_uuid binary(16) NOT NULL, " + "xsi_type varchar(50) NOT NULL, " + "content text, "
                    + "user_id int(11) DEFAULT NULL, " + "modif_user_id int(12) NOT NULL, "
                    + "modif_date timestamp NULL DEFAULT NULL) DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
            st = connection.prepareStatement(sql);
            st.execute();
            st.close();
        } else if (dbserveur.equals("oracle")) {
            String v_sql = "CREATE GLOBAL TEMPORARY TABLE t_res(" + "new_uuid RAW(16) NOT NULL, " + /// Pour la copie d'une nouvelle structure
                    "node_uuid RAW(16) NOT NULL, " + "xsi_type VARCHAR2(50 CHAR) NOT NULL, " + "content CLOB, "
                    + "user_id NUMBER(11) DEFAULT NULL, " + "modif_user_id NUMBER(12) NOT NULL, "
                    + "modif_date timestamp DEFAULT NULL) ON COMMIT PRESERVE ROWS";
            sql = "{call create_or_empty_table('t_res','" + v_sql + "')}";
            CallableStatement ocs = connection.prepareCall(sql);
            ocs.execute();
            ocs.close();
        }

        /// Pour la mise  jour de la liste des enfants/parents
        if (dbserveur.equals("mysql")) {
            sql = "CREATE TEMPORARY TABLE t_struc(" + "node_order int(12) NOT NULL, "
                    + "new_uuid binary(16) NOT NULL, " + "uuid binary(16) UNIQUE NOT NULL, "
                    + "node_parent_uuid binary(16), "
                    + "t_level INT) DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
            st = connection.prepareStatement(sql);
            st.execute();
            st.close();
        } else if (dbserveur.equals("oracle")) {
            String v_sql = "CREATE GLOBAL TEMPORARY TABLE t_struc(" + "node_order NUMBER(12) NOT NULL, "
                    + "new_uuid RAW(16) NOT NULL, " + "uuid RAW(16) NOT NULL, " + "node_parent_uuid RAW(16), "
                    + "t_level NUMBER(10,0)"
                    + ",  CONSTRAINT t_struc_UK_uuid UNIQUE (uuid)) ON COMMIT PRESERVE ROWS";
            sql = "{call create_or_empty_table('t_struc','" + v_sql + "')}";
            CallableStatement ocs = connection.prepareCall(sql);
            ocs.execute();
            ocs.close();
        }

        /// Pour l'histoire des shared_node a filtrer
        if (dbserveur.equals("mysql")) {
            sql = "CREATE TEMPORARY TABLE t_struc_2(" + "node_order int(12) NOT NULL, "
                    + "new_uuid binary(16) NOT NULL, " + "uuid binary(16) UNIQUE NOT NULL, "
                    + "node_parent_uuid binary(16), "
                    + "t_level INT) DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
            st = connection.prepareStatement(sql);
            st.execute();
            st.close();
        } else if (dbserveur.equals("oracle")) {
            String v_sql = "CREATE GLOBAL TEMPORARY TABLE t_struc_2(" + "node_order NUMBER(12) NOT NULL, "
                    + "new_uuid RAW(16) NOT NULL, " + "uuid RAW(16) NOT NULL, " + "node_parent_uuid RAW(16), "
                    + "t_level NUMBER(10,0)"
                    + ",  CONSTRAINT t_struc_2_UK_uuid UNIQUE (uuid)) ON COMMIT PRESERVE ROWS";
            sql = "{call create_or_empty_table('t_struc_2','" + v_sql + "')}";
            CallableStatement ocs = connection.prepareCall(sql);
            ocs.execute();
            ocs.close();
        }

        /// Pour les nouveaux ensembles de droits
        if (dbserveur.equals("mysql")) {
            sql = "CREATE TEMPORARY TABLE t_rights(" + "grid BIGINT NOT NULL, " + "id binary(16) NOT NULL, "
                    + "RD BOOL NOT NULL, " + "WR BOOL NOT NULL, " + "DL BOOL NOT NULL, " + "SB BOOL NOT NULL, "
                    + "AD BOOL NOT NULL, " + "types_id TEXT, "
                    + "rules_id TEXT) DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
            st = connection.prepareStatement(sql);
            st.execute();
            st.close();
        } else if (dbserveur.equals("oracle")) {
            String v_sql = "CREATE GLOBAL TEMPORARY TABLE t_rights(" + "grid NUMBER(19,0) NOT NULL, "
                    + "id RAW(16) NOT NULL, " + "RD NUMBER(1) NOT NULL, " + "WR NUMBER(1) NOT NULL, "
                    + "DL NUMBER(1) NOT NULL, " + "SB NUMBER(1) NOT NULL, " + "AD NUMBER(1) NOT NULL, "
                    + "types_id VARCHAR2(2000 CHAR), "
                    + "rules_id VARCHAR2(2000 CHAR)) ON COMMIT PRESERVE ROWS";
            sql = "{call create_or_empty_table('t_rights','" + v_sql + "')}";
            CallableStatement ocs = connection.prepareCall(sql);
            ocs.execute();
            ocs.close();
        }

        /// Copie de la structure
        sql = "INSERT INTO t_data(new_uuid, node_uuid, node_parent_uuid, node_children_uuid, node_order, metadata, metadata_wad, metadata_epm, res_node_uuid, res_res_node_uuid, res_context_node_uuid , shared_res, shared_node, shared_node_res, shared_res_uuid, shared_node_uuid, shared_node_res_uuid, asm_type, xsi_type, semtag, semantictag, label, code, descr, format, modif_user_id, modif_date, portfolio_id) ";
        if (dbserveur.equals("mysql")) {
            sql += "SELECT uuid2bin(UUID()), ";
        } else if (dbserveur.equals("oracle")) {
            sql += "SELECT sys_guid(), ";
        }
        sql += "node_uuid, node_parent_uuid, node_children_uuid, node_order, metadata, metadata_wad, metadata_epm, res_node_uuid, res_res_node_uuid, res_context_node_uuid , shared_res, shared_node, shared_node_res, shared_res_uuid, shared_node_uuid, shared_node_res_uuid, asm_type, xsi_type, semtag, semantictag, label, code, descr, format, modif_user_id, modif_date, portfolio_id "
                + "FROM node n " + "WHERE portfolio_id=uuid2bin(?)";
        st = connection.prepareStatement(sql);
        st.setString(1, portfolioUuid);
        st.executeUpdate();
        st.close();

        if (!copyshared) {
            /// Liste les noeud a filtrer
            sql = "INSERT INTO t_struc(node_order, new_uuid, uuid, node_parent_uuid, t_level) "
                    + "SELECT node_order, new_uuid, node_uuid, node_parent_uuid, 0 FROM t_data WHERE shared_node=1";
            st = connection.prepareStatement(sql);
            st.executeUpdate();
            st.close();

            int level = 0;
            int added = 1;
            if (dbserveur.equals("mysql")) {
                sql = "INSERT IGNORE INTO t_struc_2(node_order, new_uuid, uuid, node_parent_uuid, t_level) ";
            } else if (dbserveur.equals("oracle")) {
                sql = "INSERT /*+ ignore_row_on_dupkey_index(t_struc_2,t_struc_2_UK_uuid)*/ INTO t_struc_2(node_order, new_uuid, uuid, node_parent_uuid, t_level) ";
            }
            sql += "SELECT d.node_order, d.new_uuid, d.node_uuid, d.node_parent_uuid, ? "
                    + "FROM t_data d WHERE d.node_parent_uuid IN (SELECT uuid FROM t_struc t "
                    + "WHERE t.t_level=?)";

            String sqlTemp = null;
            if (dbserveur.equals("mysql")) {
                sqlTemp = "INSERT IGNORE INTO t_struc SELECT * FROM t_struc_2;";
            } else if (dbserveur.equals("oracle")) {
                sqlTemp = "INSERT /*+ ignore_row_on_dupkey_index(t_struc,t_struc_UK_uuid)*/ INTO t_struc SELECT * FROM t_struc_2";
            }
            PreparedStatement stTemp = connection.prepareStatement(sqlTemp);

            st = connection.prepareStatement(sql);
            while (added != 0) {
                st.setInt(1, level + 1);
                st.setInt(2, level);
                st.executeUpdate();
                added = stTemp.executeUpdate(); // On s'arrte quand rien  t ajout
                level = level + 1; // Prochaine tape
            }
            st.close();
            stTemp.close();

            // Retire les noeuds en dessous du shared
            sql = "DELETE FROM t_struc WHERE uuid IN (SELECT node_uuid FROM t_data WHERE shared_node=1)";
            st = connection.prepareStatement(sql);
            st.executeUpdate();
            st.close();

            sql = "DELETE FROM t_data WHERE node_uuid IN (SELECT uuid FROM t_struc)";
            st = connection.prepareStatement(sql);
            st.executeUpdate();
            st.close();

            sql = "DELETE FROM t_struc";
            st = connection.prepareStatement(sql);
            st.executeUpdate();
            st.close();

        }

        /// Copie les uuid pour la rsolution des parents/enfants
        sql = "INSERT INTO t_struc(node_order, new_uuid, uuid, node_parent_uuid) "
                + "SELECT node_order, new_uuid, node_uuid, node_parent_uuid FROM t_data";
        st = connection.prepareStatement(sql);
        st.executeUpdate();
        st.close();

        if (!copyshared) {
            /// Cas spcial pour shared_node=1
            // Le temps qu'on refasse la liste des enfants, on va enlever le noeud plus tard
            sql = "UPDATE t_data SET shared_node_uuid=node_uuid WHERE shared_node=1";
            st = connection.prepareStatement(sql);
            st.executeUpdate();
            st.close();

            // Met a jour t_struc pour la redirection. C'est pour la list des enfants
            // FIXME: A vrifier les appels qui modifie la liste des enfants.
            if (dbserveur.equals("mysql")) {
                sql = "UPDATE t_struc s INNER JOIN t_data d ON s.uuid=d.node_uuid "
                        + "SET s.new_uuid=d.node_uuid WHERE d.shared_node=1";
            } else if (dbserveur.equals("oracle")) {
                sql = "UPDATE t_struc s SET s.new_uuid=(SELECT d.node_uuid FROM t_struc s2 INNER JOIN t_data d ON s2.uuid=d.node_uuid WHERE d.shared_node=1) WHERE EXISTS (SELECT 1 FROM t_struc s2 INNER JOIN t_data d ON s2.uuid=d.node_uuid WHERE d.shared_node=1)";
            }
            st = connection.prepareStatement(sql);
            st.executeUpdate();
            st.close();
        }

        /// Copie des donnes non partags (shared=0)
        // Specific
        sql = "INSERT INTO t_res(new_uuid, node_uuid, xsi_type, content, user_id, modif_user_id, modif_date) ";
        if (dbserveur.equals("mysql")) {
            sql += "SELECT uuid2bin(UUID()), ";
        } else if (dbserveur.equals("oracle")) {
            sql += "SELECT sys_guid(), ";
        }
        sql += "r.node_uuid, r.xsi_type, r.content, r.user_id, r.modif_user_id, r.modif_date "
                + "FROM t_data d " + "LEFT JOIN resource_table r ON d.res_node_uuid=r.node_uuid " + "WHERE ";
        if (!copyshared)
            sql += "shared_res=0 AND ";
        if (dbserveur.equals("mysql")) {
            sql += "d.res_node_uuid <> 0x0000000000000000000000000000000"; // Binaire non null
        } else if (dbserveur.equals("oracle")) {
            sql += "d.res_node_uuid <> '00000000000000000000000000000000'"; // Binaire non null
        }
        st = connection.prepareStatement(sql);
        st.executeUpdate();
        st.close();

        sql = "INSERT INTO t_res(new_uuid, node_uuid, xsi_type, content, user_id, modif_user_id, modif_date) ";
        if (dbserveur.equals("mysql")) {
            sql += "SELECT uuid2bin(UUID()), ";
        } else if (dbserveur.equals("oracle")) {
            sql += "SELECT sys_guid(), ";
        }
        sql += "r.node_uuid, r.xsi_type, r.content, r.user_id, r.modif_user_id, r.modif_date "
                + "FROM t_data d " + "LEFT JOIN resource_table r ON d.res_context_node_uuid=r.node_uuid "
                + "WHERE ";
        if (!copyshared)
            sql += "shared_node=0 AND ";
        if (dbserveur.equals("mysql")) {
            sql += "d.res_context_node_uuid <> 0x0000000000000000000000000000000";
        } else if (dbserveur.equals("oracle")) {
            sql += "d.res_context_node_uuid <> '00000000000000000000000000000000'";
        }
        st = connection.prepareStatement(sql);
        st.executeUpdate();
        st.close();

        // nodeRes
        sql = "INSERT INTO t_res(new_uuid, node_uuid, xsi_type, content, user_id, modif_user_id, modif_date) ";
        if (dbserveur.equals("mysql")) {
            sql += "SELECT uuid2bin(UUID()), ";
        } else if (dbserveur.equals("oracle")) {
            sql += "SELECT sys_guid(), ";
        }
        sql += "r.node_uuid, r.xsi_type, r.content, r.user_id, r.modif_user_id, r.modif_date "
                + "FROM t_data d " + "LEFT JOIN resource_table r ON d.res_res_node_uuid=r.node_uuid "
                + "WHERE ";
        if (!copyshared)
            sql += "shared_node_res=0 AND ";
        if (dbserveur.equals("mysql")) {
            sql += "d.res_res_node_uuid <> 0x0000000000000000000000000000000";
        } else if (dbserveur.equals("oracle")) {
            sql += "d.res_res_node_uuid <> '00000000000000000000000000000000'";
        }
        st = connection.prepareStatement(sql);
        st.executeUpdate();
        st.close();

        /// Changement du uuid du portfolio
        sql = "UPDATE t_data t SET t.portfolio_id=uuid2bin(?)";
        st = connection.prepareStatement(sql);
        st.setString(1, newPortfolioUuid);
        st.executeUpdate();
        st.close();

        /// Rsolution des nouveaux uuid avec les parents
        // Avec la structure (et droits sur la structure)
        if (dbserveur.equals("mysql")) {
            sql = "UPDATE t_rights ri, t_data d SET ri.id=d.new_uuid WHERE ri.id=d.node_uuid AND d.shared_node=0";
        } else if (dbserveur.equals("oracle")) {
            sql = "UPDATE t_rights ri SET ri.id=(SELECT new_uuid FROM t_data d WHERE ri.id=d.node_uuid AND d.shared_node=0) WHERE EXISTS (SELECT 1 FROM t_data d WHERE ri.id=d.node_uuid AND d.shared_node=0)";
        }
        st = connection.prepareStatement(sql);
        st.executeUpdate();
        st.close();

        sql = "UPDATE t_data t "
                + "SET t.node_parent_uuid = (SELECT new_uuid FROM t_struc s WHERE s.uuid=t.node_parent_uuid)";
        st = connection.prepareStatement(sql);
        st.executeUpdate();
        st.close();

        // Avec les ressources (et droits des ressources)
        if (dbserveur.equals("mysql")) {
            sql = "UPDATE t_rights ri, t_res re SET ri.id = re.new_uuid WHERE re.node_uuid=ri.id";
        } else if (dbserveur.equals("oracle")) {
            sql = "UPDATE t_rights ri SET ri.id=(SELECT new_uuid FROM t_res re WHERE re.node_uuid=ri.id) WHERE EXISTS (SELECT 1 FROM t_res re WHERE re.node_uuid=ri.id)";
        }
        st = connection.prepareStatement(sql);
        st.executeUpdate();
        st.close();

        if (dbserveur.equals("mysql")) {
            sql = "UPDATE t_data d INNER JOIN t_res r ON d.res_node_uuid=r.node_uuid "
                    + "SET d.res_node_uuid=r.new_uuid";
        } else if (dbserveur.equals("oracle")) {
            sql = "UPDATE t_data d SET d.res_node_uuid=(SELECT r.new_uuid FROM t_res r WHERE d.res_node_uuid=r.node_uuid) WHERE EXISTS (SELECT 1 FROM t_res r WHERE d.res_node_uuid=r.node_uuid)";
        }
        st = connection.prepareStatement(sql);
        st.executeUpdate();
        st.close();

        if (dbserveur.equals("mysql")) {
            sql = "UPDATE t_data d INNER JOIN t_res r ON d.res_res_node_uuid=r.node_uuid "
                    + "SET d.res_res_node_uuid=r.new_uuid";
        } else if (dbserveur.equals("oracle")) {
            sql = "UPDATE t_data d SET d.res_res_node_uuid=(SELECT r.new_uuid FROM t_res r WHERE d.res_res_node_uuid=r.node_uuid) WHERE EXISTS (SELECT 1 FROM t_res r WHERE d.res_res_node_uuid=r.node_uuid)";
        }
        st = connection.prepareStatement(sql);
        st.executeUpdate();
        st.close();

        if (dbserveur.equals("mysql")) {
            sql = "UPDATE t_data d INNER JOIN t_res r ON d.res_context_node_uuid=r.node_uuid "
                    + "SET d.res_context_node_uuid=r.new_uuid";
        } else if (dbserveur.equals("oracle")) {
            sql = "UPDATE t_data d SET d.res_context_node_uuid=(SELECT r.new_uuid FROM t_res r WHERE d.res_context_node_uuid=r.node_uuid) WHERE EXISTS (SELECT 1 FROM t_res r WHERE d.res_context_node_uuid=r.node_uuid)";
        }
        st = connection.prepareStatement(sql);
        st.executeUpdate();
        st.close();

        /// Mise  jour de la liste des enfants (! requte particulire)
        /// L'ordre dtermine le rendu visuel final du xml
        if (dbserveur.equals("mysql")) {
            sql = "UPDATE t_data d, ("
                    + "SELECT node_parent_uuid, GROUP_CONCAT(bin2uuid(s.new_uuid) ORDER BY s.node_order) AS value "
                    + "FROM t_struc s GROUP BY s.node_parent_uuid) tmp " + "SET d.node_children_uuid=tmp.value "
                    + "WHERE tmp.node_parent_uuid=d.node_uuid";
        } else if (dbserveur.equals("oracle")) {
            sql = "UPDATE t_data d SET d.node_children_uuid=(SELECT value FROM (SELECT node_parent_uuid, LISTAGG(bin2uuid(s.new_uuid), ',') WITHIN GROUP (ORDER BY s.node_order) AS value FROM t_struc s GROUP BY s.node_parent_uuid) tmp WHERE tmp.node_parent_uuid=d.node_uuid) WHERE EXISTS (SELECT 1 FROM t_struc WHERE node_parent_uuid=d.node_uuid)";
        }
        st = connection.prepareStatement(sql);
        st.executeUpdate();
        st.close();

        // Mise  jour du code dans le contenu du noeud (blech)
        if (dbserveur.equals("mysql")) {
            sql = "UPDATE t_data d " + "LEFT JOIN t_res r ON d.res_res_node_uuid=r.new_uuid " + // Il faut utiliser le nouveau uuid
                    "SET r.content=REPLACE(r.content, d.code, ?) " + "WHERE d.asm_type='asmRoot'";
        } else if (dbserveur.equals("oracle")) {
            sql = "UPDATE t_res r SET r.content=(SELECT REPLACE(r2.content, d.code, ?) FROM t_data d LEFT JOIN t_res r2 ON d.res_res_node_uuid=r2.new_uuid WHERE d.asm_type='asmRoot') WHERE EXISTS (SELECT 1 FROM t_data d WHERE d.res_res_node_uuid=r.new_uuid AND d.asm_type='asmRoot')";
        }
        st = connection.prepareStatement(sql);
        st.setString(1, newCode);
        st.executeUpdate();
        st.close();

        // Mise  jour du code dans le code interne de la BD
        sql = "UPDATE t_data d SET d.code=? WHERE d.asm_type='asmRoot'";
        st = connection.prepareStatement(sql);
        st.setString(1, newCode);
        st.executeUpdate();
        st.close();

        /// temp class
        class right {
            int rd = 0;
            int wr = 0;
            int dl = 0;
            int sb = 0;
            int ad = 0;
            String types = "";
            String rules = "";
            String notify = "";
        }
        ;

        class groupright {
            right getGroup(String label) {
                right r = rights.get(label.trim());
                if (r == null) {
                    r = new right();
                    rights.put(label, r);
                }
                return r;
            }

            void setNotify(String roles) {
                Iterator<right> iter = rights.values().iterator();
                while (iter.hasNext()) {
                    right r = iter.next();
                    r.notify = roles.trim();
                }
            }

            HashMap<String, right> rights = new HashMap<String, right>();
        }
        ;

        class resolver {
            groupright getUuid(String uuid) {
                groupright gr = resolve.get(uuid);
                if (gr == null) {
                    gr = new groupright();
                    resolve.put(uuid, gr);
                }
                return gr;
            };

            HashMap<String, groupright> resolve = new HashMap<String, groupright>();
            HashMap<String, Integer> groups = new HashMap<String, Integer>();
        }
        ;

        resolver resolve = new resolver();

        /// Cre les groupes de droits en les copiants dans la table d'origine
        // Slectionne les groupes concerns
        /*
        sql = "SELECT login FROM credential c WHERE c.userid=?";
        st = connection.prepareStatement(sql);
        st.setInt(1, userId);
        ResultSet res = st.executeQuery();
                
        String login="";
        if( res.next() )
           login = res.getString("login");
        //*/

        // Selection des metadonnes
        sql = "SELECT bin2uuid(t.new_uuid) AS uuid, bin2uuid(t.portfolio_id) AS puuid, t.metadata, t.metadata_wad, t.metadata_epm "
                + "FROM t_data t";
        st = connection.prepareStatement(sql);
        ResultSet res = st.executeQuery();

        DocumentBuilder documentBuilder;
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        while (res.next()) {
            String uuid = res.getString("uuid");
            //           String puuid = res.getString("puuid");
            String meta = res.getString("metadata_wad");
            //          meta = meta.replaceAll("user", login);
            String nodeString = "<?xml version='1.0' encoding='UTF-8' standalone='no'?><transfer " + meta
                    + "/>";

            groupright role = resolve.getUuid(uuid);

            try {
                /// parse meta
                InputSource is = new InputSource(new StringReader(nodeString));
                Document doc = documentBuilder.parse(is);

                /// Process attributes
                Element attribNode = doc.getDocumentElement();
                NamedNodeMap attribMap = attribNode.getAttributes();

                String nodeRole;
                Node att = attribMap.getNamedItem("access");
                if (att != null) {
                    //if(access.equalsIgnoreCase("public") || access.contains("public"))
                    //   credential.postGroupRight("all",uuid,Credential.READ,portfolioUuid,userId);
                }
                att = attribMap.getNamedItem("seenoderoles");
                if (att != null) {
                    StringTokenizer tokens = new StringTokenizer(att.getNodeValue(), " ");
                    while (tokens.hasMoreElements()) {
                        nodeRole = tokens.nextElement().toString();

                        right r = role.getGroup(nodeRole);
                        r.rd = 1;

                        resolve.groups.put(nodeRole, 0);
                    }
                }
                att = attribMap.getNamedItem("showtoroles");
                if (att != null) {
                    StringTokenizer tokens = new StringTokenizer(att.getNodeValue(), " ");
                    while (tokens.hasMoreElements()) {
                        nodeRole = tokens.nextElement().toString();

                        right r = role.getGroup(nodeRole);
                        r.rd = 0;

                        resolve.groups.put(nodeRole, 0);
                    }
                }
                att = attribMap.getNamedItem("delnoderoles");
                if (att != null) {
                    StringTokenizer tokens = new StringTokenizer(att.getNodeValue(), " ");
                    while (tokens.hasMoreElements()) {

                        nodeRole = tokens.nextElement().toString();
                        right r = role.getGroup(nodeRole);
                        r.dl = 1;

                        resolve.groups.put(nodeRole, 0);
                    }
                }
                att = attribMap.getNamedItem("editnoderoles");
                if (att != null) {
                    StringTokenizer tokens = new StringTokenizer(att.getNodeValue(), " ");
                    while (tokens.hasMoreElements()) {
                        nodeRole = tokens.nextElement().toString();
                        right r = role.getGroup(nodeRole);
                        r.wr = 1;

                        resolve.groups.put(nodeRole, 0);
                    }
                }
                att = attribMap.getNamedItem("submitnoderoles");
                if (att != null) {
                    StringTokenizer tokens = new StringTokenizer(att.getNodeValue(), " ");
                    while (tokens.hasMoreElements()) {
                        nodeRole = tokens.nextElement().toString();
                        right r = role.getGroup(nodeRole);
                        r.sb = 1;

                        resolve.groups.put(nodeRole, 0);
                    }
                }
                att = attribMap.getNamedItem("seeresroles");
                if (att != null) {
                    StringTokenizer tokens = new StringTokenizer(att.getNodeValue(), " ");
                    while (tokens.hasMoreElements()) {
                        nodeRole = tokens.nextElement().toString();
                        right r = role.getGroup(nodeRole);
                        r.rd = 1;

                        resolve.groups.put(nodeRole, 0);
                    }
                }
                att = attribMap.getNamedItem("delresroles");
                if (att != null) {
                    StringTokenizer tokens = new StringTokenizer(att.getNodeValue(), " ");
                    while (tokens.hasMoreElements()) {
                        nodeRole = tokens.nextElement().toString();
                        right r = role.getGroup(nodeRole);
                        r.dl = 1;

                        resolve.groups.put(nodeRole, 0);
                    }
                }
                att = attribMap.getNamedItem("editresroles");
                if (att != null) {
                    StringTokenizer tokens = new StringTokenizer(att.getNodeValue(), " ");
                    while (tokens.hasMoreElements()) {
                        nodeRole = tokens.nextElement().toString();
                        right r = role.getGroup(nodeRole);
                        r.wr = 1;

                        resolve.groups.put(nodeRole, 0);
                    }
                }
                att = attribMap.getNamedItem("submitresroles");
                if (att != null) {
                    StringTokenizer tokens = new StringTokenizer(att.getNodeValue(), " ");
                    while (tokens.hasMoreElements()) {
                        nodeRole = tokens.nextElement().toString();
                        right r = role.getGroup(nodeRole);
                        r.sb = 1;

                        resolve.groups.put(nodeRole, 0);
                    }
                }
                Node actionroles = attribMap.getNamedItem("actionroles");
                if (actionroles != null) {
                    /// Format pour l'instant: actionroles="sender:1,2;responsable:4"
                    StringTokenizer tokens = new StringTokenizer(actionroles.getNodeValue(), ";");
                    while (tokens.hasMoreElements()) {
                        nodeRole = tokens.nextElement().toString();
                        StringTokenizer data = new StringTokenizer(nodeRole, ":");
                        String nrole = data.nextElement().toString();
                        String actions = data.nextElement().toString().trim();
                        right r = role.getGroup(nrole);
                        r.rules = actions;

                        resolve.groups.put(nrole, 0);
                    }
                }
                Node menuroles = attribMap.getNamedItem("menuroles");
                if (menuroles != null) {
                    /// Pour les diffrents items du menu
                    StringTokenizer menuline = new StringTokenizer(menuroles.getNodeValue(), ";");

                    while (menuline.hasMoreTokens()) {
                        String line = menuline.nextToken();
                        /// Format pour l'instant: mi6-parts,mission,Ajouter une mission,secret_agent
                        StringTokenizer tokens = new StringTokenizer(line, ",");
                        String menurolename = null;
                        for (int t = 0; t < 4; ++t)
                            menurolename = tokens.nextToken();

                        if (menurolename != null)
                            resolve.groups.put(menurolename.trim(), 0);
                    }
                }
                Node notifyroles = attribMap.getNamedItem("notifyroles");
                if (notifyroles != null) {
                    /// Format pour l'instant: notifyroles="sender responsable"
                    StringTokenizer tokens = new StringTokenizer(notifyroles.getNodeValue(), " ");
                    String merge = "";
                    if (tokens.hasMoreElements())
                        merge = tokens.nextElement().toString().trim();
                    while (tokens.hasMoreElements())
                        merge += "," + tokens.nextElement().toString().trim();
                    role.setNotify(merge);
                }

                // No need to set public on multiple portoflio
                /*
                meta = res.getString("metadata");
                nodeString = "<?xml version='1.0' encoding='UTF-8' standalone='no'?><transfer "+meta+"/>";
                is = new InputSource(new StringReader(nodeString));
                doc = documentBuilder.parse(is);
                attribNode = doc.getDocumentElement();
                attribMap = attribNode.getAttributes();
                        
                boolean isPublic = false;
                try
                {
                   String publicatt = attribMap.getNamedItem("public").getNodeValue();
                   if( "Y".equals(publicatt) )
                      isPublic = true;
                }
                catch(Exception ex) {}
                setPublicState(userId, puuid, isPublic);
                //*/

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        res.close();
        st.close();

        /*
        sql = "SELECT grid FROM group_right_info " +
              "WHERE portfolio_id=uuid2bin(?)";
        st = connection.prepareStatement(sql);
        st.setString(1, portfolioUuid);
        ResultSet res = st.executeQuery();
                
        /// Pour chaque grid, on en cr un nouveau et met  jour nos nouveaux droits
        sql = "INSERT INTO group_right_info(owner, label, change_rights, portfolio_id) " +
              "SELECT owner, label, change_rights, uuid2bin(?) FROM group_right_info WHERE grid=?";
        st = connection.prepareStatement(sql);
        st.setString(1, newPortfolioUuid);
                
        if (dbserveur.equals("mysql")){
           sql = "UPDATE t_rights SET grid=LAST_INSERT_ID() WHERE grid=?";
        } else if (dbserveur.equals("oracle")){
             sql = "UPDATE t_rights SET grid=group_right_info_SEQ.CURRVAL WHERE grid=?";
        }
        PreparedStatement stUpd = connection.prepareStatement(sql);
                
        while( res.next() )
        {
           int grid = res.getInt("grid");
           st.setInt(2, grid);
           st.executeUpdate();   // Ajout du nouveau rrg
                
           stUpd.setInt(1, grid);
           stUpd.executeUpdate();  /// Met a jour la table de droit temporaire
        }
        st.close();
        //*/

        connection.setAutoCommit(false);

        /// On insre les donnes pr-compil
        Iterator<String> entries = resolve.groups.keySet().iterator();

        // Cr les groupes, ils n'existent pas
        String grquery = "INSERT INTO group_info(grid,owner,label) " + "VALUES(?,?,?)";
        PreparedStatement st2 = connection.prepareStatement(grquery);
        String gri = "INSERT INTO group_right_info(owner, label, change_rights, portfolio_id) "
                + "VALUES(?,?,?,uuid2bin(?))";
        st = connection.prepareStatement(gri, Statement.RETURN_GENERATED_KEYS);
        if (dbserveur.equals("oracle")) {
            st = connection.prepareStatement(gri, new String[] { "grid" });
        }

        while (entries.hasNext()) {
            String label = entries.next();
            st.setInt(1, 1);
            st.setString(2, label);
            st.setInt(3, 0);
            st.setString(4, newPortfolioUuid);

            st.execute();
            ResultSet keys = st.getGeneratedKeys();
            keys.next();
            int grid = keys.getInt(1);
            resolve.groups.put(label, grid);

            st2.setInt(1, grid);
            st2.setInt(2, 1);
            st2.setString(3, label);
            st2.execute();
        }

        /// Ajout des droits des noeuds
        String insertRight = "INSERT INTO group_rights(grid, id, RD, WR, DL, SB, AD, types_id, rules_id, notify_roles) "
                + "VALUES(?,uuid2bin(?),?,?,?,?,?,?,?,?)";
        st = connection.prepareStatement(insertRight);

        Iterator<Entry<String, groupright>> rights = resolve.resolve.entrySet().iterator();
        while (rights.hasNext()) {
            Entry<String, groupright> entry = rights.next();
            String uuid = entry.getKey();
            groupright gr = entry.getValue();

            Iterator<Entry<String, right>> rightiter = gr.rights.entrySet().iterator();
            while (rightiter.hasNext()) {
                Entry<String, right> rightelem = rightiter.next();
                String group = rightelem.getKey();
                int grid = resolve.groups.get(group);
                right rightval = rightelem.getValue();
                st.setInt(1, grid);
                st.setString(2, uuid);
                st.setInt(3, rightval.rd);
                st.setInt(4, rightval.wr);
                st.setInt(5, rightval.dl);
                st.setInt(6, rightval.sb);
                st.setInt(7, rightval.ad);
                st.setString(8, rightval.types);
                st.setString(9, rightval.rules);
                st.setString(10, rightval.notify);

                st.execute();
            }
        }

        /// On copie tout dans les vrai tables
        /// Structure
        sql = "INSERT INTO node(node_uuid, node_parent_uuid, node_children_uuid, node_order, metadata, metadata_wad, metadata_epm, res_node_uuid, res_res_node_uuid, res_context_node_uuid, shared_res, shared_node, shared_node_res, shared_res_uuid, shared_node_uuid, shared_node_res_uuid, asm_type, xsi_type, semtag, semantictag, label, code, descr, format, modif_user_id, modif_date, portfolio_id) "
                + "SELECT new_uuid, node_parent_uuid, node_children_uuid, node_order, metadata, metadata_wad, metadata_epm, res_node_uuid, res_res_node_uuid, res_context_node_uuid, shared_res, shared_node, shared_node_res, shared_res_uuid, shared_node_uuid, shared_node_res_uuid, asm_type, xsi_type, semtag, semantictag, label, code, descr, format, modif_user_id, modif_date, portfolio_id "
                + "FROM t_data";
        st = connection.prepareStatement(sql);
        st.executeUpdate();
        st.close();

        /// Resources
        sql = "INSERT INTO resource_table(node_uuid, xsi_type, content, user_id, modif_user_id, modif_date) "
                + "SELECT new_uuid, xsi_type, content, user_id, modif_user_id, modif_date " + "FROM t_res";
        st = connection.prepareStatement(sql);
        st.executeUpdate();
        st.close();

        /// Ajout du portfolio dans la table
        sql = "INSERT INTO portfolio(portfolio_id, root_node_uuid, user_id, model_id, modif_user_id, modif_date, active) "
                + "SELECT d.portfolio_id, d.new_uuid, p.user_id, p.model_id, p.modif_user_id, p.modif_date, p.active "
                + "FROM t_data d INNER JOIN portfolio p " + "ON d.node_uuid=p.root_node_uuid";

        st = connection.prepareStatement(sql);
        st.executeUpdate();
        st.close();

        /// Ajout du portfolio dans le groupe de portfolio
        if (null == portfGroupName || "".equals(portfGroupName))
            portfGroupName = "default";

        sql = "INSERT INTO portfolio_group(owner, portfolio_id, group_name) VALUES(?,uuid2bin(?),?)";

        st = connection.prepareStatement(sql);
        st.setInt(1, userId);
        st.setString(2, newPortfolioUuid);
        st.setString(3, portfGroupName);
        st.executeUpdate();
        st.close();

        /// Finalement on cre un rle designer
        int groupid = postCreateRole(newPortfolioUuid, "designer", userId);

        /// Ajoute la personne dans ce groupe
        putUserGroup(Integer.toString(groupid), Integer.toString(userId));

    } catch (Exception e) {
        try {
            newPortfolioUuid = "erreur: " + e.getMessage();
            if (connection.getAutoCommit() == false)
                connection.rollback();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
        e.printStackTrace();
    } finally {
        try {
            connection.setAutoCommit(true);
            // Les 'pooled connection' ne se ferment pas vraiment. On nettoie manuellement les tables temporaires...
            if (dbserveur.equals("mysql")) {
                sql = "DROP TEMPORARY TABLE IF EXISTS t_data, t_res, t_struc, t_struc_2, t_rights";
                st = connection.prepareStatement(sql);
                st.execute();
                st.close();
            }

            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    return newPortfolioUuid;
}

From source file:com.moviejukebox.reader.MovieJukeboxXMLReader.java

/**
 * Parse a single movie detail XML file//  w w w .  j a v a 2 s.  c  o m
 *
 * @param xmlFile
 * @param movie
 * @return
 */
public boolean parseMovieXML(File xmlFile, Movie movie) {
    boolean forceDirtyFlag = Boolean.FALSE; // force dirty flag for example when extras have been deleted
    Document xmlDoc;

    try {
        xmlDoc = DOMHelper.getDocFromFile(xmlFile);
    } catch (MalformedURLException error) {
        LOG.error(ERROR_FIXIT, xmlFile.getName());
        LOG.error(SystemTools.getStackTrace(error));
        return Boolean.FALSE;
    } catch (IOException error) {
        LOG.error(ERROR_FIXIT, xmlFile.getName());
        LOG.error(SystemTools.getStackTrace(error));
        return Boolean.FALSE;
    } catch (ParserConfigurationException | SAXException error) {
        LOG.error(ERROR_FIXIT, xmlFile.getName());
        LOG.error(SystemTools.getStackTrace(error));
        return Boolean.FALSE;
    }

    NodeList nlMovies; // Main list of movies, there should only be 1
    Node nMovie; // Node for the movie

    NodeList nlElements; // Reusable NodeList for the other elements
    Node nElements; // Reusable Node for the other elements

    nlMovies = xmlDoc.getElementsByTagName(MOVIE);
    for (int loopMovie = 0; loopMovie < nlMovies.getLength(); loopMovie++) {
        nMovie = nlMovies.item(loopMovie);
        if (nMovie.getNodeType() == Node.ELEMENT_NODE) {
            Element eMovie = (Element) nMovie;

            // Get all the IDs associated with the movie
            nlElements = eMovie.getElementsByTagName("id");
            for (int looper = 0; looper < nlElements.getLength(); looper++) {
                nElements = nlElements.item(looper);
                if (nElements.getNodeType() == Node.ELEMENT_NODE) {
                    Element eId = (Element) nElements;

                    String movieDb = eId.getAttribute(MOVIEDB);
                    if (StringTools.isNotValidString(movieDb)) {
                        movieDb = ImdbPlugin.IMDB_PLUGIN_ID;
                    }
                    movie.setId(movieDb, eId.getTextContent());
                }
            } // End of ID

            // Get the Version the XML was written with
            movie.setMjbVersion(DOMHelper.getValueFromElement(eMovie, "mjbVersion"));

            // Get the Git SHA the XML was written with
            movie.setMjbGitSHA(DOMHelper.getValueFromElement(eMovie, "mjbGitSHA"));

            // Get the date/time the XML was written
            movie.setMjbGenerationDateString(DOMHelper.getValueFromElement(eMovie, "xmlGenerationDate"));

            if (StringTools.isNotValidString(movie.getBaseFilename())) {
                movie.setBaseFilename(DOMHelper.getValueFromElement(eMovie, "baseFilenameBase"));
            }

            if (StringTools.isNotValidString(movie.getBaseName())) {
                movie.setBaseName(DOMHelper.getValueFromElement(eMovie, BASE_FILENAME));
            }

            // Get the title fields
            parseOverridableTitle(movie, eMovie);
            parseOverridableOriginalTitle(movie, eMovie);
            movie.setTitleSort(DOMHelper.getValueFromElement(eMovie, SORT_TITLE));

            // Get the year. We don't care about the attribute as that is the index
            parseOverridableYear(movie, eMovie);

            // Get the release date
            parseOverridableReleaseDate(movie, eMovie);

            // get the show status
            movie.setShowStatus(DOMHelper.getValueFromElement(eMovie, "showStatus"));

            // Get the ratings. We don't care about the RATING as this is a calulated value.
            // So just get the childnodes of the "ratings" node
            nlElements = eMovie.getElementsByTagName("ratings");
            if (nlElements.getLength() > 0) {
                nlElements = nlElements.item(0).getChildNodes();
                for (int looper = 0; looper < nlElements.getLength(); looper++) {
                    nElements = nlElements.item(looper);
                    if (nElements.getNodeType() == Node.ELEMENT_NODE) {
                        Element eRating = (Element) nElements;

                        String movieDb = eRating.getAttribute(MOVIEDB);
                        if (StringTools.isNotValidString(movieDb)) {
                            movieDb = ImdbPlugin.IMDB_PLUGIN_ID;
                        }
                        movie.addRating(movieDb, Integer.parseInt(eRating.getTextContent()));
                    }
                }
            } // End of Ratings

            // Get the watched flags
            movie.setWatchedNFO(Boolean.parseBoolean(DOMHelper.getValueFromElement(eMovie, "watchedNFO")));
            movie.setWatchedFile(Boolean.parseBoolean(DOMHelper.getValueFromElement(eMovie, "watchedFile")));

            // Get artwork URLS
            movie.setPosterURL(HTMLTools.decodeUrl(DOMHelper.getValueFromElement(eMovie, "posterURL")));
            movie.setFanartURL(HTMLTools.decodeUrl(DOMHelper.getValueFromElement(eMovie, "fanartURL")));
            movie.setBannerURL(HTMLTools.decodeUrl(DOMHelper.getValueFromElement(eMovie, "bannerURL")));
            movie.setClearArtURL(HTMLTools.decodeHtml(DOMHelper.getValueFromElement(eMovie, "clearArtURL")));
            movie.setClearLogoURL(HTMLTools.decodeHtml(DOMHelper.getValueFromElement(eMovie, "clearLogoURL")));
            movie.setTvThumbURL(HTMLTools.decodeHtml(DOMHelper.getValueFromElement(eMovie, "tvThumbURL")));
            movie.setSeasonThumbURL(
                    HTMLTools.decodeHtml(DOMHelper.getValueFromElement(eMovie, "seasonThumbURL")));
            movie.setMovieDiscURL(HTMLTools.decodeHtml(DOMHelper.getValueFromElement(eMovie, "movieDiscURL")));

            // Get artwork files
            movie.setPosterFilename(HTMLTools.decodeUrl(DOMHelper.getValueFromElement(eMovie, "posterFile")));
            movie.setDetailPosterFilename(
                    HTMLTools.decodeUrl(DOMHelper.getValueFromElement(eMovie, "detailPosterFile")));
            movie.setThumbnailFilename(HTMLTools.decodeUrl(DOMHelper.getValueFromElement(eMovie, "thumbnail")));
            movie.setFanartFilename(HTMLTools.decodeUrl(DOMHelper.getValueFromElement(eMovie, "fanartFile")));
            movie.setBannerFilename(HTMLTools.decodeUrl(DOMHelper.getValueFromElement(eMovie, "bannerFile")));
            movie.setWideBannerFilename(
                    HTMLTools.decodeUrl(DOMHelper.getValueFromElement(eMovie, "wideBannerFile")));
            movie.setClearArtFilename(
                    HTMLTools.decodeUrl(DOMHelper.getValueFromElement(eMovie, "clearArtFile")));
            movie.setClearLogoFilename(
                    HTMLTools.decodeUrl(DOMHelper.getValueFromElement(eMovie, "clearLogoFile")));
            movie.setTvThumbFilename(HTMLTools.decodeUrl(DOMHelper.getValueFromElement(eMovie, "tvThumbFile")));
            movie.setSeasonThumbFilename(
                    HTMLTools.decodeUrl(DOMHelper.getValueFromElement(eMovie, "seasonThumbFile")));
            movie.setMovieDiscFilename(
                    HTMLTools.decodeUrl(DOMHelper.getValueFromElement(eMovie, "movieDiscFile")));

            // Get the plot and outline
            parseOverridablePlot(movie, eMovie);
            parseOverridableOutline(movie, eMovie);

            // Get the quote
            parseOverridableQuote(movie, eMovie);

            // Get the tagline
            parseOverridableTagline(movie, eMovie);

            // Get the company name
            parseOverridableCompany(movie, eMovie);

            // get the runtime
            parseOverridableRuntime(movie, eMovie);

            // get the top 250
            parseOverridableTop250(movie, eMovie);

            // Get the directors
            nlElements = eMovie.getElementsByTagName("directors");
            if (nlElements.getLength() > 0) {
                Element tagElement = (Element) nlElements.item(0);
                nlElements = tagElement.getChildNodes();
                for (int looper = 0; looper < nlElements.getLength(); looper++) {
                    nElements = nlElements.item(looper);
                    if (nElements.getNodeType() == Node.ELEMENT_NODE) {
                        Element ePerson = (Element) nElements;
                        movie.addDirector(ePerson.getTextContent(), tagElement.getAttribute(SOURCE));
                    }
                }
            }

            // Get the writers
            nlElements = eMovie.getElementsByTagName("writers");
            if (nlElements.getLength() > 0) {
                Element tagElement = (Element) nlElements.item(0);
                nlElements = tagElement.getChildNodes();
                for (int looper = 0; looper < nlElements.getLength(); looper++) {
                    nElements = nlElements.item(looper);
                    if (nElements.getNodeType() == Node.ELEMENT_NODE) {
                        Element ePerson = (Element) nElements;
                        movie.addWriter(ePerson.getTextContent(), tagElement.getAttribute(SOURCE));
                    }
                }
            }

            // Get the cast
            nlElements = eMovie.getElementsByTagName("cast");
            if (nlElements.getLength() > 0) {
                Element tagElement = (Element) nlElements.item(0);
                nlElements = tagElement.getChildNodes();
                for (int looper = 0; looper < nlElements.getLength(); looper++) {
                    nElements = nlElements.item(looper);
                    if (nElements.getNodeType() == Node.ELEMENT_NODE) {
                        Element ePerson = (Element) nElements;
                        movie.addActor(ePerson.getTextContent(), tagElement.getAttribute(SOURCE));
                    }
                }
            }

            // Get the country
            parseOverridableCountry(movie, eMovie);

            // Get the genres
            nlElements = eMovie.getElementsByTagName("genres");
            if (nlElements.getLength() > 0) {
                Element tagElement = (Element) nlElements.item(0);
                nlElements = tagElement.getChildNodes();
                List<String> genres = new ArrayList<>();
                for (int looper = 0; looper < nlElements.getLength(); looper++) {
                    nElements = nlElements.item(looper);
                    if (nElements.getNodeType() == Node.ELEMENT_NODE) {
                        Element eGenre = (Element) nElements;
                        genres.add(eGenre.getTextContent());
                    }
                }
                movie.setGenres(genres, tagElement.getAttribute(SOURCE));
            }

            // Process the sets
            nlElements = eMovie.getElementsByTagName("sets");
            if (nlElements.getLength() > 0) {
                nlElements = nlElements.item(0).getChildNodes();
                for (int looper = 0; looper < nlElements.getLength(); looper++) {
                    nElements = nlElements.item(looper);
                    if (nElements.getNodeType() == Node.ELEMENT_NODE) {
                        Element eSet = (Element) nElements;
                        String order = eSet.getAttribute(ORDER);
                        if (StringTools.isValidString(order)) {
                            movie.addSet(eSet.getTextContent(), Integer.parseInt(order));
                        } else {
                            movie.addSet(eSet.getTextContent());
                        }
                    }
                }
            }

            // Get certification
            parseOverridableCertification(movie, eMovie);

            // Get language
            parseOverridableLanguage(movie, eMovie);

            // Get subtitles
            movie.setSubtitles(DOMHelper.getValueFromElement(eMovie, "subtitles"));

            // Get the TrailerExchange
            movie.setTrailerExchange(
                    DOMHelper.getValueFromElement(eMovie, "trailerExchange").equalsIgnoreCase(YES));

            // Get trailerLastScan date/time
            movie.setTrailerLastScan(DOMHelper.getValueFromElement(eMovie, TRAILER_LAST_SCAN));

            // Get file container
            parseOverridableContainer(movie, eMovie);

            nlElements = eMovie.getElementsByTagName("codecs");
            if (nlElements.getLength() > 0) {
                nlElements = nlElements.item(0).getChildNodes();
                for (int looper = 0; looper < nlElements.getLength(); looper++) {
                    nElements = nlElements.item(looper);
                    if (nElements.getNodeType() == Node.ELEMENT_NODE) {
                        String codecType = nElements.getNodeName();
                        if (nElements.getChildNodes().getLength() > 0) {
                            for (int cLooper = 0; cLooper < nElements.getChildNodes().getLength(); cLooper++) {
                                Node nCodec = nElements.getChildNodes().item(cLooper);
                                if (nCodec.getNodeType() == Node.ELEMENT_NODE) {
                                    Element eCodec = (Element) nCodec;

                                    Codec codec;
                                    if (CodecType.VIDEO.toString().equalsIgnoreCase(codecType)) {
                                        codec = new Codec(CodecType.VIDEO);
                                    } else {
                                        codec = new Codec(CodecType.AUDIO);
                                    }
                                    codec.setCodecId(eCodec.getAttribute("codecId"));
                                    codec.setCodecIdHint(eCodec.getAttribute("codecIdHint"));
                                    codec.setCodecFormat(eCodec.getAttribute("format"));
                                    codec.setCodecFormatProfile(eCodec.getAttribute("formatProfile"));
                                    codec.setCodecFormatVersion(eCodec.getAttribute("formatVersion"));
                                    codec.setCodecLanguage(eCodec.getAttribute(LANGUAGE));
                                    codec.setCodecBitRate(eCodec.getAttribute("bitrate"));
                                    String tmpValue = eCodec.getAttribute("channels");
                                    if (StringUtils.isNotBlank(tmpValue)) {
                                        codec.setCodecChannels(
                                                Integer.parseInt(eCodec.getAttribute("channels")));
                                    }
                                    codec.setCodec(eCodec.getTextContent().trim());

                                    tmpValue = eCodec.getAttribute(SOURCE);
                                    if (StringTools.isValidString(tmpValue)) {
                                        codec.setCodecSource(CodecSource.fromString(tmpValue));
                                    } else {
                                        codec.setCodecSource(CodecSource.UNKNOWN);
                                    }

                                    movie.addCodec(codec);
                                }
                            } // END of codec information for audio/video
                        }
                    } // END of audio/video codec
                } // END of codecs loop
            } // END of codecs

            // get the resolution
            parseOverridableResolution(movie, eMovie);

            // get the video source
            parseOverridableVideoSource(movie, eMovie);

            // get the video output
            parseOverridableVideoOutput(movie, eMovie);

            // get aspect ratio
            parseOverridableAspectRatio(movie, eMovie);

            // get frames per second
            parseOverridableFramesPerSecond(movie, eMovie);

            // Get navigation info
            movie.setFirst(HTMLTools.decodeUrl(DOMHelper.getValueFromElement(eMovie, "first")));
            movie.setPrevious(HTMLTools.decodeUrl(DOMHelper.getValueFromElement(eMovie, "previous")));
            movie.setNext(HTMLTools.decodeUrl(DOMHelper.getValueFromElement(eMovie, "next")));
            movie.setLast(HTMLTools.decodeUrl(DOMHelper.getValueFromElement(eMovie, "last")));

            // Get the library description, if it's not been set elsewhere (e.g. scanner)
            String tempLibraryDescription = DOMHelper.getValueFromElement(eMovie, "libraryDescription");
            if (StringTools.isNotValidString(movie.getLibraryDescription())) {
                movie.setLibraryDescription(tempLibraryDescription);
            } else if (!movie.getLibraryDescription().equals(tempLibraryDescription)) {
                // The current description is different to the one in the XML
                LOG.debug("Different library description! Setting dirty INFO");
                forceDirtyFlag = Boolean.TRUE;
            }

            // Get prebuf
            movie.setPrebuf(Long.parseLong(DOMHelper.getValueFromElement(eMovie, "prebuf")));

            // Issue 1901: Awards
            nlElements = eMovie.getElementsByTagName("awards");
            if (nlElements.getLength() > 0) {
                nlElements = nlElements.item(0).getChildNodes();
                for (int looper = 0; looper < nlElements.getLength(); looper++) {
                    nElements = nlElements.item(looper);
                    if (nElements.getNodeType() == Node.ELEMENT_NODE) {
                        Element eAwardEvent = (Element) nElements;
                        AwardEvent awardEvent = new AwardEvent();
                        awardEvent.setName(eAwardEvent.getAttribute(NAME));

                        Node nAward;
                        for (int loopAwards = 0; loopAwards < eAwardEvent.getChildNodes()
                                .getLength(); loopAwards++) {
                            nAward = eAwardEvent.getChildNodes().item(loopAwards);
                            if (nAward.getNodeType() == Node.ELEMENT_NODE) {
                                Element eAward = (Element) nAward;
                                Award award = new Award();

                                award.setName(eAward.getTextContent());
                                award.setNominated(Integer.parseInt(eAward.getAttribute("nominated")));
                                award.setWon(Integer.parseInt(eAward.getAttribute(WON)));
                                award.setYear(Integer.parseInt(eAward.getAttribute(YEAR)));
                                String tmpAward = eAward.getAttribute("wons");
                                if (StringTools.isValidString(tmpAward)) {
                                    award.setWons(Arrays.asList(tmpAward.split(Movie.SPACE_SLASH_SPACE)));
                                }
                                tmpAward = eAward.getAttribute("nominations");
                                if (StringTools.isValidString(tmpAward)) {
                                    award.setNominations(
                                            Arrays.asList(tmpAward.split(Movie.SPACE_SLASH_SPACE)));
                                }

                                awardEvent.addAward(award);
                            }
                        } // End of Awards

                        movie.addAward(awardEvent);
                    }
                }
            } // End of AwardEvents

            // Issue 1897: Cast enhancement
            nlElements = eMovie.getElementsByTagName("people");
            if (nlElements.getLength() > 0) {
                nlElements = nlElements.item(0).getChildNodes();

                for (int looper = 0; looper < nlElements.getLength(); looper++) {
                    nElements = nlElements.item(looper);
                    if (nElements.getNodeType() == Node.ELEMENT_NODE) {
                        Element ePerson = (Element) nElements;
                        Filmography person = new Filmography();

                        person.setCastId(ePerson.getAttribute("cast_id"));
                        person.setCharacter(ePerson.getAttribute(CHARACTER));
                        person.setDepartment(ePerson.getAttribute(DEPARTMENT));
                        person.setDoublage(ePerson.getAttribute("doublage"));
                        person.setId(ePerson.getAttribute("id"));
                        person.setJob(ePerson.getAttribute(JOB));
                        person.setName(ePerson.getAttribute(NAME));
                        person.setOrder(ePerson.getAttribute(ORDER));
                        person.setTitle(ePerson.getAttribute(TITLE));
                        person.setUrl(ePerson.getAttribute(URL));
                        person.setPhotoFilename(ePerson.getAttribute("photoFile"));
                        person.setFilename(ePerson.getTextContent());

                        // Get any "id_???" values
                        for (int loopAttr = 0; loopAttr < ePerson.getAttributes().getLength(); loopAttr++) {
                            Node nPersonAttr = ePerson.getAttributes().item(loopAttr);
                            if (nPersonAttr.getNodeName().startsWith(ID)) {
                                String name = nPersonAttr.getNodeName().replace(ID, "");
                                person.setId(name, nPersonAttr.getNodeValue());
                            }
                        }

                        String source = ePerson.getAttribute(SOURCE);
                        if (StringTools.isValidString(source)) {
                            person.setSource(source);
                            if (person.getDepartment().equalsIgnoreCase(Filmography.DEPT_DIRECTING)) {
                                movie.setOverrideSource(OverrideFlag.PEOPLE_DIRECTORS, source);
                            } else if (person.getDepartment().equalsIgnoreCase(Filmography.DEPT_WRITING)) {
                                movie.setOverrideSource(OverrideFlag.PEOPLE_WRITERS, source);
                            } else if (person.getDepartment().equalsIgnoreCase(Filmography.DEPT_ACTORS)) {
                                movie.setOverrideSource(OverrideFlag.PEOPLE_ACTORS, source);
                            }
                        } else {
                            person.setSource(Movie.UNKNOWN);
                        }
                        movie.addPerson(person);
                    }
                }
            } // End of Cast

            // Issue 2012: Financial information about movie
            nlElements = eMovie.getElementsByTagName("business");
            for (int looper = 0; looper < nlElements.getLength(); looper++) {
                nElements = nlElements.item(looper);
                if (nElements.getNodeType() == Node.ELEMENT_NODE) {
                    Element eBusiness = (Element) nElements;
                    movie.setBudget(eBusiness.getAttribute("budget"));

                    Node nCountry;
                    for (int loopBus = 0; loopBus < eBusiness.getChildNodes().getLength(); loopBus++) {
                        nCountry = eBusiness.getChildNodes().item(loopBus);
                        if (nCountry.getNodeType() == Node.ELEMENT_NODE) {
                            Element eCountry = (Element) nCountry;
                            if ("gross".equalsIgnoreCase(eCountry.getNodeName())) {
                                movie.setGross(eCountry.getAttribute(COUNTRY), eCountry.getTextContent());
                            } else if ("openweek".equalsIgnoreCase(eCountry.getNodeName())) {
                                movie.setOpenWeek(eCountry.getAttribute(COUNTRY), eCountry.getTextContent());
                            }
                        }
                    } // End of budget info
                }
            } // End of business info

            // Issue 2013: Add trivia
            if (ENABLE_TRIVIA) {
                nlElements = eMovie.getElementsByTagName("trivia");
                for (int looper = 0; looper < nlElements.getLength(); looper++) {
                    nElements = nlElements.item(looper);
                    movie.addDidYouKnow(nElements.getTextContent());
                }
            } // End of trivia info

            // Get the file list
            nlElements = eMovie.getElementsByTagName("files");
            if (nlElements.getLength() > 0) {
                nlElements = nlElements.item(0).getChildNodes();
                for (int looper = 0; looper < nlElements.getLength(); looper++) {
                    nElements = nlElements.item(looper);
                    if (nElements.getNodeType() == Node.ELEMENT_NODE) {
                        Element eFile = (Element) nElements;
                        MovieFile movieFile = new MovieFile();

                        try {
                            File mfFile = new File(DOMHelper.getValueFromElement(eFile, "fileLocation"));
                            // Check to see if the file exists, or we are preserving the jukebox
                            if (mfFile.exists() || MovieJukebox.isJukeboxPreserve()) {
                                // Save the file to the MovieFile
                                movieFile.setFile(mfFile);
                            } else {
                                // We can't find this file anymore, so skip it.
                                LOG.debug(
                                        "Missing video file in the XML file ({}), it may have been moved or no longer exist.",
                                        mfFile.getName());
                                continue;
                            }
                        } catch (Exception ignore) {
                            // If there is an error creating the file then don't save anything
                            LOG.debug("Failed parsing file {}", xmlFile.getName());
                            continue;
                        }

                        String attr = eFile.getAttribute(TITLE);
                        if (StringTools.isValidString(attr)) {
                            movieFile.setTitle(attr);
                        }

                        attr = eFile.getAttribute(SEASON);
                        if (StringUtils.isNumeric(attr)) {
                            movieFile.setSeason(Integer.parseInt(attr));
                        }

                        attr = eFile.getAttribute("firstPart");
                        if (StringUtils.isNumeric(attr)) {
                            movieFile.setFirstPart(Integer.parseInt(attr));
                        }

                        attr = eFile.getAttribute("lastPart");
                        if (StringUtils.isNumeric(attr)) {
                            movieFile.setLastPart(Integer.parseInt(attr));
                        }

                        attr = eFile.getAttribute("subtitlesExchange");
                        if (StringTools.isValidString(attr)) {
                            movieFile.setSubtitlesExchange(attr.equalsIgnoreCase(YES));
                        }

                        movieFile.setFilename(DOMHelper.getValueFromElement(eFile, "fileURL"));

                        if (DOMHelper.getValueFromElement(eFile, "fileArchiveName") != null) {
                            movieFile.setArchiveName(DOMHelper.getValueFromElement(eFile, "fileArchiveName"));
                        }

                        // We need to get the part from the fileTitle
                        NodeList nlFileParts = eFile.getElementsByTagName("fileTitle");
                        if (nlFileParts.getLength() > 0) {
                            for (int looperFile = 0; looperFile < nlFileParts.getLength(); looperFile++) {
                                Node nFileParts = nlFileParts.item(looperFile);
                                if (nFileParts.getNodeType() == Node.ELEMENT_NODE) {
                                    Element eFileParts = (Element) nFileParts;
                                    String part = eFileParts.getAttribute(PART);
                                    String source = eFileParts.getAttribute(SOURCE);
                                    if (StringUtils.isNumeric(part)) {
                                        movieFile.setTitle(NumberUtils.toInt(part, 0),
                                                eFileParts.getTextContent(), source);
                                    } else {
                                        movieFile.setTitle(eFileParts.getTextContent(), source);
                                    }
                                }
                            }
                        }

                        // Get the airs info
                        nlFileParts = eFile.getElementsByTagName("airsInfo");
                        if (nlFileParts.getLength() > 0) {
                            for (int looperFile = 0; looperFile < nlFileParts.getLength(); looperFile++) {
                                Node nFileParts = nlFileParts.item(looperFile);
                                if (nFileParts.getNodeType() == Node.ELEMENT_NODE) {
                                    Element eFileParts = (Element) nFileParts;
                                    int part = NumberUtils.toInt(eFileParts.getAttribute(PART), 1);

                                    movieFile.setAirsAfterSeason(part, eFileParts.getAttribute("afterSeason"));
                                    movieFile.setAirsBeforeEpisode(part,
                                            eFileParts.getAttribute("beforeEpisode"));
                                    movieFile.setAirsBeforeSeason(part,
                                            eFileParts.getAttribute("beforeSeason"));
                                }
                            }
                        }

                        // Get first aired information
                        nlFileParts = eFile.getElementsByTagName("firstAired");
                        if (nlFileParts.getLength() > 0) {
                            for (int looperFile = 0; looperFile < nlFileParts.getLength(); looperFile++) {
                                Node nFileParts = nlFileParts.item(looperFile);
                                if (nFileParts.getNodeType() == Node.ELEMENT_NODE) {
                                    Element eFileParts = (Element) nFileParts;
                                    int part = NumberUtils.toInt(eFileParts.getAttribute(PART), 1);
                                    String source = eFileParts.getAttribute(SOURCE);
                                    movieFile.setFirstAired(part, eFileParts.getTextContent(), source);
                                }
                            }
                        }

                        // get the file plot
                        nlFileParts = eFile.getElementsByTagName("filePlot");
                        if (nlFileParts.getLength() > 0) {
                            for (int looperFile = 0; looperFile < nlFileParts.getLength(); looperFile++) {
                                Node nFileParts = nlFileParts.item(looperFile);
                                if (nFileParts.getNodeType() == Node.ELEMENT_NODE) {
                                    Element eFileParts = (Element) nFileParts;
                                    int part = NumberUtils.toInt(eFileParts.getAttribute(PART), 1);
                                    String source = eFileParts.getAttribute(SOURCE);
                                    movieFile.setPlot(part, eFileParts.getTextContent(), source, Boolean.TRUE);
                                }
                            }
                        }

                        // get the file rating
                        nlFileParts = eFile.getElementsByTagName("fileRating");
                        if (nlFileParts.getLength() > 0) {
                            for (int looperFile = 0; looperFile < nlFileParts.getLength(); looperFile++) {
                                Node nFileParts = nlFileParts.item(looperFile);
                                if (nFileParts.getNodeType() == Node.ELEMENT_NODE) {
                                    Element eFileParts = (Element) nFileParts;
                                    int part = NumberUtils.toInt(eFileParts.getAttribute(PART), 1);
                                    String source = eFileParts.getAttribute(SOURCE);
                                    movieFile.setRating(part, eFileParts.getTextContent(), source);
                                }
                            }
                        }

                        // get the file image url
                        nlFileParts = eFile.getElementsByTagName("fileImageURL");
                        if (nlFileParts.getLength() > 0) {
                            for (int looperFile = 0; looperFile < nlFileParts.getLength(); looperFile++) {
                                Node nFileParts = nlFileParts.item(looperFile);
                                if (nFileParts.getNodeType() == Node.ELEMENT_NODE) {
                                    Element eFileParts = (Element) nFileParts;
                                    int part = NumberUtils.toInt(eFileParts.getAttribute(PART), 1);
                                    movieFile.setVideoImageURL(part,
                                            HTMLTools.decodeUrl(eFileParts.getTextContent()));
                                }
                            }
                        }

                        // get the file image filename
                        nlFileParts = eFile.getElementsByTagName("fileImageFile");
                        if (nlFileParts.getLength() > 0) {
                            for (int looperFile = 0; looperFile < nlFileParts.getLength(); looperFile++) {
                                Node nFileParts = nlFileParts.item(looperFile);
                                if (nFileParts.getNodeType() == Node.ELEMENT_NODE) {
                                    Element eFileParts = (Element) nFileParts;
                                    int part = NumberUtils.toInt(eFileParts.getAttribute(PART), 1);
                                    movieFile.setVideoImageFilename(part,
                                            HTMLTools.decodeUrl(eFileParts.getTextContent()));
                                }
                            }
                        }

                        // get the file IDs
                        nlFileParts = eFile.getElementsByTagName("fileId");
                        if (nlFileParts.getLength() > 0) {
                            for (int looperFile = 0; looperFile < nlFileParts.getLength(); looperFile++) {
                                Node nFileParts = nlFileParts.item(looperFile);
                                if (nFileParts.getNodeType() == Node.ELEMENT_NODE) {
                                    Element eFileParts = (Element) nFileParts;
                                    int part = NumberUtils.toInt(eFileParts.getAttribute(PART), 1);
                                    String source = eFileParts.getAttribute(SOURCE);
                                    movieFile.setId(part, source, eFileParts.getTextContent());
                                }
                            }
                        }

                        NodeList nlAttachments = eMovie.getElementsByTagName("attachments");
                        if (nlAttachments.getLength() > 0) {
                            nlAttachments = nlAttachments.item(0).getChildNodes();
                            for (int looperAtt = 0; looperAtt < nlAttachments.getLength(); looperAtt++) {
                                Node nAttachment = nlAttachments.item(looperAtt);
                                if (nAttachment.getNodeType() == Node.ELEMENT_NODE) {
                                    Element eAttachment = (Element) nAttachment;
                                    Attachment attachment = new Attachment();
                                    attachment.setType(
                                            AttachmentType.fromString(eAttachment.getAttribute("type")));
                                    attachment.setAttachmentId(Integer.parseInt(
                                            DOMHelper.getValueFromElement(eAttachment, "attachmentId")));
                                    attachment.setContentType(ContentType.fromString(
                                            DOMHelper.getValueFromElement(eAttachment, "contentType")));
                                    attachment.setMimeType(
                                            DOMHelper.getValueFromElement(eAttachment, "mimeType"));
                                    attachment.setPart(Integer
                                            .parseInt(DOMHelper.getValueFromElement(eAttachment, "part")));
                                    attachment.setSourceFile(movieFile.getFile());
                                    movieFile.addAttachment(attachment);
                                }
                            }
                        }

                        // Parse watched 
                        String watchedDateString = DOMHelper.getValueFromElement(eFile, "watchedDate");
                        final long watchedDate;
                        if (StringTools.isNotValidString(watchedDateString)) {
                            watchedDate = 0;
                        } else {
                            // strip milliseconds
                            Calendar cal = Calendar.getInstance();
                            cal.setTimeInMillis(DateTime.parse(watchedDateString).toMillis());
                            cal.set(Calendar.MILLISECOND, 0);
                            watchedDate = cal.getTimeInMillis();
                        }
                        final boolean watched = Boolean.parseBoolean(eFile.getAttribute("watched"));
                        movieFile.setWatched(watched, watchedDate);

                        // This is not a new file
                        movieFile.setNewFile(Boolean.FALSE);

                        // Add the movie file to the movie
                        movie.addMovieFile(movieFile);
                    }
                }
            } // END of files

            // Get the extra list
            nlElements = eMovie.getElementsByTagName("extras");
            if (nlElements.getLength() > 0) {
                nlElements = nlElements.item(0).getChildNodes();
                for (int looper = 0; looper < nlElements.getLength(); looper++) {
                    nElements = nlElements.item(looper);
                    if (nElements.getNodeType() == Node.ELEMENT_NODE) {
                        Element eExtra = (Element) nElements;

                        String extraTitle = eExtra.getAttribute(TITLE);
                        String extraFilename = eExtra.getTextContent();

                        if (!extraTitle.isEmpty() && !extraFilename.isEmpty()) {
                            boolean exist = Boolean.FALSE;
                            if (extraFilename.startsWith("http:")) {
                                // This is a URL from a NFO file
                                ExtraFile ef = new ExtraFile();
                                ef.setNewFile(Boolean.FALSE);
                                ef.setTitle(extraTitle);
                                ef.setFilename(extraFilename);
                                movie.addExtraFile(ef, Boolean.FALSE); // Add to the movie, but it's not dirty
                                exist = Boolean.TRUE;
                            } else {
                                // Check for existing files
                                for (ExtraFile ef : movie.getExtraFiles()) {
                                    // Check if the movie has already the extra file
                                    if (ef.getFilename().equals(extraFilename)) {
                                        exist = Boolean.TRUE;
                                        // the extra file is old
                                        ef.setNewFile(Boolean.FALSE);
                                        break;
                                    }
                                }
                            }

                            if (!exist) {
                                // the extra file has been deleted so force the dirty flag
                                forceDirtyFlag = Boolean.TRUE;
                            }
                        }
                    }
                }
            } // END of extras

        } // End of ELEMENT_NODE
    } // End of Movie Loop

    // This is a new movie, so clear the current dirty flags
    movie.clearDirty();
    movie.setDirty(DirtyFlag.INFO, forceDirtyFlag || movie.hasNewMovieFiles() || movie.hasNewExtraFiles());

    return Boolean.TRUE;
}

From source file:com.codename1.android.AndroidLayoutImporter.java

private void convertButton(Element inputSrcElement, Element out) {
    out.removeAttribute("layout");
    out.setAttribute("type", "Button");
    //System.out.println("Converting button "+inputSrcElement);
    int attlen = inputSrcElement.getAttributes().getLength();
    for (int i = 0; i < attlen; i++) {
        Node n = inputSrcElement.getAttributes().item(i);
        //System.out.println("Namespace is "+n.getNamespaceURI());
        //System.out.println("Node "+i+"="+n);
    }/*from  ww  w  . j a v a2  s. com*/

    //System.out.println("Text is "+inputSrcElement.getAttributeNS(NS_ANDROID, "text"));
    if (inputSrcElement.hasAttributeNS(NS_ANDROID, "text")) {
        out.setAttribute("text", parseText(inputSrcElement.getAttributeNS(NS_ANDROID, "text")));
    }

}

From source file:net.sourceforge.pmd.rules.RuleFactory.java

/**
 * Parses a property definition node and returns the defined property descriptor.
 *
 * @param propertyElement Property node to parse
 *
 * @return The property descriptor//from  www.  j  a v a  2s  . co m
 */
private static PropertyDescriptor<?> parsePropertyDefinition(Element propertyElement) {
    String typeId = propertyElement.getAttribute(PropertyDescriptorField.TYPE.attributeName());

    PropertyDescriptorExternalBuilder<?> pdFactory = PropertyTypeId.factoryFor(typeId);
    if (pdFactory == null) {
        throw new IllegalArgumentException("No property descriptor factory for type: " + typeId);
    }

    Map<PropertyDescriptorField, String> values = new HashMap<>();
    NamedNodeMap atts = propertyElement.getAttributes();

    /// populate a map of values for an individual descriptor
    for (int i = 0; i < atts.getLength(); i++) {
        Attr a = (Attr) atts.item(i);
        values.put(PropertyDescriptorField.getConstant(a.getName()), a.getValue());
    }

    if (StringUtils.isBlank(values.get(DEFAULT_VALUE))) {
        NodeList children = propertyElement.getElementsByTagName(DEFAULT_VALUE.attributeName());
        if (children.getLength() == 1) {
            values.put(DEFAULT_VALUE, children.item(0).getTextContent());
        } else {
            throw new IllegalArgumentException("No value defined!");
        }
    }

    // casting is not pretty but prevents the interface from having this method
    return pdFactory.build(values);
}

From source file:net.sourceforge.pmd.testframework.RuleTst.java

private TestDescriptor[] parseTests(Rule rule, Document doc) {
    Element root = doc.getDocumentElement();
    NodeList testCodes = root.getElementsByTagName("test-code");

    TestDescriptor[] tests = new TestDescriptor[testCodes.getLength()];
    for (int i = 0; i < testCodes.getLength(); i++) {
        Element testCode = (Element) testCodes.item(i);

        boolean reinitializeRule = true;
        Node reinitializeRuleAttribute = testCode.getAttributes().getNamedItem("reinitializeRule");
        if (reinitializeRuleAttribute != null) {
            String reinitializeRuleValue = reinitializeRuleAttribute.getNodeValue();
            if ("false".equalsIgnoreCase(reinitializeRuleValue)
                    || "0".equalsIgnoreCase(reinitializeRuleValue)) {
                reinitializeRule = false;
            }//from   w  ww . j  a  v  a  2 s .c o m
        }

        boolean isRegressionTest = true;
        Node regressionTestAttribute = testCode.getAttributes().getNamedItem("regressionTest");
        if (regressionTestAttribute != null) {
            String reinitializeRuleValue = regressionTestAttribute.getNodeValue();
            if ("false".equalsIgnoreCase(reinitializeRuleValue)) {
                isRegressionTest = false;
            }
        }

        boolean isUseAuxClasspath = true;
        Node useAuxClasspathAttribute = testCode.getAttributes().getNamedItem("useAuxClasspath");
        if (useAuxClasspathAttribute != null) {
            String useAuxClasspathValue = useAuxClasspathAttribute.getNodeValue();
            if ("false".equalsIgnoreCase(useAuxClasspathValue)) {
                isUseAuxClasspath = false;
            }
        }

        NodeList ruleProperties = testCode.getElementsByTagName("rule-property");
        Properties properties = new Properties();
        for (int j = 0; j < ruleProperties.getLength(); j++) {
            Node ruleProperty = ruleProperties.item(j);
            String propertyName = ruleProperty.getAttributes().getNamedItem("name").getNodeValue();
            properties.setProperty(propertyName, parseTextNode(ruleProperty));
        }

        NodeList expectedMessagesNodes = testCode.getElementsByTagName("expected-messages");
        List<String> messages = new ArrayList<>();
        if (expectedMessagesNodes != null && expectedMessagesNodes.getLength() > 0) {
            Element item = (Element) expectedMessagesNodes.item(0);
            NodeList messagesNodes = item.getElementsByTagName("message");
            for (int j = 0; j < messagesNodes.getLength(); j++) {
                messages.add(parseTextNode(messagesNodes.item(j)));
            }
        }

        NodeList expectedLineNumbersNodes = testCode.getElementsByTagName("expected-linenumbers");
        List<Integer> expectedLineNumbers = new ArrayList<>();
        if (expectedLineNumbersNodes != null && expectedLineNumbersNodes.getLength() > 0) {
            Element item = (Element) expectedLineNumbersNodes.item(0);
            String numbers = item.getTextContent();
            for (String n : numbers.split(" *, *")) {
                expectedLineNumbers.add(Integer.valueOf(n));
            }
        }

        String code = getNodeValue(testCode, "code", false);
        if (code == null) {
            // Should have a coderef
            NodeList coderefs = testCode.getElementsByTagName("code-ref");
            if (coderefs.getLength() == 0) {
                throw new RuntimeException(
                        "Required tag is missing from the test-xml. Supply either a code or a code-ref tag");
            }
            Node coderef = coderefs.item(0);
            String referenceId = coderef.getAttributes().getNamedItem("id").getNodeValue();
            NodeList codeFragments = root.getElementsByTagName("code-fragment");
            for (int j = 0; j < codeFragments.getLength(); j++) {
                String fragmentId = codeFragments.item(j).getAttributes().getNamedItem("id").getNodeValue();
                if (referenceId.equals(fragmentId)) {
                    code = parseTextNode(codeFragments.item(j));
                }
            }

            if (code == null) {
                throw new RuntimeException("No matching code fragment found for coderef");
            }
        }

        String description = getNodeValue(testCode, "description", true);
        int expectedProblems = Integer.parseInt(getNodeValue(testCode, "expected-problems", true));

        String languageVersionString = getNodeValue(testCode, "source-type", false);
        if (languageVersionString == null) {
            tests[i] = new TestDescriptor(code, description, expectedProblems, rule);
        } else {
            LanguageVersion languageVersion = LanguageRegistry
                    .findLanguageVersionByTerseName(languageVersionString);
            if (languageVersion != null) {
                tests[i] = new TestDescriptor(code, description, expectedProblems, rule, languageVersion);
            } else {
                throw new RuntimeException("Unknown LanguageVersion for test: " + languageVersionString);
            }
        }
        tests[i].setReinitializeRule(reinitializeRule);
        tests[i].setRegressionTest(isRegressionTest);
        tests[i].setUseAuxClasspath(isUseAuxClasspath);
        tests[i].setExpectedMessages(messages);
        tests[i].setExpectedLineNumbers(expectedLineNumbers);
        tests[i].setProperties(properties);
        tests[i].setNumberInDocument(i + 1);
    }
    return tests;
}