Example usage for java.util StringTokenizer hasMoreElements

List of usage examples for java.util StringTokenizer hasMoreElements

Introduction

In this page you can find the example usage for java.util StringTokenizer hasMoreElements.

Prototype

public boolean hasMoreElements() 

Source Link

Document

Returns the same value as the hasMoreTokens method.

Usage

From source file:com.android.bluetooth.map.BluetoothMapContent.java

private void extractEmailAddresses(long id, BluetoothMapbMessageMmsEmail message) {
    if (V)/*ww w .  j av  a  2s . c o  m*/
        Log.v(TAG, "extractEmailAddresses with id " + id);
    String urlEmail = "content://com.android.email.provider/message";
    Uri uriEmail = Uri.parse(urlEmail);
    StringTokenizer emailId;
    String tempEmail = null;
    Cursor c = mResolver.query(uriEmail, EMAIL_PROJECTION, "_id = " + id, null, null);
    if (c != null && c.moveToFirst()) {
        String senderName = null;
        if ((senderName = c.getString(c.getColumnIndex(MessageColumns.FROM_LIST))) != null) {
            if (V)
                Log.v(TAG, " senderName " + senderName);
            if (senderName.contains("")) {
                String[] senderStr = senderName.split("");
                if (senderStr != null && senderStr.length > 0) {
                    if (V)
                        Log.v(TAG, " senderStr[1] " + senderStr[1].trim());
                    if (V)
                        Log.v(TAG, " senderStr[0] " + senderStr[0].trim());
                    setVCardFromEmailAddress(message, senderStr[1].trim(), true);
                    if (senderStr[0].indexOf('<') != -1 && senderStr[0].indexOf('>') != -1) {
                        if (V)
                            Log.v(TAG, "from addressing is " + senderName
                                    .substring(senderStr[0].indexOf('<') + 1, senderStr[0].lastIndexOf('>')));
                        message.addFrom(null, senderStr[0].substring(senderStr[0].indexOf('<') + 1,
                                senderStr[0].lastIndexOf('>')));
                    } else {
                        message.addFrom(null, senderStr[0].trim());
                    }
                }
            } else {
                if (V)
                    Log.v(TAG, " senderStr is" + senderName.trim());
                setVCardFromEmailAddress(message, senderName.trim(), true);
                if (senderName.indexOf('<') != -1 && senderName.indexOf('>') != -1) {
                    if (V)
                        Log.v(TAG, "from addressing is " + senderName.substring(senderName.indexOf('<') + 1,
                                senderName.lastIndexOf('>')));
                    message.addFrom(null,
                            senderName.substring(senderName.indexOf('<') + 1, senderName.lastIndexOf('>')));
                } else {
                    message.addFrom(null, senderName.trim());
                }
            }
        }
        String recipientName = null;
        String multiRecepients = null;
        if ((recipientName = c.getString(c.getColumnIndex(MessageColumns.TO_LIST))) != null) {
            if (V)
                Log.v(TAG, " recipientName " + recipientName);
            if (recipientName.contains("")) {
                String[] recepientStr = recipientName.split("");
                if (recepientStr != null && recepientStr.length > 0) {
                    if (V) {
                        Log.v(TAG, " recepientStr[1] " + recepientStr[1].trim());
                        Log.v(TAG, " recepientStr[0] " + recepientStr[0].trim());
                    }
                    setVCardFromEmailAddress(message, recepientStr[1].trim(), false);
                    message.addTo(recepientStr[1].trim(), recepientStr[0].trim());
                }
            } else if (recipientName.contains("")) {
                multiRecepients = recipientName.replace('', ';');
                if (multiRecepients != null) {
                    if (V) {
                        Log.v(TAG, " Setting ::Recepient name :: " + multiRecepients.trim());
                    }
                    emailId = new StringTokenizer(multiRecepients.trim(), ";");
                    do {
                        setVCardFromEmailAddress(message, emailId.nextElement().toString(), false);
                    } while (emailId.hasMoreElements());

                    message.addTo(multiRecepients.trim(), multiRecepients.trim());
                }
            } else if (recipientName.contains(",")) {
                multiRecepients = recipientName.replace(", \"", "; \"");
                multiRecepients = recipientName.replace(", ", "; ");
                multiRecepients = recipientName.replace(",", ";");
                if (multiRecepients != null) {
                    if (V) {
                        Log.v(TAG, "Setting ::Recepient name :: " + multiRecepients.trim());
                    }
                    emailId = new StringTokenizer(multiRecepients.trim(), ";");
                    do {
                        tempEmail = emailId.nextElement().toString();
                        setVCardFromEmailAddress(message, tempEmail, false);

                        if (tempEmail.indexOf('<') != -1) {
                            if (D)
                                Log.d(TAG, "Adding to: " + tempEmail.substring(tempEmail.indexOf('<') + 1,
                                        tempEmail.indexOf('>')));
                            message.addTo(null,
                                    tempEmail.substring(tempEmail.indexOf('<') + 1, tempEmail.indexOf('>')));
                        } else {
                            message.addTo(null, tempEmail);
                        }
                    } while (emailId.hasMoreElements());
                }
            } else {
                Log.v(TAG, " Setting ::Recepient name :: " + recipientName.trim());
                setVCardFromEmailAddress(message, recipientName.trim(), false);
                if (recipientName.indexOf('<') != -1 && recipientName.indexOf('>') != -1) {
                    if (V)
                        Log.v(TAG, "to addressing is " + recipientName.substring(recipientName.indexOf('<') + 1,
                                recipientName.lastIndexOf('>')));
                    message.addTo(null, recipientName.substring(recipientName.indexOf('<') + 1,
                            recipientName.lastIndexOf('>')));
                } else {
                    message.addTo(null, recipientName.trim());
                }
            }
        }

        recipientName = null;
        multiRecepients = null;
        if ((recipientName = c.getString(c.getColumnIndex(MessageColumns.CC_LIST))) != null) {
            if (V)
                Log.v(TAG, " recipientName " + recipientName);
            if (recipientName.contains("^B")) {
                String[] recepientStr = recipientName.split("^B");
                if (recepientStr != null && recepientStr.length > 0) {
                    if (V) {
                        Log.v(TAG, " recepientStr[1] " + recepientStr[1].trim());
                        Log.v(TAG, " recepientStr[0] " + recepientStr[0].trim());
                    }
                    setVCardFromEmailAddress(message, recepientStr[1].trim(), false);
                    message.addCc(recepientStr[1].trim(), recepientStr[0].trim());
                }
            } else if (recipientName.contains("")) {
                multiRecepients = recipientName.replace('', ';');
                if (multiRecepients != null) {
                    if (V) {
                        Log.v(TAG, " Setting ::Recepient name :: " + multiRecepients.trim());
                    }
                    emailId = new StringTokenizer(multiRecepients.trim(), ";");
                    do {
                        setVCardFromEmailAddress(message, emailId.nextElement().toString(), false);
                    } while (emailId.hasMoreElements());

                    message.addCc(multiRecepients.trim(), multiRecepients.trim());
                }
            } else if (recipientName.contains(",")) {
                multiRecepients = recipientName.replace(", \"", "; \"");
                multiRecepients = recipientName.replace(", ", "; ");
                multiRecepients = recipientName.replace(",", ";");

                if (multiRecepients != null) {
                    if (V) {
                        Log.v(TAG, "Setting ::Recepient name :: " + multiRecepients.trim());
                    }
                    emailId = new StringTokenizer(multiRecepients.trim(), ";");
                    do {
                        tempEmail = emailId.nextElement().toString();
                        setVCardFromEmailAddress(message, tempEmail, false);
                        message.addCc(null, tempEmail);
                    } while (emailId.hasMoreElements());
                }
            } else {
                if (V)
                    Log.v(TAG, " Setting ::Recepient name :: " + recipientName.trim());
                setVCardFromEmailAddress(message, recipientName.trim(), false);
                if (recipientName.indexOf('<') != -1 && recipientName.indexOf('>') != -1) {
                    if (V)
                        Log.v(TAG, "CC addressing is " + recipientName.substring(recipientName.indexOf('<') + 1,
                                recipientName.lastIndexOf('>')));
                    message.addCc(null, recipientName.substring(recipientName.indexOf('<') + 1,
                            recipientName.lastIndexOf('>')));
                } else {
                    message.addCc(null, recipientName.trim());
                }
            }
        }
        c.close();
    }
}

From source file:org.energy_home.jemma.osgi.ah.felix.console.web.HacWebCommandProvider.java

protected void renderContent(HttpServletRequest req, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter pw = response.getWriter();
    if (appliancesProxy == null)
        return;/*www .  ja v a 2  s .  co  m*/

    String appRoot = req.getContextPath() + req.getServletPath();
    String pathInfo = req.getPathInfo();
    pathInfo = pathInfo.substring(LABEL.length() + 1);
    StringTokenizer st = null;
    String appliancePid;
    try {
        if (pathInfo.startsWith("/confirm")) {
            st = new StringTokenizer(pathInfo, "/");
            if (st.hasMoreTokens())
                st.nextToken();
            String confirmParam = null;
            if (st.hasMoreTokens())
                confirmParam = st.nextToken();
            appliancePid = null;
            if (st.hasMoreTokens())
                appliancePid = st.nextToken();
            if (confirmParam.equals("delete"))
                pw.println("</br></br><b><font color=\"red\">Are you sure you want to delete appliance "
                        + appliancePid + "?&nbsp;&nbsp;&nbsp;<a href=\"" + appRoot + "/" + LABEL + "/delete/"
                        + appliancePid + "\">yes</a>&nbsp;&nbsp;&nbsp;" + "<a href=\"" + appRoot + "/" + LABEL
                        + "\">no</a>");
        } else if (pathInfo == null || pathInfo.equals("") || pathInfo.equals("/")
                || pathInfo.startsWith("/install") || pathInfo.startsWith("/delete")) {
            List v = null;
            boolean installing = false;
            boolean deleteStatus = true;
            boolean closeStatus = true;
            boolean openStatus = true;
            boolean installStatus = true;
            if (pathInfo.startsWith("/delete")) {
                st = new StringTokenizer(pathInfo, "/");
                if (st.hasMoreTokens())
                    st.nextToken();
                appliancePid = null;
                if (st.hasMoreTokens())
                    appliancePid = st.nextToken();
                deleteStatus = appliancesProxy.deleteAppliance(appliancePid);
            }
            if (pathInfo.startsWith("/install")) {
                installing = true;
                String installParam = null;
                st = new StringTokenizer(pathInfo, "/");
                if (st.hasMoreTokens())
                    st.nextToken();
                if (st.hasMoreTokens())
                    installParam = st.nextToken();
                if (installParam != null) {
                    if (installParam.equals("open"))
                        openStatus = openZigBeeNetwork();
                    else if (installParam.equals("close"))
                        closeStatus = closeZigBeeNetwork();
                    else
                        installStatus = appliancesProxy.installAppliance(installParam);
                }
                v = appliancesProxy.getInstallingAppliancePids();
                pw.println("<br/><b><u>INSTALLING APPLIANCES</u>&nbsp;&nbsp;&nbsp;(<a href=\"" + appRoot + "/"
                        + LABEL + "/install\">Reload page</a>&nbsp;&nbsp;&nbsp;<a href=\"" + appRoot + "/"
                        + LABEL + "\">Go to installed appliances</a>)</b></br>");
                pw.println("<br/><b>[<a href=\"" + appRoot + "/" + LABEL
                        + "/install/open\">Open network</a>&nbsp;&nbsp;&nbsp;<a href=\"" + appRoot + "/" + LABEL
                        + "/install/close\">Close network</a>]</b>");
                if (!openStatus)
                    pw.println("<b><font color=\"red\">Some problem occurred while opening network</font></b>");
                if (!closeStatus)
                    pw.println("<b><font color=\"red\">Some problem occurred while closing network</font></b>");
                if (!installStatus)
                    pw.println("<b><font color=\"red\">Some problem occurred while installing appliance "
                            + installParam + "</font></b>");
                pw.println("</br><hr/>");
            } else {
                v = appliancesProxy.getAppliancePids();
                v.add(PROXY_APPLIANCE_PID);
                pw.println("<br/><b><u>INSTALLED APPLIANCES</u>&nbsp;&nbsp;&nbsp;(<a href=\"" + appRoot + "/"
                        + LABEL + "\">Reload page</a>&nbsp;&nbsp;&nbsp;<a href=\"" + appRoot + "/" + LABEL
                        + "/install\">Go to installing appliances</a>)</b></br><hr/>");
            }
            List driverApplianceList = new ArrayList();
            List virtualApplianceList = new ArrayList();
            List singletonApplianceList = new ArrayList();
            if (v != null) {
                appliancePid = null;
                IAppliance appliance = null;
                for (Iterator iterator = v.iterator(); iterator.hasNext();) {
                    appliancePid = (String) iterator.next();
                    if (installing)
                        appliance = appliancesProxy.getInstallingAppliance(appliancePid);
                    else
                        appliance = appliancesProxy.getAppliance(appliancePid);
                    if (appliance != null) {
                        if (appliance.isSingleton())
                            singletonApplianceList.add(appliance);
                        else if (appliance.isDriver())
                            driverApplianceList.add(appliance);
                        else
                            virtualApplianceList.add(appliance);
                    }
                }
                for (Iterator iterator = driverApplianceList.iterator(); iterator.hasNext();) {
                    appliance = (IAppliance) iterator.next();
                    renderAppliance(appRoot, installing, false, appliance, pw);
                }
                pw.println("<hr/>");
                for (Iterator iterator = virtualApplianceList.iterator(); iterator.hasNext();) {
                    appliance = (IAppliance) iterator.next();
                    renderAppliance(appRoot, installing, false, appliance, pw);
                }
                pw.println("<hr/>");
                for (Iterator iterator = singletonApplianceList.iterator(); iterator.hasNext();) {
                    appliance = (IAppliance) iterator.next();
                    renderAppliance(appRoot, installing, false, appliance, pw);
                }
            }
        } else if (pathInfo.startsWith("/config")) {
            st = new StringTokenizer(pathInfo, "/");
            st.nextToken();
            appliancePid = st.nextToken();
            Integer endPointId = null;
            if (st.hasMoreElements()) {
                endPointId = new Integer(st.nextToken());
            }
            String[] params = req.getParameterValues("param");
            IApplianceConfiguration config = appliancesProxy.getApplianceConfiguration(appliancePid);
            if (config != null && params != null && params.length >= 1) {
                config.updateName(endPointId, params[0]);
                config.updateCategoryPid(endPointId, params[1]);
                config.updateLocationPid(endPointId, params[2]);
                appliancesProxy.updateApplianceConfiguration(config);
            }
            renderApplianceConfiguration(appRoot, appliancesProxy.getApplianceConfiguration(appliancePid),
                    endPointId, pw);
        } else {
            st = new StringTokenizer(pathInfo, "/");
            int i = 0;
            appliancePid = null;
            int endPointId = -1;
            String clusterName = null;
            String methodName = null;
            while (st.hasMoreElements()) {
                switch (i) {
                case 0:
                    appliancePid = st.nextToken();
                    break;
                case 1:
                    endPointId = Integer.parseInt(st.nextToken());
                    break;
                case 2:
                    clusterName = st.nextToken();
                    break;
                case 3:
                    methodName = st.nextToken();
                    break;
                default:
                    break;
                }
                i++;
            }
            String[] params = req.getParameterValues("param");
            IAppliance appliance = appliancesProxy.getAppliance(appliancePid);
            if (appliance == null)
                appliance = appliancesProxy.getInstallingAppliance(appliancePid);
            if (appliance == null) {
                pw.println(
                        "<br><br>Please wait some seconds and try to reload this web page or click on the AH tab...");
                return;
            }
            IApplianceConfiguration config = appliancesProxy.getApplianceConfiguration(appliancePid);
            if (endPointId < 0) {
                renderAppliance(appRoot, false, true, appliance, pw);
            } else {
                renderClusterCommands(appRoot, config, appliance.getEndPoint(endPointId), clusterName,
                        methodName, params, pw);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.pari.nm.utils.db.InventoryDBHelper.java

public static void insertModuleEolInfo(String modFilePath) {
    if (InventoryDBHelper.isModulesPopulated()) {
        return;/*  ww  w. j  av a 2 s.c  om*/
    }
    Connection c = null;
    PreparedStatement ps = null;
    InputStream in = null;
    try {
        if (modFilePath != null && (modFilePath.startsWith("/") || modFilePath.startsWith("\\"))) {
            modFilePath = modFilePath.substring(1);
        }
        in = Thread.currentThread().getContextClassLoader().getResourceAsStream(modFilePath);

        c = DBHelper.getConnection();
        c.setAutoCommit(false);
        ps = c.prepareStatement(DBHelperConstants.INSERT_MODULE_EOL_DB);

        StringBuffer sbuf = new StringBuffer();
        byte[] buf = new byte[8096];
        int read = -1;
        while ((read = in.read(buf)) != -1) {
            sbuf.append(new String(buf, 0, read));
        }

        StringTokenizer st = new StringTokenizer(sbuf.toString(), "\n");
        if (st.hasMoreElements()) {
            st.nextElement(); // takeout the header
        }
        while (st.hasMoreElements()) {
            String line = st.nextToken().trim();
            if (line.length() == 0) {
                continue;
            }
            StringTokenizer stt = new StringTokenizer(line, "\t");
            String fru = null;
            String deviceType = null;
            String url = null;
            Timestamp aDate = null;
            Timestamp eosDate = null;
            Timestamp eolDate = null;
            Timestamp eocrDate = null;
            Timestamp eoeDate = null;
            if (stt.hasMoreTokens()) {
                fru = stt.nextToken();
            }
            if (stt.hasMoreTokens()) {
                deviceType = stt.nextToken();
            }
            if (stt.hasMoreTokens()) {
                url = stt.nextToken();
            }
            if (stt.hasMoreTokens()) {
                aDate = getTimestamp(stt.nextToken());
            }
            if (stt.hasMoreTokens()) {
                eosDate = getTimestamp(stt.nextToken());
            }
            if (stt.hasMoreTokens()) {
                eolDate = getTimestamp(stt.nextToken());
            }
            if (stt.hasMoreTokens()) {
                eoeDate = getTimestamp(stt.nextToken());
            }
            if (stt.hasMoreTokens()) {
                eocrDate = getTimestamp(stt.nextToken());
            }

            ps.setString(1, fru);
            ps.setString(2, url);
            ps.setString(3, deviceType);
            ps.setTimestamp(4, aDate);
            ps.setTimestamp(5, eosDate);
            ps.setTimestamp(6, eolDate);
            ps.setTimestamp(7, eocrDate);
            ps.setTimestamp(8, eoeDate);
            ps.executeUpdate();
        }
    } catch (Exception ee) {
        logger.warn("Error in insertModuleEolInfo", ee);
    } finally {
        try {
            c.commit();

        } catch (Exception ee) {
        }
        try {
            c.setAutoCommit(true);

        } catch (Exception ee) {
        }

        try {
            ps.close();
        } catch (Exception ee) {
        }

        try {
            DBHelper.releaseConnection(c);
        } catch (Exception ee) {
        }
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException ex) {
            logger.error("Exception in closing InputStream in InventoryDBHelper", ex);
        }
    }
}

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

private String writeNode(Node node, String portfolioUuid, String portfolioModelId, int userId, int ordrer,
        String forcedUuid, String forcedUuidParent, int sharedResParent, int sharedNodeResParent, boolean isPut)
        throws Exception {
    String uuid = "";
    String originUuid = null;/*from  w  ww. j a  va  2  s.  c  o  m*/
    String parentUuid = null;
    String nodeChildrenUuid = null;
    String modelNodeUuid = null;
    int sharedRes = 0;
    int sharedNode = 0;
    int sharedNodeRes = 0;

    String sharedResUuid = null;
    String sharedNodeUuid = null;
    String sharedNodeResUuid = null;

    String metadata = "";
    String metadataWad = "";
    String metadataEpm = "";
    String asmType = null;
    String xsiType = null;
    String semtag = null;
    String format = null;
    String label = null;
    String code = null;
    String descr = null;
    String semanticTag = null;

    String nodeRole = null;

    String access = null;

    int returnValue = 0;

    if (node == null)
        return null;

    if (node.getNodeName().equals("portfolio")) {
        // On n'attribue pas d'uuid sur la balise portfolio
    } else {
        try {
            if (node.getAttributes().getNamedItem("id") != null) {
                originUuid = node.getAttributes().getNamedItem("id").getNodeValue();
                if (originUuid.length() > 0) {
                    uuid = node.getAttributes().getNamedItem("id").getNodeValue();
                } else
                    uuid = UUID.randomUUID().toString();
            } else
                uuid = UUID.randomUUID().toString();
        } catch (Exception ex) {
            uuid = UUID.randomUUID().toString();
        }
    }

    // Si uuid forc, alors on ne tient pas compte de l'uuid indiqu dans le xml
    if (forcedUuid != null) {
        uuid = forcedUuid;
        parentUuid = forcedUuidParent;
    } else if (forcedUuidParent != null) {
        // Dans le cas d'un uuid parent forc => POST => on gnre un UUID
        if (uuid == null)
            uuid = UUID.randomUUID().toString();
        parentUuid = forcedUuidParent;
    } else {
        try {

            if (node.getParentNode().getAttributes().getNamedItem("id") != null)
                if (node.getParentNode().getAttributes().getNamedItem("id").getNodeValue().length() > 0)
                    parentUuid = node.getParentNode().getAttributes().getNamedItem("id").getNodeValue();
        } catch (Exception ex) {
            //parentUuid = UUID.randomUUID().toString();
        }
    }

    try {
        if (node.getNodeName() != null)
            asmType = node.getNodeName();
    } catch (Exception ex) {
    }
    try {
        if (node.getAttributes().getNamedItem("xsi_type") != null)
            xsiType = node.getAttributes().getNamedItem("xsi_type").getNodeValue().trim();
    } catch (Exception ex) {
    }
    try {
        if (node.getAttributes().getNamedItem("semtag") != null)
            semtag = node.getAttributes().getNamedItem("semtag").getNodeValue().trim();
    } catch (Exception ex) {

    }
    try {
        if (node.getAttributes().getNamedItem("format") != null)
            format = node.getAttributes().getNamedItem("format").getNodeValue().trim();
    } catch (Exception ex) {
    }

    // Si id dfini, alors on crit en base
    //TODO Transactionnel noeud+enfant
    NodeList children = null;
    try {
        children = node.getChildNodes();
        // On parcourt une premire fois les enfants pour rcuperer la liste  crire en base
        int j = 0;
        for (int i = 0; i < children.getLength(); i++) {
            //if(!children.item(i).getNodeName().equals("#text"))
            //   nodeChildren.add(children.item(i).getAttributes().getNamedItem("id").getNodeValue());
            if (!children.item(i).getNodeName().equals("#text")) {
                if (children.item(i).getNodeName().equals("metadata-wad")) {

                    metadataWad = DomUtils.getNodeAttributesString(children.item(i));// " attr1=\"wad1\" attr2=\"wad2\" ";
                    metadataWad = processMeta(userId, metadataWad);

                    // Gestion de la securit intgre
                    //
                    Node metadataWadNode = children.item(i);
                    try {
                        if (metadataWadNode.getAttributes().getNamedItem("access") != null) {
                            //if(access.equalsIgnoreCase("public") || access.contains("public"))
                            //   credential.postGroupRight("all",uuid,Credential.READ,portfolioUuid,userId);
                        }
                    } catch (Exception ex) {
                    }

                    try {
                        if (metadataWadNode.getAttributes().getNamedItem("seenoderoles") != null) {
                            StringTokenizer tokens = new StringTokenizer(
                                    metadataWadNode.getAttributes().getNamedItem("seenoderoles").getNodeValue(),
                                    " ");
                            while (tokens.hasMoreElements()) {

                                nodeRole = tokens.nextElement().toString();
                                credential.postGroupRight(nodeRole, uuid, Credential.READ, portfolioUuid,
                                        userId);
                            }
                        }
                    } catch (Exception ex) {
                    }
                    try {
                        if (metadataWadNode.getAttributes().getNamedItem("delnoderoles") != null) {
                            StringTokenizer tokens = new StringTokenizer(
                                    metadataWadNode.getAttributes().getNamedItem("delnoderoles").getNodeValue(),
                                    " ");
                            while (tokens.hasMoreElements()) {

                                nodeRole = tokens.nextElement().toString();
                                credential.postGroupRight(nodeRole, uuid, Credential.DELETE, portfolioUuid,
                                        userId);
                            }
                        }
                    } catch (Exception ex) {
                    }
                    try {
                        if (metadataWadNode.getAttributes().getNamedItem("editnoderoles") != null) {
                            StringTokenizer tokens = new StringTokenizer(metadataWadNode.getAttributes()
                                    .getNamedItem("editnoderoles").getNodeValue(), " ");
                            while (tokens.hasMoreElements()) {

                                nodeRole = tokens.nextElement().toString();
                                credential.postGroupRight(nodeRole, uuid, Credential.WRITE, portfolioUuid,
                                        userId);
                            }
                        }
                    } catch (Exception ex) {
                    }
                    try {
                        if (metadataWadNode.getAttributes().getNamedItem("submitnoderoles") != null) {
                            StringTokenizer tokens = new StringTokenizer(metadataWadNode.getAttributes()
                                    .getNamedItem("submitnoderoles").getNodeValue(), " ");
                            while (tokens.hasMoreElements()) {

                                nodeRole = tokens.nextElement().toString();
                                credential.postGroupRight(nodeRole, uuid, Credential.SUBMIT, portfolioUuid,
                                        userId);
                            }
                        }
                    } catch (Exception ex) {
                    }
                    //
                    try {
                        if (metadataWadNode.getAttributes().getNamedItem("seeresroles") != null) {
                            StringTokenizer tokens = new StringTokenizer(
                                    metadataWadNode.getAttributes().getNamedItem("seeresroles").getNodeValue(),
                                    " ");
                            while (tokens.hasMoreElements()) {

                                nodeRole = tokens.nextElement().toString();
                                credential.postGroupRight(nodeRole, uuid, Credential.READ, portfolioUuid,
                                        userId);
                            }
                        }
                    } catch (Exception ex) {
                    }

                    try {
                        if (metadataWadNode.getAttributes().getNamedItem("delresroles") != null) {
                            StringTokenizer tokens = new StringTokenizer(
                                    metadataWadNode.getAttributes().getNamedItem("delresroles").getNodeValue(),
                                    " ");
                            while (tokens.hasMoreElements()) {

                                nodeRole = tokens.nextElement().toString();
                                credential.postGroupRight(nodeRole, uuid, Credential.DELETE, portfolioUuid,
                                        userId);
                            }
                        }
                    } catch (Exception ex) {
                    }

                    try {
                        if (metadataWadNode.getAttributes().getNamedItem("editresroles") != null) {
                            StringTokenizer tokens = new StringTokenizer(
                                    metadataWadNode.getAttributes().getNamedItem("editresroles").getNodeValue(),
                                    " ");
                            while (tokens.hasMoreElements()) {

                                nodeRole = tokens.nextElement().toString();
                                credential.postGroupRight(nodeRole, uuid, Credential.WRITE, portfolioUuid,
                                        userId);
                            }
                        }
                    } catch (Exception ex) {
                    }

                    try {
                        if (metadataWadNode.getAttributes().getNamedItem("submitresroles") != null) {
                            StringTokenizer tokens = new StringTokenizer(metadataWadNode.getAttributes()
                                    .getNamedItem("submitresroles").getNodeValue(), " ");
                            while (tokens.hasMoreElements()) {

                                nodeRole = tokens.nextElement().toString();
                                credential.postGroupRight(nodeRole, uuid, Credential.SUBMIT, portfolioUuid,
                                        userId);
                            }
                        }
                    } catch (Exception ex) {
                    }

                    try {
                        Node actionroles = metadataWadNode.getAttributes().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);
                            }
                        }
                    } catch (Exception ex) {
                    }

                } else if (children.item(i).getNodeName().equals("metadata-epm")) {
                    metadataEpm = DomUtils.getNodeAttributesString(children.item(i));
                } else if (children.item(i).getNodeName().equals("metadata")) {
                    String tmpSharedRes = "";
                    try {
                        tmpSharedRes = children.item(i).getAttributes().getNamedItem("sharedResource")
                                .getNodeValue();
                    } catch (Exception ex) {
                    }

                    String tmpSharedNode = "";
                    try {
                        tmpSharedNode = children.item(i).getAttributes().getNamedItem("sharedNode")
                                .getNodeValue();
                    } catch (Exception ex) {
                    }

                    String tmpSharedNodeRes = "";
                    try {
                        tmpSharedNodeRes = children.item(i).getAttributes().getNamedItem("sharedNodeResource")
                                .getNodeValue();
                    } catch (Exception ex) {
                    }

                    try {
                        semanticTag = children.item(i).getAttributes().getNamedItem("semantictag")
                                .getNodeValue();
                        /*
                          else if(children.item(i).getNodeName().equals("semanticTag"))
                          {
                              semanticTag = DomUtils.getInnerXml(children.item(i));
                          }
                          //*/
                    } catch (Exception ex) {
                    }

                    if (tmpSharedRes.equalsIgnoreCase("y"))
                        sharedRes = 1;
                    if (tmpSharedNode.equalsIgnoreCase("y"))
                        sharedNode = 1;
                    if (tmpSharedNodeRes.equalsIgnoreCase("y"))
                        sharedNodeRes = 1;

                    metadata = DomUtils.getNodeAttributesString(children.item(i));
                }
                // On vrifie si l'enfant n'est pas un lement de type code, label ou descr
                else if (children.item(i).getNodeName().equals("label")) {
                    label = DomUtils.getInnerXml(children.item(i));
                } else if (children.item(i).getNodeName().equals("code")) {
                    code = DomUtils.getInnerXml(children.item(i));
                } else if (children.item(i).getNodeName().equals("description")) {
                    descr = DomUtils.getInnerXml(children.item(i));
                } else if (children.item(i).getAttributes() != null) {
                    if (children.item(i).getAttributes().getNamedItem("id") != null) {

                        if (nodeChildrenUuid == null)
                            nodeChildrenUuid = "";
                        if (j > 0)
                            nodeChildrenUuid += ",";
                        nodeChildrenUuid += children.item(i).getAttributes().getNamedItem("id").getNodeValue()
                                .toString();

                        j++;
                    }
                }
            }
        }
    } catch (Exception ex) {
        // Pas d'enfants
        ex.printStackTrace();
    }

    //System.out.println(uuid+":"+node.getNodeName()+":"+parentUuid+":"+nodeChildrenUuid);

    // Si on est au debut de l'arbre, on stocke la dfinition du portfolio
    // dans la table portfolio
    if (uuid != null && node.getParentNode() != null) {
        if (node.getNodeName().equals("asmRoot")) {
            // On retrouve le code cach dans une ressource. blegh
            NodeList childs = node.getChildNodes();
            for (int k = 0; k < childs.getLength(); ++k) {
                Node child = childs.item(k);
                if ("asmResource".equals(child.getNodeName())) {
                    NodeList grandchilds = child.getChildNodes();
                    for (int l = 0; l < grandchilds.getLength(); ++l) {
                        Node gc = grandchilds.item(l);
                        if ("code".equals(gc.getNodeName())) {
                            code = DomUtils.getInnerXml(gc);
                            break;
                        }
                    }
                }
                if (code != null)
                    break;
            }
        } else if (portfolioUuid == null)
            throw new Exception("Il manque la balise asmRoot !!");
    }

    // Si on instancie un portfolio  partir d'un modle
    // Alors on gre les share*
    if (portfolioModelId != null) {
        if (sharedNode == 1) {
            sharedNodeUuid = originUuid;
        }

    } else
        modelNodeUuid = null;

    if (uuid != null && !node.getNodeName().equals("portfolio") && !node.getNodeName().equals("asmResource"))
        returnValue = insertMySqlNode(uuid, parentUuid, nodeChildrenUuid, asmType, xsiType, sharedRes,
                sharedNode, sharedNodeRes, sharedResUuid, sharedNodeUuid, sharedNodeResUuid, metadata,
                metadataWad, metadataEpm, semtag, semanticTag, label, code, descr, format, ordrer, userId,
                portfolioUuid);

    // Si le parent a t forc, cela veut dire qu'il faut mettre  jour les enfants du parent
    //TODO
    // MODIF : On le met  jour tout le temps car dans le cas d'un POST les uuid ne sont pas connus  l'avance
    //if(forcedUuidParent!=null)
    updateMysqlNodeChildren(forcedUuidParent);

    // Si le noeud est de type asmResource, on stocke le innerXML du noeud
    if (node.getNodeName().equals("asmResource")) {
        if (portfolioModelId != null) {
            if (xsiType.equals("nodeRes") && sharedNodeResParent == 1) {
                sharedNodeResUuid = originUuid;
                insertMysqlResource(sharedNodeResUuid, parentUuid, xsiType, DomUtils.getInnerXml(node),
                        portfolioModelId, sharedNodeResParent, sharedResParent, userId);
            } else if (!xsiType.equals("context") && !xsiType.equals("nodeRes") && sharedResParent == 1) {

                sharedResUuid = originUuid;
                insertMysqlResource(sharedResUuid, parentUuid, xsiType, DomUtils.getInnerXml(node),
                        portfolioModelId, sharedNodeResParent, sharedResParent, userId);
            } else {
                insertMysqlResource(uuid, parentUuid, xsiType, DomUtils.getInnerXml(node), portfolioModelId,
                        sharedNodeResParent, sharedResParent, userId);
            }
        } else
            insertMysqlResource(uuid, parentUuid, xsiType, DomUtils.getInnerXml(node), portfolioModelId,
                    sharedNodeResParent, sharedResParent, userId);

    }

    // On vrifie enfin si on a import des ressources fichiers dont l'UID correspond
    // pour remplacer l'UID d'origine par l'UID gener
    if (portfolioRessourcesImportUuid.size() > 0) {
        for (int k = 0; k < portfolioRessourcesImportUuid.size(); k++) {
            if (portfolioRessourcesImportUuid.get(k).equals(originUuid)) {
                String portfolioRessourcesDestPath = portfolioRessourcesImportPath.get(k).replace(originUuid,
                        uuid);
                File f = new File(portfolioRessourcesImportPath.get(k));
                f.renameTo(new File(portfolioRessourcesDestPath));
                //System.out.println();
                updateMysqlFileUuid(originUuid, uuid);
            }

        }
    }

    // On reparcourt ensuite les enfants pour continuer la recursivit
    //      if(children!=null && sharedNode!=1)
    if (children != null) {
        int k = 0;
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            if (child.getAttributes() != null) {
                String nodeName = child.getNodeName();
                if ("asmRoot".equals(nodeName) || "asmStructure".equals(nodeName) || "asmUnit".equals(nodeName)
                        || "asmUnitStructure".equals(nodeName) || "asmUnitContent".equals(nodeName)
                        || "asmContext".equals(nodeName)) {
                    //System.out.println("uid="+uuid+":"+",enfant_uuid="+children.item(i).getAttributes().getNamedItem("id")+",ordre="+k);
                    writeNode(child, portfolioUuid, portfolioModelId, userId, k, null, uuid, sharedRes,
                            sharedNodeRes, isPut);
                    k++;
                } else if ("asmResource".equals(nodeName)) // Les asmResource pose problme dans l'ordre des noeuds
                {
                    writeNode(child, portfolioUuid, portfolioModelId, userId, k, null, uuid, sharedRes,
                            sharedNodeRes, isPut);
                }
            }
        }
    }

    return uuid;
}

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

public String resetRights() {
    try {/*from w  w  w .j av  a  2 s.c o m*/
        /// 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

private String writeNode(Node node, String portfolioUuid, String portfolioModelId, int userId, int ordrer,
        String forcedUuid, String forcedUuidParent, int sharedResParent, int sharedNodeResParent,
        boolean rewriteId, HashMap<String, String> resolve) throws Exception {
    String uuid = "";
    String originUuid = null;//from w w w.  j  av a  2 s. c o  m
    String parentUuid = null;
    String modelNodeUuid = null;
    int sharedRes = 0;
    int sharedNode = 0;
    int sharedNodeRes = 0;

    String sharedResUuid = null;
    String sharedNodeUuid = null;
    String sharedNodeResUuid = null;

    String metadata = "";
    String metadataWad = "";
    String metadataEpm = "";
    String asmType = null;
    String xsiType = null;
    String semtag = null;
    String format = null;
    String label = null;
    String code = null;
    String descr = null;
    String semanticTag = null;

    String nodeRole = null;

    String access = null;

    int returnValue = 0;

    if (node == null)
        return null;

    if (node.getNodeName().equals("portfolio")) {
        // On n'attribue pas d'uuid sur la balise portfolio
    } else {
    }

    String currentid = "";
    Node idAtt = node.getAttributes().getNamedItem("id");
    if (idAtt != null) {
        String tempId = idAtt.getNodeValue();
        if (tempId.length() > 0)
            currentid = tempId;
    }

    // Si uuid forc, alors on ne tient pas compte de l'uuid indiqu dans le xml
    if (rewriteId) // On garde les uuid par dfaut
    {
        uuid = currentid;
    } else {
        uuid = forcedUuid;
    }

    if (resolve != null) // Mapping old id -> new id
        resolve.put(currentid, uuid);

    if (forcedUuidParent != null) {
        // Dans le cas d'un uuid parent forc => POST => on gnre un UUID
        parentUuid = forcedUuidParent;
    }

    /// Rcupration d'autre infos
    try {
        if (node.getNodeName() != null)
            asmType = node.getNodeName();
    } catch (Exception ex) {
    }
    try {
        if (node.getAttributes().getNamedItem("xsi_type") != null)
            xsiType = node.getAttributes().getNamedItem("xsi_type").getNodeValue().trim();
    } catch (Exception ex) {
    }
    try {
        if (node.getAttributes().getNamedItem("semtag") != null)
            semtag = node.getAttributes().getNamedItem("semtag").getNodeValue().trim();
    } catch (Exception ex) {

    }
    try {
        if (node.getAttributes().getNamedItem("format") != null)
            format = node.getAttributes().getNamedItem("format").getNodeValue().trim();
    } catch (Exception ex) {
    }

    // Si id dfini, alors on crit en base
    //TODO Transactionnel noeud+enfant
    NodeList children = null;
    try {
        children = node.getChildNodes();
        // On parcourt une premire fois les enfants pour rcuperer la liste  crire en base
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);

            if ("#text".equals(child.getNodeName()))
                continue;

            //if(!children.item(i).getNodeName().equals("#text"))
            //   nodeChildren.add(children.item(i).getAttributes().getNamedItem("id").getNodeValue());
            if (children.item(i).getNodeName().equals("metadata-wad")) {
                metadataWad = DomUtils.getNodeAttributesString(children.item(i));// " attr1=\"wad1\" attr2=\"wad2\" ";
                //               metadataWad = processMeta(userId, metadataWad);

                // Gestion de la securit intgre
                //
                Node metadataWadNode = children.item(i);
                try {
                    if (metadataWadNode.getAttributes().getNamedItem("access") != null) {
                        //if(access.equalsIgnoreCase("public") || access.contains("public"))
                        //   credential.postGroupRight("all",uuid,Credential.READ,portfolioUuid,userId);
                    }
                } catch (Exception ex) {
                }

                try {
                    if (metadataWadNode.getAttributes().getNamedItem("seenoderoles") != null) {
                        StringTokenizer tokens = new StringTokenizer(
                                metadataWadNode.getAttributes().getNamedItem("seenoderoles").getNodeValue(),
                                " ");
                        while (tokens.hasMoreElements()) {

                            nodeRole = tokens.nextElement().toString();
                            credential.postGroupRight(nodeRole, uuid, Credential.READ, portfolioUuid, userId);
                        }
                    }
                } catch (Exception ex) {
                }
                try {
                    if (metadataWadNode.getAttributes().getNamedItem("delnoderoles") != null) {
                        StringTokenizer tokens = new StringTokenizer(
                                metadataWadNode.getAttributes().getNamedItem("delnoderoles").getNodeValue(),
                                " ");
                        while (tokens.hasMoreElements()) {

                            nodeRole = tokens.nextElement().toString();
                            credential.postGroupRight(nodeRole, uuid, Credential.DELETE, portfolioUuid, userId);
                        }
                    }
                } catch (Exception ex) {
                }
                try {
                    if (metadataWadNode.getAttributes().getNamedItem("editnoderoles") != null) {
                        StringTokenizer tokens = new StringTokenizer(
                                metadataWadNode.getAttributes().getNamedItem("editnoderoles").getNodeValue(),
                                " ");
                        while (tokens.hasMoreElements()) {

                            nodeRole = tokens.nextElement().toString();
                            credential.postGroupRight(nodeRole, uuid, Credential.WRITE, portfolioUuid, userId);
                        }
                    }
                } catch (Exception ex) {
                }
                try {
                    if (metadataWadNode.getAttributes().getNamedItem("submitnoderoles") != null) {
                        StringTokenizer tokens = new StringTokenizer(
                                metadataWadNode.getAttributes().getNamedItem("submitnoderoles").getNodeValue(),
                                " ");
                        while (tokens.hasMoreElements()) {
                            nodeRole = tokens.nextElement().toString();
                            credential.postGroupRight(nodeRole, uuid, Credential.SUBMIT, portfolioUuid, userId);
                        }
                    }
                } catch (Exception ex) {
                }
                //
                try {
                    if (metadataWadNode.getAttributes().getNamedItem("seeresroles") != null) {
                        StringTokenizer tokens = new StringTokenizer(
                                metadataWadNode.getAttributes().getNamedItem("seeresroles").getNodeValue(),
                                " ");
                        while (tokens.hasMoreElements()) {
                            nodeRole = tokens.nextElement().toString();
                            credential.postGroupRight(nodeRole, uuid, Credential.READ, portfolioUuid, userId);
                        }
                    }
                } catch (Exception ex) {
                }

                try {
                    if (metadataWadNode.getAttributes().getNamedItem("delresroles") != null) {
                        StringTokenizer tokens = new StringTokenizer(
                                metadataWadNode.getAttributes().getNamedItem("delresroles").getNodeValue(),
                                " ");
                        while (tokens.hasMoreElements()) {
                            nodeRole = tokens.nextElement().toString();
                            credential.postGroupRight(nodeRole, uuid, Credential.DELETE, portfolioUuid, userId);
                        }
                    }
                } catch (Exception ex) {
                }

                try {
                    if (metadataWadNode.getAttributes().getNamedItem("editresroles") != null) {
                        StringTokenizer tokens = new StringTokenizer(
                                metadataWadNode.getAttributes().getNamedItem("editresroles").getNodeValue(),
                                " ");
                        while (tokens.hasMoreElements()) {
                            nodeRole = tokens.nextElement().toString();
                            credential.postGroupRight(nodeRole, uuid, Credential.WRITE, portfolioUuid, userId);
                        }
                    }
                } catch (Exception ex) {
                }

                try {
                    if (metadataWadNode.getAttributes().getNamedItem("submitresroles") != null) {
                        StringTokenizer tokens = new StringTokenizer(
                                metadataWadNode.getAttributes().getNamedItem("submitresroles").getNodeValue(),
                                " ");
                        while (tokens.hasMoreElements()) {
                            nodeRole = tokens.nextElement().toString();
                            credential.postGroupRight(nodeRole, uuid, Credential.SUBMIT, portfolioUuid, userId);
                        }
                    }
                } catch (Exception ex) {
                }

                try {
                    Node actionroles = metadataWadNode.getAttributes().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);
                        }
                    }
                } catch (Exception ex) {
                }

                try /// TODO:  l'intgration avec sakai/LTI
                {
                    Node notifyroles = metadataWadNode.getAttributes().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);
                    }
                } catch (Exception ex) {
                }

            } else if (children.item(i).getNodeName().equals("metadata-epm")) {
                metadataEpm = DomUtils.getNodeAttributesString(children.item(i));
            } else if (children.item(i).getNodeName().equals("metadata")) {
                try {
                    String publicatt = children.item(i).getAttributes().getNamedItem("public").getNodeValue();
                    if ("Y".equals(publicatt))
                        setPublicState(userId, portfolioUuid, true);
                    else if ("N".equals(publicatt))
                        setPublicState(userId, portfolioUuid, false);
                } catch (Exception ex) {
                }

                String tmpSharedRes = "";
                try {
                    tmpSharedRes = children.item(i).getAttributes().getNamedItem("sharedResource")
                            .getNodeValue();
                } catch (Exception ex) {
                }

                String tmpSharedNode = "";
                try {
                    tmpSharedNode = children.item(i).getAttributes().getNamedItem("sharedNode").getNodeValue();
                } catch (Exception ex) {
                }

                String tmpSharedNodeRes = "";
                try {
                    tmpSharedNodeRes = children.item(i).getAttributes().getNamedItem("sharedNodeResource")
                            .getNodeValue();
                } catch (Exception ex) {
                }

                try {
                    semanticTag = children.item(i).getAttributes().getNamedItem("semantictag").getNodeValue();
                    /*
                    else if(children.item(i).getNodeName().equals("semanticTag"))
                    {
                       semanticTag = DomUtils.getInnerXml(children.item(i));
                    }
                    //*/
                } catch (Exception ex) {
                }

                if (tmpSharedRes.equalsIgnoreCase("y"))
                    sharedRes = 1;
                if (tmpSharedNode.equalsIgnoreCase("y"))
                    sharedNode = 1;
                if (tmpSharedNodeRes.equalsIgnoreCase("y"))
                    sharedNodeRes = 1;

                metadata = DomUtils.getNodeAttributesString(children.item(i));
            }
            // On vrifie si l'enfant n'est pas un lement de type code, label ou descr
            else if (children.item(i).getNodeName().equals("label")) {
                label = DomUtils.getInnerXml(children.item(i));
            } else if (children.item(i).getNodeName().equals("code")) {
                code = DomUtils.getInnerXml(children.item(i));
            } else if (children.item(i).getNodeName().equals("description")) {
                descr = DomUtils.getInnerXml(children.item(i));
            } else if (children.item(i).getAttributes() != null) {
                /*
                if(children.item(i).getAttributes().getNamedItem("id")!=null)
                {
                        
                   if(nodeChildrenUuid==null) nodeChildrenUuid = "";
                   if(j>0) nodeChildrenUuid += ",";
                   nodeChildrenUuid += children.item(i).getAttributes().getNamedItem("id").getNodeValue().toString();
                        
                   j++;
                }
                //*/
            }
        }
    } catch (Exception ex) {
        // Pas d'enfants
        ex.printStackTrace();
    }

    //System.out.println(uuid+":"+node.getNodeName()+":"+parentUuid+":"+nodeChildrenUuid);

    // Si on est au debut de l'arbre, on stocke la dfinition du portfolio
    // dans la table portfolio
    if (uuid != null && node.getParentNode() != null) {
        // On retrouve le code cach dans les ressources. blegh
        NodeList childs = node.getChildNodes();
        for (int k = 0; k < childs.getLength(); ++k) {
            Node child = childs.item(k);
            if ("asmResource".equals(child.getNodeName())) {
                NodeList grandchilds = child.getChildNodes();
                for (int l = 0; l < grandchilds.getLength(); ++l) {
                    Node gc = grandchilds.item(l);
                    if ("code".equals(gc.getNodeName())) {
                        code = DomUtils.getInnerXml(gc);
                        break;
                    }
                }
            }
            if (code != null)
                break;
        }

        if (node.getNodeName().equals("asmRoot")) {
        } else if (portfolioUuid == null)
            throw new Exception("Il manque la balise asmRoot !!");
    }

    // Si on instancie un portfolio  partir d'un modle
    // Alors on gre les share*
    if (portfolioModelId != null) {
        if (sharedNode == 1) {
            sharedNodeUuid = originUuid;
        }
    } else
        modelNodeUuid = null;

    if (uuid != null && !node.getNodeName().equals("portfolio") && !node.getNodeName().equals("asmResource"))
        returnValue = insertMySqlNode(uuid, parentUuid, "", asmType, xsiType, sharedRes, sharedNode,
                sharedNodeRes, sharedResUuid, sharedNodeUuid, sharedNodeResUuid, metadata, metadataWad,
                metadataEpm, semtag, semanticTag, label, code, descr, format, ordrer, userId, portfolioUuid);

    // Si le parent a t forc, cela veut dire qu'il faut mettre  jour les enfants du parent
    //TODO
    // MODIF : On le met  jour tout le temps car dans le cas d'un POST les uuid ne sont pas connus  l'avance
    //if(forcedUuidParent!=null)

    // Si le noeud est de type asmResource, on stocke le innerXML du noeud
    if (node.getNodeName().equals("asmResource")) {
        if (portfolioModelId != null) {
            if (xsiType.equals("nodeRes") && sharedNodeResParent == 1) {
                sharedNodeResUuid = originUuid;
                insertMysqlResource(sharedNodeResUuid, parentUuid, xsiType, DomUtils.getInnerXml(node),
                        portfolioModelId, sharedNodeResParent, sharedResParent, userId);
            } else if (!xsiType.equals("context") && !xsiType.equals("nodeRes") && sharedResParent == 1) {

                sharedResUuid = originUuid;
                insertMysqlResource(sharedResUuid, parentUuid, xsiType, DomUtils.getInnerXml(node),
                        portfolioModelId, sharedNodeResParent, sharedResParent, userId);
            } else {
                insertMysqlResource(uuid, parentUuid, xsiType, DomUtils.getInnerXml(node), portfolioModelId,
                        sharedNodeResParent, sharedResParent, userId);
            }
        } else
            insertMysqlResource(uuid, parentUuid, xsiType, DomUtils.getInnerXml(node), portfolioModelId,
                    sharedNodeResParent, sharedResParent, userId);

    }

    // On vrifie enfin si on a import des ressources fichiers dont l'UID correspond
    // pour remplacer l'UID d'origine par l'UID gener
    /*
    if(portfolioRessourcesImportUuid.size()>0)
    {
       for(int k=0;k<portfolioRessourcesImportUuid.size();k++)
       {
    if(portfolioRessourcesImportUuid.get(k).equals(originUuid))
    {
       String portfolioRessourcesDestPath = portfolioRessourcesImportPath.get(k).replace(originUuid, uuid);
       File f = new File(portfolioRessourcesImportPath.get(k));
       f.renameTo(new File(portfolioRessourcesDestPath));
       //System.out.println();
       updateMysqlFileUuid(originUuid,uuid);
    }
            
       }
    }
    //*/

    // On reparcourt ensuite les enfants pour continuer la recursivit
    //      if(children!=null && sharedNode!=1)
    if (children != null) {
        int k = 0;
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            String childId = null;
            if (!rewriteId)
                childId = UUID.randomUUID().toString();

            if (child.getAttributes() != null) {
                String nodeName = child.getNodeName();
                if ("asmRoot".equals(nodeName) || "asmStructure".equals(nodeName) || "asmUnit".equals(nodeName)
                        || "asmUnitStructure".equals(nodeName) || "asmUnitContent".equals(nodeName)
                        || "asmContext".equals(nodeName)) {
                    //System.out.println("uid="+uuid+":"+",enfant_uuid="+children.item(i).getAttributes().getNamedItem("id")+",ordre="+k);
                    writeNode(child, portfolioUuid, portfolioModelId, userId, k, childId, uuid, sharedRes,
                            sharedNodeRes, rewriteId, resolve);
                    k++;
                } else if ("asmResource".equals(nodeName)) // Les asmResource pose problme dans l'ordre des noeuds
                {
                    writeNode(child, portfolioUuid, portfolioModelId, userId, k, childId, uuid, sharedRes,
                            sharedNodeRes, rewriteId, resolve);
                }
            }
        }
    }

    updateMysqlNodeChildren(forcedUuidParent);

    return uuid;
}

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;//w ww. j  a  v  a 2 s . c o  m
    String createdUuid = "erreur";

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

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

        //         t1 = System.currentTimeMillis();

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

        //         t2 = System.currentTimeMillis();

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

        //         t3 = System.currentTimeMillis();

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

        //         t4 = System.currentTimeMillis();

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

        //         t5 = System.currentTimeMillis();

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

        //         t6 = System.currentTimeMillis();

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

        //         t7 = System.currentTimeMillis();

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

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

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

        //         t8 = System.currentTimeMillis();

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

        //         t9 = System.currentTimeMillis();

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

        //         t10 = System.currentTimeMillis();

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

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

        //         t11 = System.currentTimeMillis();

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

        //         t12 = System.currentTimeMillis();

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

        //         t13 = System.currentTimeMillis();

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

        //         t14 = System.currentTimeMillis();

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

        //         t15 = System.currentTimeMillis();

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

        //         t16 = System.currentTimeMillis();

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

        //         t17 = System.currentTimeMillis();

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

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

        //         t18 = System.currentTimeMillis();

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

        //         t19 = System.currentTimeMillis();

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

        //         t20 = System.currentTimeMillis();

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

        //         t21 = System.currentTimeMillis();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        //         end = System.currentTimeMillis();

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

            touchPortfolio(destUuid, null);

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

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

    return createdUuid;
}

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

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

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

        if (portfolioUuid == null)
            return "";

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

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

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

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

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

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

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

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

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

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

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

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

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

        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        resolver resolve = new resolver();

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

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

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

            groupright role = resolve.getUuid(uuid);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        connection.setAutoCommit(false);

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

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

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

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

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

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

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

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

                st.execute();
            }
        }

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

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

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

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

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

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

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

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

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

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

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

    return newPortfolioUuid;
}

From source file:com.globalsight.webservices.Ambassador.java

/**
 * Remote leveraging./*w  w w.  ja v  a  2s . c o  m*/
 * 
 * @param p_accessToken
 *            Access token.
 * @param p_remoteTmProfileId
 *            Tm profile id on remote server
 * @param p_segmentMap
 *            (OriginalTuvId:Segment) map
 * @param p_sourceLocaleId
 *            Source locale Id
 * @param p_btrgLocal2LevLocalesMap
 *            (Target locale Id:leverage locales Ids with comma seperated)
 *            map
 * @param p_translatable
 *            True:translatable segments;False:localizable segments
 * @param p_escapeString
 *            If escape string.
 * @return leveraged results in map.
 * 
 * @throws WebServiceException
 */
public HashMap searchEntriesInBatch(String p_accessToken, Long p_remoteTmProfileId, Map p_segmentMap,
        Long p_sourceLocaleId, Map p_btrgLocal2LevLocalesMap, Boolean p_translatable, Boolean p_escapeString)
        throws WebServiceException {
    checkAccess(p_accessToken, "searchEntriesInBatch");
    // checkPermission(p_accessToken, Permission.SERVICE_TM_SEARCH_ENTRY);

    HashMap originalTuvId2MatchesMap = new HashMap();
    Session session = null;
    try {
        session = HibernateUtil.getSession();

        Leverager leverager = new Leverager(session);
        LocaleManager localeManager = ServerProxy.getLocaleManager();
        ProjectHandler projectHandler = ServerProxy.getProjectHandler();

        // source locale
        GlobalSightLocale sourceLocale = null;
        sourceLocale = localeManager.getLocaleById(p_sourceLocaleId);

        // target locales and leverage locales
        ArrayList trgLocales = new ArrayList();
        LeveragingLocales levLocales = new LeveragingLocales();
        if (p_btrgLocal2LevLocalesMap != null && p_btrgLocal2LevLocalesMap.size() > 0) {
            Iterator iter = p_btrgLocal2LevLocalesMap.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                long trgLocaleId = ((Long) entry.getKey()).longValue();
                GlobalSightLocale trgLocale = localeManager.getLocaleById(trgLocaleId);
                trgLocales.add(trgLocale);

                String levLocaleIds = (String) entry.getValue();
                StringTokenizer st = new StringTokenizer(levLocaleIds, ",");
                while (st.hasMoreElements()) {
                    long levLocaleId = Long.parseLong((String) st.nextElement());
                    GlobalSightLocale levLocale = localeManager.getLocaleById(levLocaleId);
                    Set leveragingLocales = null;
                    try {
                        leveragingLocales = levLocales.getLeveragingLocales(levLocale);
                    } catch (Exception e) {
                    }
                    levLocales.setLeveragingLocale(levLocale, leveragingLocales);
                }
            }
        }

        // tm profile
        TranslationMemoryProfile tmp = TMProfileHandlerHelper.getTMProfileById(p_remoteTmProfileId);
        if (tmp == null) {
            String message = "Unable to get translation memory profile by id:" + p_remoteTmProfileId;
            logger.error(message);
            throw new WebServiceException(message);
        }

        ProjectTM ptm = ServerProxy.getProjectHandler().getProjectTMById(tmp.getProjectTmIdForSave(), false);
        // tmIdsOverride
        Set tmIdsOverride = new HashSet();
        Vector<LeverageProjectTM> tms = tmp.getProjectTMsToLeverageFrom();
        for (LeverageProjectTM tm : tms) {
            ProjectTM projectTm = (ProjectTM) projectHandler.getProjectTMById(tm.getProjectTmId(), false);
            if (projectTm.getIsRemoteTm() == false) {
                tmIdsOverride.add(tm.getProjectTmId());
            }
        }

        // levOptions & leverageDataCenter
        OverridableLeverageOptions levOptions = new OverridableLeverageOptions(tmp, levLocales);
        int threshold = (int) tmp.getFuzzyMatchThreshold();
        levOptions.setMatchThreshold(threshold);
        levOptions.setTmsToLeverageFrom(tmIdsOverride);
        boolean isTmProcedence = tmp.isTmProcendence();

        // find the source tuvs
        List<PageTmTuv> sourceTuvs = new ArrayList<PageTmTuv>();
        Iterator segmentsIter = p_segmentMap.entrySet().iterator();
        while (segmentsIter.hasNext()) {
            Map.Entry entry = (Map.Entry) segmentsIter.next();
            long srcTuvId = ((Long) entry.getKey()).longValue();
            String segment = (String) entry.getValue();
            segment = wrapSegment(segment, p_escapeString.booleanValue());
            PageTmTu tu = new PageTmTu(-1, -1, "plaintext", "text", p_translatable);
            PageTmTuv tuv = new PageTmTuv(srcTuvId, segment, sourceLocale);
            tuv.setTu(tu);
            tuv.setExactMatchKey();
            tu.addTuv(tuv);
            sourceTuvs.add(tuv);
        }

        // Leverage
        LeverageDataCenter leverageDataCenter = null;
        try {
            leverageDataCenter = LingServerProxy.getTmCoreManager().leverageSegments(sourceTuvs, sourceLocale,
                    trgLocales, levOptions);
        } catch (Exception e) {
            logger.error("Failed to leverage segments.", e);
        }

        Iterator itLeverageMatches = leverageDataCenter.leverageResultIterator();
        while (itLeverageMatches.hasNext()) {
            // one "LeverageMatches" represents one segment matches
            LeverageMatches levMatches = (LeverageMatches) itLeverageMatches.next();
            long originalTuvId = levMatches.getOriginalTuv().getId();
            HashMap trgLocaleMatchesMap = new HashMap();

            long jobId = -1; // -1 is fine here
            Iterator itLocales = levMatches.targetLocaleIterator(jobId);
            while (itLocales.hasNext()) {
                GlobalSightLocale targetLocale = (GlobalSightLocale) itLocales.next();
                Vector matchedTuvMapForSpecifiedTrgLocale = new Vector();

                HashMap innerMap = new HashMap();
                Iterator itMatch = levMatches.matchIterator(targetLocale, jobId);
                while (itMatch.hasNext()) {
                    LeveragedTuv matchedTuv = (LeveragedTuv) itMatch.next();

                    HashMap matchInfoMap = new HashMap();
                    String subId = ((SegmentTmTu) levMatches.getOriginalTuv().getTu()).getSubId();
                    matchInfoMap.put("subId", subId);
                    String matchedSegment = matchedTuv.getSegmentNoTopTag();
                    matchedSegment = matchedTuv.getSegment();
                    matchInfoMap.put("matchedSegment", matchedSegment);
                    String matchType = matchedTuv.getMatchState().getName();
                    matchInfoMap.put("matchType", matchType);
                    int orderNum = matchedTuv.getOrder();
                    matchInfoMap.put("orderNum", orderNum);
                    float score = matchedTuv.getScore();
                    matchInfoMap.put("score", score);
                    // source string from TM
                    ProjectTmTuvT tmTuv = HibernateUtil.get(ProjectTmTuvT.class, matchedTuv.getId());
                    String tmSource = "";
                    if (tmTuv != null) {
                        try {
                            tmSource = tmTuv.getTu().getSourceTuv().getSegmentString();
                        } catch (Exception ex) {
                        }
                    }
                    matchInfoMap.put("tmSourceStr", tmSource);
                    int matchedTableType = LeverageMatchLingManagerLocal.getMatchTableType(matchedTuv);
                    matchInfoMap.put("matchedTableType", matchedTableType);

                    matchedTuvMapForSpecifiedTrgLocale.add(matchInfoMap);
                }
                innerMap.put(targetLocale.getId(), matchedTuvMapForSpecifiedTrgLocale);

                trgLocaleMatchesMap.putAll(innerMap);
            }

            originalTuvId2MatchesMap.put(originalTuvId, trgLocaleMatchesMap);
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new WebServiceException(e.getMessage());
    } finally {
        try {
            if (session != null) {
                session.close();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new WebServiceException(e.getMessage());
        }
    }

    return originalTuvId2MatchesMap;
}