Example usage for org.w3c.dom NamedNodeMap getNamedItem

List of usage examples for org.w3c.dom NamedNodeMap getNamedItem

Introduction

In this page you can find the example usage for org.w3c.dom NamedNodeMap getNamedItem.

Prototype

public Node getNamedItem(String name);

Source Link

Document

Retrieves a node specified by name.

Usage

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

@Override
public Object putNodeMetadata(MimeType mimeType, String nodeUuid, String xmlNode, int userId, int groupId)
        throws Exception {

    String metadata = "";

    int sharedRes = 0;
    int sharedNode = 0;
    int sharedNodeRes = 0;

    int returnValue = 0;

    //TODO putNode getNodeRight
    if (!credential.hasNodeRight(userId, groupId, nodeUuid, credential.WRITE))
        return "faux";

    String status = "erreur";

    //TODO Optimiser le nombre de requetes (3 => 1)
    int nodeOrder = getNodeOrderByNodeUuid(nodeUuid);
    String parentNodeUuid = getNodeParentUuidByNodeUuid(nodeUuid);
    String portfolioUid = getPortfolioUuidByNodeUuid(nodeUuid);
    String portfolioModelId = getPortfolioModelUuid(portfolioUid);

    // D'abord on supprime les noeuds existants
    //deleteNode(nodeUuid, userId);
    xmlNode = DomUtils.cleanXMLData(xmlNode);
    Document doc = DomUtils.xmlString2Document(xmlNode, new StringBuffer());
    // Puis on le recree
    Node node;//from ww  w  . j a va 2  s . co m
    node = doc.getDocumentElement();

    if (node.getNodeName().equals("metadata")) {
        String tag = "";
        NamedNodeMap attr = node.getAttributes();
        try {
            tag = attr.getNamedItem("semantictag").getNodeValue();
        } catch (Exception ex) {
        }

        String tmpSharedRes = "";
        try {
            tmpSharedRes = attr.getNamedItem("sharedResource").getNodeValue();
            if (tmpSharedRes.equalsIgnoreCase("y"))
                sharedRes = 1;
        } catch (Exception ex) {
        }

        String tmpSharedNode = "";
        try {
            tmpSharedNode = attr.getNamedItem("sharedNode").getNodeValue();
            if (tmpSharedNode.equalsIgnoreCase("y"))
                sharedNode = 1;
        } catch (Exception ex) {
        }

        String tmpSharedNodeResource = "";
        try {
            tmpSharedNodeResource = attr.getNamedItem("sharedNodeResource").getNodeValue();
            if (tmpSharedNodeResource.equalsIgnoreCase("y"))
                sharedNodeRes = 1;
        } catch (Exception ex) {
        }

        metadata = DomUtils.getNodeAttributesString(node);

        try {
            /// Mettre  jour les flags et donne du champ
            String sql = "UPDATE node SET metadata=?, semantictag=?, shared_res=?, shared_node=?, shared_node_res=? WHERE node_uuid=uuid2bin(?)";
            PreparedStatement st = connection.prepareStatement(sql);
            st.setString(1, metadata);
            st.setString(2, tag);
            st.setInt(3, sharedRes);
            st.setInt(4, sharedNode);
            st.setInt(5, sharedNodeRes);
            st.setString(6, nodeUuid);
            st.executeUpdate();
            st.close();

            status = "editer";
        } catch (Exception ex) {
        }

    }

    //      if (1 == updatetMySqlNodeMetadata(nodeUuid,metadata)){
    //         return ;
    //      }

    return status;
}

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

@Override
public Object putNodeMetadata(MimeType mimeType, String nodeUuid, String xmlNode, int userId, int groupId)
        throws Exception {
    String metadata = "";

    int sharedRes = 0;
    int sharedNode = 0;
    int sharedNodeRes = 0;

    //TODO putNode getNodeRight
    if (!credential.hasNodeRight(userId, groupId, nodeUuid, Credential.WRITE))
        throw new RestWebApplicationException(Status.FORBIDDEN, " No WRITE credential ");
    //return "faux";

    String status = "erreur";

    String portfolioUid = getPortfolioUuidByNodeUuid(nodeUuid);

    // D'abord on supprime les noeuds existants
    //deleteNode(nodeUuid, userId);
    xmlNode = DomUtils.cleanXMLData(xmlNode);
    Document doc = DomUtils.xmlString2Document(xmlNode, new StringBuffer());
    // Puis on le recree
    Node node;/*from  ww  w . j  a v  a 2s. c o m*/
    node = doc.getDocumentElement();

    if (node.getNodeName().equals("metadata")) {

        String tag = "";
        NamedNodeMap attr = node.getAttributes();

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

        try {
            tag = attr.getNamedItem("semantictag").getNodeValue();
        } catch (Exception ex) {
        }

        String tmpSharedRes = "";
        try {
            tmpSharedRes = attr.getNamedItem("sharedResource").getNodeValue();
            if (tmpSharedRes.equalsIgnoreCase("y"))
                sharedRes = 1;
        } catch (Exception ex) {
        }

        String tmpSharedNode = "";
        try {
            tmpSharedNode = attr.getNamedItem("sharedNode").getNodeValue();
            if (tmpSharedNode.equalsIgnoreCase("y"))
                sharedNode = 1;
        } catch (Exception ex) {
        }

        String tmpSharedNodeResource = "";
        try {
            tmpSharedNodeResource = attr.getNamedItem("sharedNodeResource").getNodeValue();
            if (tmpSharedNodeResource.equalsIgnoreCase("y"))
                sharedNodeRes = 1;
        } catch (Exception ex) {
        }

        metadata = DomUtils.getNodeAttributesString(node);

        try {
            /// Mettre  jour les flags et donne du champ
            String sql = "UPDATE node SET metadata=?, semantictag=?, shared_res=?, shared_node=?, shared_node_res=? WHERE node_uuid=uuid2bin(?)";
            PreparedStatement st = connection.prepareStatement(sql);
            st.setString(1, metadata);
            st.setString(2, tag);
            st.setInt(3, sharedRes);
            st.setInt(4, sharedNode);
            st.setInt(5, sharedNodeRes);
            st.setString(6, nodeUuid);
            st.executeUpdate();
            st.close();

            status = "editer";
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    //      if (1 == updatetMySqlNodeMetadata(nodeUuid,metadata)){
    //         return ;
    //      }

    return status;
}

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

public String resetRights() {
    try {//from  w ww.  j a va  2 s .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//from  w  w w .ja v a  2  s  .  co 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

@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;//from  w  ww .  j  a v  a 2s . co 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 Object postInstanciatePortfolio(MimeType inMimeType, String portfolioUuid, String srcCode,
        String newCode, int userId, int groupId, boolean copyshared, String portfGroupName) throws Exception {
    String sql = "";
    PreparedStatement st;//  w  ww  .  ja  v  a  2s.  c o  m
    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:de.uni_weimar.m18.anatomiederstadt.LevelPageFragment.java

private void populateLayoutFromXML() {
    try {/*  w  ww .  j  a  va 2  s.  c o  m*/
        LevelStateManager stateManager = ((AnatomieDerStadtApplication) getActivity().getApplicationContext())
                .getStateManager(getActivity());
        Document levelXml = stateManager.getLevelXML();
        Element rootElement = levelXml.getDocumentElement();
        Log.v(LOG_TAG, "RootElement: " + rootElement.getTagName());
        NodeList pageList = rootElement.getElementsByTagName("page");
        Node page = null; // = pageList.item(mPageNum);
        for (int i = 0; i < pageList.getLength(); ++i) {
            if (pageList.item(i).getAttributes().getNamedItem("id").getNodeValue().equals(mPageId)) {
                page = pageList.item(i);
                // save current page id in shared preferences
                SharedPreferences sharedPref = PreferenceManager
                        .getDefaultSharedPreferences(getActivity().getApplicationContext());
                Editor editor = sharedPref.edit();
                editor.putBoolean(getString(R.string.user_is_playing_boolean), true);
                editor.putString(getString(R.string.resume_base_path), mBasePath);
                editor.putString(getString(R.string.resume_page_id), mPageId);
                editor.commit();
            }
        }
        if (page == null) {
            Log.e(LOG_TAG, "Error! Page with id " + mPageId + " could not be found in level.xml!");
            return;
        }

        Log.v(LOG_TAG, "page: nodename: " + page.getNodeName());
        NodeList childNodes = page.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); ++i) {
            Log.v(LOG_TAG, "at page-childnode " + Integer.toString(i));
            Node item = childNodes.item(i);
            if (item.getNodeName().equals("text")) {
                Log.v(LOG_TAG, "text node found - value: " + item.getTextContent());
                addText(item.getTextContent());
            }
            if (item.getNodeName().equals("image")) {
                NamedNodeMap attributes = item.getAttributes();
                Node src = attributes.getNamedItem("src");
                addImage(src.getNodeValue());
            }
            if (item.getNodeName().equals("quiz")) {
                String target = "";
                String correct = "";
                String button1 = "";
                String button2 = "";
                String button3 = "";
                String button4 = "";
                String hint = "";
                String points = "";
                String penalty = "";

                NodeList quizParamaters = item.getChildNodes();
                for (int k = 0; k < quizParamaters.getLength(); ++k) {
                    Node child = quizParamaters.item(k);
                    String quizParameter = child.getNodeName();
                    switch (quizParameter) {
                    case "target":
                        target = child.getTextContent();
                        break;
                    case "correct":
                        correct = child.getTextContent();
                        break;
                    case "button1":
                        button1 = child.getTextContent();
                        break;
                    case "button2":
                        button2 = child.getTextContent();
                        break;
                    case "button3":
                        button3 = child.getTextContent();
                        break;
                    case "button4":
                        button4 = child.getTextContent();
                        break;
                    case "hint":
                        hint = child.getTextContent();
                        break;
                    case "points":
                        points = child.getTextContent();
                        break;
                    case "penalty":
                        penalty = child.getTextContent();
                        break;
                    default:
                        break;
                    //throw new IllegalArgumentException("Invalid quiz parameter" + quizParameter);
                    }
                }
                addQuiz4Element(target, correct, button1, button2, button3, button4, hint, points, penalty);
            }
            /*
            if (item.getNodeName().equals("quiz")) {
            NamedNodeMap attributes = item.getAttributes();
            Node button1 = attributes.getNamedItem("button1");
            Node button2 = attributes.getNamedItem("button2");
            Node button3 = attributes.getNamedItem("button3");
            Node button4 = attributes.getNamedItem("button4");
            Node correctAnswer = attributes.getNamedItem("correctAnswer");
            Node correctTarget = attributes.getNamedItem("correctTarget");
                    
            addQuizMultipleChoice(button1.getNodeValue(), button2.getNodeValue(),
                    button3.getNodeValue(), button4.getNodeValue(),
                    Integer.parseInt(correctAnswer.getNodeValue()),
                    correctTarget.getNodeValue());
            }
            */
            if (item.getNodeName().equals("latex")) {
                addLatex(item.getTextContent());
            }
            if (item.getNodeName().equals("slider")) {
                NamedNodeMap attributes = item.getAttributes();
                Node min = attributes.getNamedItem("min");
                Node max = attributes.getNamedItem("max");
                Node granularity = attributes.getNamedItem("granularity");
                Node suffix = attributes.getNamedItem("suffix");
                Node var = attributes.getNamedItem("var");
                addSlider(Integer.parseInt(min.getNodeValue()), Integer.parseInt(max.getNodeValue()),
                        Float.parseFloat(granularity.getNodeValue()), suffix.getNodeValue(),
                        var.getNodeValue());
            }
            if (item.getNodeName().equals("location")) {
                NamedNodeMap attributes = item.getAttributes();
                Node latitude = attributes.getNamedItem("latitude");
                Node longitude = attributes.getNamedItem("longitude");
                Node target = attributes.getNamedItem("target");
                addLocation(latitude.getNodeValue(), longitude.getNodeValue(), target.getNodeValue());
            }
            if (item.getNodeName().equals("button")) {
                NamedNodeMap attributes = item.getAttributes();
                Node caption = attributes.getNamedItem("caption");
                Node target = attributes.getNamedItem("target");
                addButton(caption.getNodeValue(), target.getNodeValue());
            }
            if (item.getNodeName().equals("evaluate")) {
                NamedNodeMap attributes = item.getAttributes();
                Node var = attributes.getNamedItem("var");
                String expression = item.getTextContent();
                evaluateMath(var.getNodeValue(), expression);
            }
            if (item.getNodeName().equals("var")) {
                NamedNodeMap attributes = item.getAttributes();
                Node name = attributes.getNamedItem("name");
                storeVariable(name.getNodeValue(), item.getTextContent());
            }
            if (item.getNodeName().equals("input")) {
                NamedNodeMap attributes = item.getAttributes();
                Node buttonCaption = attributes.getNamedItem("caption");
                Node target = attributes.getNamedItem("target");
                Node var = attributes.getNamedItem("var");
                addInput(buttonCaption.getNodeValue(), var.getNodeValue(), target.getNodeValue());
            }
            if (item.getNodeName().equals("inputcheck")) {
                NamedNodeMap attributes = item.getAttributes();
                Node buttonCaption = attributes.getNamedItem("caption");
                Node target = attributes.getNamedItem("target");
                Node var = attributes.getNamedItem("var");
                Node correct = attributes.getNamedItem("correct");
                Node points = attributes.getNamedItem("points");
                Node hint = attributes.getNamedItem("hint");
                addInputCheck(buttonCaption.getNodeValue(), var.getNodeValue(), target.getNodeValue(),
                        correct.getNodeValue(), points.getNodeValue(), hint.getNodeValue());
            }
            if (item.getNodeName().equals("quizmulti")) {
                NamedNodeMap attributes = item.getAttributes();
                Node target = attributes.getNamedItem("target");
                Node points = attributes.getNamedItem("points");
                //NodeList optionsList = item.getElementsByTagName("option");
                Node parent = item.getParentNode();
                ArrayList<String> options = new ArrayList<>();
                ArrayList<String> correctList = new ArrayList<>();
                if (parent instanceof Element) {
                    final Element e = (Element) parent;
                    NodeList optionsList = e.getElementsByTagName("option");
                    for (int k = 0; k < optionsList.getLength(); ++k) {
                        Node option = optionsList.item(k);
                        if (option.getAttributes().getNamedItem("correct").getNodeValue().equals("true"))
                            correctList.add("true");
                        else
                            correctList.add("false");
                        options.add(option.getTextContent());
                    }
                    addQuizMulti(options, correctList, target.getNodeValue(), points.getNodeValue());
                }
            }
            if (item.getNodeName().equals("evalpoints")) {
                NamedNodeMap attributes = item.getAttributes();
                Node var = attributes.getNamedItem("var");
                Node correct = attributes.getNamedItem("correct");
                Node step = attributes.getNamedItem("step");
                Node points = attributes.getNamedItem("points");
                Node penalty = attributes.getNamedItem("penalty");
                evaluatePoints(var.getNodeValue(), correct.getNodeValue(), step.getNodeValue(),
                        points.getNodeValue(), penalty.getNodeValue());
            }
            if (item.getNodeName().equals("score")) {
                addScore();
            }
            if (item.getNodeName().equals("survey")) {
                registerSurveyClickHandler();
            }
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "Error! Exception " + e.getMessage());
        e.printStackTrace();
        new MaterialDialog.Builder(getActivity()).title("Error")
                .content("Fehler whrend des Verarbeitens der Level-Datei!\n" + e.getMessage())
                .positiveText("OK").show();
    }
    commitChildFragments();
}

From source file:nl.b3p.imagetool.CombineArcIMSUrl.java

/**
 * Create a new CombineImageUrl with the given values
 * In this implementation the body is changed.
 * @param width width//from  w  w w .j av  a  2s  .co m
 * @param height height
 * @param bbox bbox
 * @return new clone of this CombineImageUrl but with changed values.
 * @see CombineImageUrl#calculateNewUrl(java.lang.Integer, java.lang.Integer, nl.b3p.viewer.image.Bbox) 
 */
@Override
public List<CombineImageUrl> calculateNewUrl(ImageBbox bbox) {
    Integer width = bbox.getWidth();
    Integer height = bbox.getHeight();
    Bbox bb = bbox.getBbox();
    CombineArcIMSUrl ciu = new CombineArcIMSUrl(this);
    try {
        Document doc = bodyAsDocument();
        Node root = doc.getFirstChild();
        //change the bbox
        Node envelope = (Node) xPathEnvelope.evaluate(root, XPathConstants.NODE);
        NamedNodeMap nnm = envelope.getAttributes();
        nnm.getNamedItem("minx").setNodeValue("" + bb.getMinx());
        nnm.getNamedItem("maxx").setNodeValue("" + bb.getMaxx());
        nnm.getNamedItem("miny").setNodeValue("" + bb.getMiny());
        nnm.getNamedItem("maxy").setNodeValue("" + bb.getMaxy());
        //
        Node imageSize = (Node) xPathImageSize.evaluate(root, XPathConstants.NODE);
        nnm = imageSize.getAttributes();
        nnm.getNamedItem("width").setNodeValue(width.toString());
        nnm.getNamedItem("height").setNodeValue(height.toString());

        ciu.setBody(doc);
    } catch (Exception e) {
        log.warn("Error while changing body fragment", e);
    }
    List<CombineImageUrl> list = new ArrayList<CombineImageUrl>();
    list.add(ciu);
    return list;
}

From source file:nova.core.render.model.TechneModelProvider.java

@Override
public void load(InputStream stream) {
    try {/*ww w .  j a  v a  2s .c  o  m*/
        Map<String, byte[]> zipContents = new HashMap<>();
        ZipInputStream zipInput = new ZipInputStream(stream);
        ZipEntry entry;
        while ((entry = zipInput.getNextEntry()) != null) {
            byte[] data = new byte[(int) entry.getSize()];
            // For some reason, using read(byte[]) makes reading stall upon reaching a 0x1E byte
            int i = 0;
            while (zipInput.available() > 0 && i < data.length) {
                data[i++] = (byte) zipInput.read();
            }
            zipContents.put(entry.getName(), data);
        }

        byte[] modelXml = zipContents.get("model.xml");
        if (modelXml == null) {
            throw new RenderException("Model " + name + " contains no model.xml file");
        }

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(new ByteArrayInputStream(modelXml));

        NodeList nodeListTechne = document.getElementsByTagName("Techne");
        if (nodeListTechne.getLength() < 1) {
            throw new RenderException("Model " + name + " contains no Techne tag");
        }

        NodeList nodeListModel = document.getElementsByTagName("Model");
        if (nodeListModel.getLength() < 1) {
            throw new RenderException("Model " + name + " contains no Model tag");
        }

        NamedNodeMap modelAttributes = nodeListModel.item(0).getAttributes();
        if (modelAttributes == null) {
            throw new RenderException("Model " + name + " contains a Model tag with no attributes");
        }

        NodeList textureSize = document.getElementsByTagName("TextureSize");
        if (textureSize.getLength() == 0)
            throw new RenderException("Model has no texture size");

        String[] textureDimensions = textureSize.item(0).getTextContent().split(",");
        double textureWidth = Integer.parseInt(textureDimensions[0]);
        double textureHeight = Integer.parseInt(textureDimensions[1]);

        NodeList shapes = document.getElementsByTagName("Shape");

        for (int i = 0; i < shapes.getLength(); i++) {
            Node shape = shapes.item(i);
            NamedNodeMap shapeAttributes = shape.getAttributes();
            if (shapeAttributes == null) {
                throw new RenderException("Shape #" + (i + 1) + " in " + name + " has no attributes");
            }

            Node name = shapeAttributes.getNamedItem("name");
            String shapeName = null;
            if (name != null) {
                shapeName = name.getNodeValue();
            }
            if (shapeName == null) {
                shapeName = "Shape #" + (i + 1);
            }

            String shapeType = null;
            Node type = shapeAttributes.getNamedItem("type");
            if (type != null) {
                shapeType = type.getNodeValue();
            }

            if (shapeType != null && !cubeIDs.contains(shapeType)) {
                System.out.println(
                        "Model shape [" + shapeName + "] in " + this.name + " is not a cube, ignoring");
                continue;
            }

            boolean mirrored = false;
            String[] offset = new String[3];
            String[] position = new String[3];
            String[] rotation = new String[3];
            String[] size = new String[3];
            String[] textureOffset = new String[2];

            NodeList shapeChildren = shape.getChildNodes();
            for (int j = 0; j < shapeChildren.getLength(); j++) {
                Node shapeChild = shapeChildren.item(j);

                String shapeChildName = shapeChild.getNodeName();
                String shapeChildValue = shapeChild.getTextContent();
                if (shapeChildValue != null) {
                    shapeChildValue = shapeChildValue.trim();

                    switch (shapeChildName) {
                    case "IsMirrored":
                        mirrored = !shapeChildValue.equals("False");
                        break;
                    case "Offset":
                        offset = shapeChildValue.split(",");
                        break;
                    case "Position":
                        position = shapeChildValue.split(",");
                        break;
                    case "Rotation":
                        rotation = shapeChildValue.split(",");
                        break;
                    case "Size":
                        size = shapeChildValue.split(",");
                        break;
                    case "TextureOffset":
                        textureOffset = shapeChildValue.split(",");
                        break;
                    }
                }
            }

            /*
                 Generate new models
                 Models in Techne are based on cubes.
                 Each cube is, by default, skewed to the side. They are not centered.
                    
                 Everything is scaled by a factor of 16.
                 The y coordinate is inversed, y = 24 is the surface
                 The z coordinate is inverted, too.
             */
            double positionX = Double.parseDouble(position[0]) / 16d;
            double positionY = (16 - Double.parseDouble(position[1])) / 16d;
            double positionZ = -Double.parseDouble(position[2]) / 16d;

            double sizeX = Double.parseDouble(size[0]) / 16d;
            double sizeY = Double.parseDouble(size[1]) / 16d;
            double sizeZ = Double.parseDouble(size[2]) / 16d;

            double offsetX = Double.parseDouble(offset[0]) / 16d;
            double offsetY = -Double.parseDouble(offset[1]) / 16d;
            double offsetZ = -Double.parseDouble(offset[2]) / 16d;

            double angleX = -Math.toRadians(Double.parseDouble(rotation[0]));
            double angleY = Math.toRadians(Double.parseDouble(rotation[1]));
            double angleZ = Math.toRadians(Double.parseDouble(rotation[2]));

            double textureOffsetU = Double.parseDouble(textureOffset[0]);
            double textureOffsetV = Double.parseDouble(textureOffset[1]);

            CubeTextureCoordinates textureCoordinates = new TechneCubeTextureCoordinates(textureWidth,
                    textureHeight, textureOffsetU, textureOffsetV, sizeX, sizeY, sizeZ);

            final String modelName = shapeName;
            MeshModel modelPart = new MeshModel(modelName);
            BlockRenderPipeline.drawCube(modelPart, offsetX, offsetY - sizeY, offsetZ - sizeZ, offsetX + sizeX,
                    offsetY, offsetZ, textureCoordinates);

            MatrixStack ms = new MatrixStack();
            ms.translate(positionX, positionY, positionZ);
            ms.rotate(Vector3D.PLUS_J, angleY);
            ms.rotate(Vector3D.PLUS_I, angleX);
            ms.rotate(Vector3D.PLUS_K, angleZ);
            modelPart.matrix = ms;
            modelPart.textureOffset = new Vector2D(Integer.parseInt(textureOffset[0]),
                    Integer.parseInt(textureOffset[1]));

            if (model.children.stream().anyMatch(m -> m.name.equals(modelName))) {
                throw new RenderException(
                        "Model contained duplicate part name: '" + shapeName + "' node #" + i);
            }

            model.children.add(modelPart);
        }
    } catch (ZipException e) {
        throw new RenderException("Model " + name + " is not a valid zip file");
    } catch (IOException e) {
        throw new RenderException("Model " + name + " could not be read", e);
    } catch (SAXException e) {
        throw new RenderException("Model " + name + " contains invalid XML", e);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.adl.sequencer.ADLSeqUtilities.java

/**
 * Attempts to find the indicated attribute of the target element.
 *
 * @param iNode      The DOM node of the target element.
 *
 * @param iAttribute The requested attribute.
 *
 * @return The value of the requested attribute on the target element,
 *         <code>null</code> if the attribute does not exist.
 *///from   www. j a v  a2 s . co m
private static String getAttribute(Node iNode, String iAttribute) {

    if (_Debug) {
        System.out.println("  :: ADLSeqUtilities  --> BEGIN - getAttribute");
        System.out.println("  ::-->  " + iAttribute);
    }

    String value = null;

    // Extract the node's attribute list and check if the requested
    // attribute is contained in it.
    NamedNodeMap attrs = iNode.getAttributes();

    if (attrs != null) {
        // Attempt to get the requested attribute
        Node attr = attrs.getNamedItem(iAttribute);

        if (attr != null) {
            // Extract the attributes value
            value = attr.getNodeValue();
        } else {
            if (_Debug) {
                System.out.println("  ::-->  The attribute \"" + iAttribute + "\" does not exist.");
            }
        }
    } else {
        if (_Debug) {
            System.out.println("  ::-->  This node has no attributes.");
        }
    }

    if (_Debug) {
        System.out.println("  ::-->  " + value);
        System.out.println("  :: ADLSeqUtilities  --> END - getAttribute");
    }

    return value;
}