Example usage for java.util UUID UUID

List of usage examples for java.util UUID UUID

Introduction

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

Prototype

public UUID(long mostSigBits, long leastSigBits) 

Source Link

Document

Constructs a new UUID using the specified data.

Usage

From source file:ca.nrc.cadc.vos.server.NodeDAO.java

private void getOwners(Node node, boolean resolve) {
    if (node == null || node.appData == null)
        return;/* w  ww.jav a2 s  .  c  o  m*/

    NodeID nid = (NodeID) node.appData;
    if (nid.owner != null)
        return; // already loaded (parent loop below)

    String ownerPropertyString = null;
    Subject s;
    if (resolve) {
        s = identityCache.get(nid.ownerObject);

        if (s == null) {
            log.debug("lookup subject for owner=" + nid.ownerObject);
            s = identManager.toSubject(nid.ownerObject);
            prof.checkpoint("IdentityManager.toSubject");
            identityCache.put(nid.ownerObject, s);
        } else {
            log.debug("found cached subject for owner=" + nid.ownerObject);
        }

        ownerPropertyString = identManager.toOwnerString(s);
    } else {
        log.debug("creating numeric principal only subject.");
        s = new Subject();
        if (nid.ownerObject != null) {
            Integer ownerInt = (Integer) nid.ownerObject;
            UUID numericID = new UUID(0L, (long) ownerInt);
            s.getPrincipals().add(new NumericPrincipal(numericID));
            ownerPropertyString = ownerInt.toString();
        }
    }

    nid.owner = s;
    if (ownerPropertyString != null)
        node.getProperties().add(new NodeProperty(VOS.PROPERTY_URI_CREATOR, ownerPropertyString));

    Node parent = node.getParent();
    while (parent != null) {
        getOwners(parent, resolve);
        parent = parent.getParent();
    }
}

From source file:org.apache.jackrabbit.oak.plugins.segment.file.TarReader.java

private static Map<UUID, List<UUID>> parseGraph(ByteBuffer graphByteBuffer) {
    int count = graphByteBuffer.getInt(graphByteBuffer.limit() - 12);

    ByteBuffer buffer = graphByteBuffer.duplicate();
    buffer.limit(graphByteBuffer.limit() - 16);

    List<UUID> uuids = newArrayListWithCapacity(count);
    for (int i = 0; i < count; i++) {
        uuids.add(new UUID(buffer.getLong(), buffer.getLong()));
    }//ww  w  .  j a  v a  2s  . co  m

    Map<UUID, List<UUID>> graph = newHashMap();
    while (buffer.hasRemaining()) {
        UUID uuid = uuids.get(buffer.getInt());
        List<UUID> list = newArrayList();
        int refid = buffer.getInt();
        while (refid != -1) {
            list.add(uuids.get(refid));
            refid = buffer.getInt();
        }
        graph.put(uuid, list);
    }
    return graph;
}

From source file:com.krawler.esp.servlets.deskeramob.java

/** 
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 * @param request servlet request/*from   w w w .  j  av  a 2s  .  c o m*/
 * @param response servlet response
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, SessionExpiredException {
    response.setContentType("text/html;charset=UTF-8");
    ResultSet rs = null;
    ResultSet rsForSubQ = null;
    PreparedStatement pstmt = null;
    String result = "";
    Connection conn = null;
    try {
        conn = DbPool.getConnection();
        int action = Integer.parseInt(request.getParameter("action"));
        int mode = Integer.parseInt(request.getParameter("mode"));
        switch (action) {
        case 0: // generate application id
            String u = request.getParameter("u");
            String p = request.getParameter("p");
            String d = request.getParameter("d");
            String udid = request.getParameter("udid");
            result = generateAppID(conn, u, p, d, udid);
            break;

        case 1: // dashboard request
            int limit = 15, offset = 0;
            String userid = getUserid(conn, request.getParameter("applicationid").toString());
            String projectlist = DashboardHandler.getProjectList(conn, userid, 1000, 0, "");
            JSONArray projList = null;
            try {
                JSONObject projListObj = new JSONObject(projectlist);
                projList = projListObj.getJSONArray("data");
            } catch (JSONException ex) {
                result = "{\"data\":[{\"success\":false,\"data\":" + ex.getMessage() + "}]}";
            }
            switch (mode) {
            case 1: // due tasks
                try {
                    PreparedStatement pstmt1 = null;
                    JSONObject jobj = new JSONObject();
                    String query = "Select count(post_id) AS count from mailmessages inner join users "
                            + "on users.userid = mailmessages.poster_id where folder = ? and to_id = ? and readflag = false ORDER BY post_time";
                    pstmt1 = conn.prepareStatement(query);
                    pstmt1.setString(1, "0");
                    pstmt1.setString(2, userid);
                    ResultSet rs1 = pstmt1.executeQuery();
                    int count = 0;
                    if (rs1.next()) {
                        count = rs1.getInt("count");
                    }
                    if (projList == null) {
                        result = "{\"success\":[{\"result\": true}],\"msgcount\":[{\"count\":\""
                                + Integer.toString(count) + "\"}],\"data\":[]}";
                    } else {
                        for (int i = 0; i < projList.length(); i++) {
                            JSONObject temp = projList.getJSONObject(i);
                            String projid = temp.getString("id");
                            String qry = "";
                            String projName = "";
                            boolean moderator = DashboardHandler.isModerator(conn, userid, projid);
                            if (!moderator) {
                                qry = "(SELECT taskid FROM proj_task WHERE projectid=? AND taskid NOT IN "
                                        + "(SELECT taskid FROM proj_taskresourcemapping)) " + "UNION "
                                        + "(SELECT taskid FROM proj_taskresourcemapping WHERE resourceid = ? "
                                        + "AND taskid IN (SELECT taskid FROM proj_task WHERE projectid = ?))";
                                pstmt1 = conn.prepareStatement(qry);
                                pstmt1.setString(1, projid);
                                pstmt1.setString(2, userid);
                                pstmt1.setString(3, projid);
                            } else {
                                qry = "SELECT taskid FROM proj_task WHERE projectid = ?";
                                pstmt1 = conn.prepareStatement(qry);
                                pstmt1.setString(1, projid);
                            }
                            rs1 = pstmt1.executeQuery();
                            String tids = "";
                            while (rs1.next()) {
                                tids += "'" + rs1.getString("taskid") + "',";
                            }
                            if (tids.length() > 0) {
                                tids = tids.substring(0, (tids.length() - 1));
                                pstmt1 = conn.prepareStatement(
                                        "SELECT projectname FROM project WHERE projectid = ?");
                                pstmt1.setString(1, projid);
                                rs1 = pstmt1.executeQuery();
                                if (rs1.next()) {
                                    projName = rs1.getString("projectname");
                                }
                                qry = "SELECT priority,taskname,percentcomplete,DATE_FORMAT(startdate,'%D %b %y') AS startdate,DATE_FORMAT(enddate,'%D %b %y') AS enddate, taskid "
                                        + "FROM proj_task " + "WHERE percentcomplete < 100 AND taskid IN ("
                                        + tids
                                        + ") AND (date(enddate)>=date(now())) AND (date(startdate) <= date(now()))";
                                //                                            pstmt.setInt(1, limit);
                                pstmt1 = conn.prepareStatement(qry);
                                rs1 = pstmt1.executeQuery();
                                while (rs1.next()) {
                                    JSONObject j = new JSONObject();
                                    j.put("projectname", projName);
                                    j.put("taskname", rs1.getString("taskname"));
                                    j.put("taskid", rs1.getString("taskid"));
                                    j.put("complete", rs1.getString("percentcomplete"));
                                    j.put("startdate", rs1.getString("startdate"));
                                    j.put("enddate", rs1.getString("enddate"));
                                    int ptr = rs1.getInt("priority");
                                    String pStr = "medium";
                                    if (ptr == 0) {
                                        pStr = "low";
                                    } else if (ptr == 2) {
                                        pStr = "high";
                                    }
                                    j.put("priority", pStr);
                                    if (moderator) {
                                        String res = DashboardHandler.getTaskResources(conn,
                                                rs1.getString("taskid"), projid, userid);
                                        if (!StringUtil.equal(res, "{}")) {
                                            JSONObject jobj1 = new JSONObject(res);
                                            JSONArray jarr = jobj1.getJSONArray("data");
                                            String resr = "";
                                            for (int cnt = 0; cnt < jarr.length(); cnt++) {
                                                resr += jarr.getJSONObject(cnt).getString("resourcename")
                                                        + ", ";
                                            }
                                            resr = resr.substring(0, (resr.length() - 2));
                                            if (!StringUtil.isNullOrEmpty(resr)) {
                                                j.put("assignedto", resr);
                                            }
                                        }
                                    }
                                    jobj.append("data", j);
                                }
                            }
                        }
                    }
                    if (jobj.has("data")) {
                        JSONObject fin = new JSONObject();
                        fin.put("count", String.valueOf(count));
                        jobj.append("msgcount", fin);
                        result = jobj.toString();
                    } else {
                        result = "{\"success\":[{\"result\": true}],\"msgcount\":[{\"count\":\""
                                + Integer.toString(count) + "\"}],\"data\":[]}";
                    }
                } catch (JSONException ex) {
                }
                break;
            case 0: // overdue tasks
                try {
                    JSONObject jobj = new JSONObject();
                    PreparedStatement pstmt1 = null;
                    String query = "Select count(post_id) AS count from mailmessages inner join users "
                            + "on users.userid = mailmessages.poster_id where folder = ? and to_id = ? and readflag = false ORDER BY post_time";
                    pstmt1 = conn.prepareStatement(query);
                    pstmt1.setString(1, "0");
                    pstmt1.setString(2, userid);
                    ResultSet rs1 = pstmt1.executeQuery();
                    int count = 0;
                    if (rs1.next()) {
                        count = rs1.getInt("count");
                    }
                    if (projList == null) {
                        result = "{\"success\":[{\"result\": true}],\"msgcount\":[{\"count\":\""
                                + Integer.toString(count) + "\"}],\"data\":[]}";
                    } else {
                        for (int i = 0; i < projList.length(); i++) {
                            JSONObject temp = projList.getJSONObject(i);
                            String projid = temp.getString("id");
                            String qry = "";
                            String projName = "";
                            boolean moderator = DashboardHandler.isModerator(conn, userid, projid);
                            if (!moderator) {
                                qry = "(SELECT taskid FROM proj_task WHERE projectid=? AND taskid NOT IN "
                                        + "(SELECT taskid FROM proj_taskresourcemapping)) " + "UNION "
                                        + "(SELECT taskid FROM proj_taskresourcemapping WHERE resourceid = ?)";
                                pstmt1 = conn.prepareStatement(qry);
                                pstmt1.setString(1, projid);
                                pstmt1.setString(2, userid);
                            } else {
                                qry = "SELECT taskid FROM proj_task WHERE projectid = ?";
                                pstmt1 = conn.prepareStatement(qry);
                                pstmt1.setString(1, projid);
                            }
                            rs1 = pstmt1.executeQuery();
                            String tids = "";
                            while (rs1.next()) {
                                tids += "'" + rs1.getString("taskid") + "',";
                            }
                            if (tids.length() > 0) {
                                tids = tids.substring(0, (tids.length() - 1));
                                pstmt1 = conn.prepareStatement(
                                        "SELECT projectname FROM project WHERE projectid = ?");
                                pstmt1.setString(1, projid);
                                rs1 = pstmt1.executeQuery();
                                if (rs1.next()) {
                                    projName = rs1.getString("projectname");
                                }
                                qry = "SELECT priority,taskname,percentcomplete, datediff(CURRENT_DATE,date(enddate)) as overdueby,DATE_FORMAT(enddate,'%D %b %y') AS enddate, taskid "
                                        + "FROM proj_task " + "WHERE percentcomplete < 100 AND taskid IN ("
                                        + tids + ") AND date(proj_task.enddate) < date(now()) LIMIT ? OFFSET ?";
                                pstmt1 = conn.prepareStatement(qry);
                                pstmt1.setInt(1, limit);
                                pstmt1.setInt(2, offset);
                                rs1 = pstmt1.executeQuery();
                                while (rs1.next()) {
                                    JSONObject j = new JSONObject();
                                    j.put("projectname", projName);
                                    j.put("taskid", rs1.getString("taskid"));
                                    j.put("taskname", rs1.getString("taskname"));
                                    j.put("complete", rs1.getString("percentcomplete"));
                                    j.put("overdueby", rs1.getString("overdueby"));
                                    j.put("enddate", rs1.getString("enddate"));
                                    int ptr = rs1.getInt("priority");
                                    String pStr = "medium";
                                    if (ptr == 0) {
                                        pStr = "low";
                                    } else if (ptr == 2) {
                                        pStr = "high";
                                    }
                                    j.put("priority", pStr);
                                    if (moderator) {
                                        String res = DashboardHandler.getTaskResources(conn,
                                                rs1.getString("taskid"), projid, userid);
                                        if (!StringUtil.equal(res, "{}")) {
                                            JSONObject jobj1 = new JSONObject(res);
                                            JSONArray jarr = jobj1.getJSONArray("data");
                                            String resr = "";
                                            for (int cnt = 0; cnt < jarr.length(); cnt++) {
                                                resr += jarr.getJSONObject(cnt).getString("resourcename")
                                                        + ", ";
                                            }
                                            resr = resr.substring(0, (resr.length() - 2));
                                            if (!StringUtil.isNullOrEmpty(resr)) {
                                                j.put("assignedto", resr);
                                            }
                                        }
                                    }
                                    jobj.append("data", j);
                                }
                            }
                        }
                    }
                    if (jobj.has("data")) {
                        JSONObject fin = new JSONObject();
                        fin.put("count", count);
                        jobj.append("msgcount", fin);
                        result = jobj.toString();
                    } else {
                        result = "{\"success\":[{\"result\": true}],\"msgcount\":[{\"count\":\""
                                + Integer.toString(count) + "\"}],\"data\":[]}";
                    }
                } catch (JSONException ex) {
                }
                break;
            case 2: // calendar events
                PreparedStatement pstmt1 = null;
                String query = "Select count(post_id) AS count from mailmessages inner join users "
                        + "on users.userid = mailmessages.poster_id where folder = ? and to_id = ? and readflag = false ORDER BY post_time";
                pstmt1 = conn.prepareStatement(query);
                pstmt1.setString(1, "0");
                pstmt1.setString(2, userid);
                ResultSet rs1 = pstmt1.executeQuery();
                int count = 0;
                if (rs1.next()) {
                    count = rs1.getInt("count");
                }
                String sqlquery = "SELECT calendarevents.subject,project.projectname, DATE_FORMAT(calendarevents.startts,'%D %b %y') AS 'startdate' ,"
                        + "DATE_FORMAT(calendarevents.startts,'%h:%i %p') AS 'starttime',"
                        + "CASE calendarevents.priority WHEN 'm' THEN 'Medium' WHEN 'l' THEN 'Low' WHEN 'h' THEN 'High' END AS priority"
                        + " FROM calendarevents INNER JOIN calendars ON calendars.cid =calendarevents.cid INNER JOIN project ON project.projectid = calendars.userid "
                        + " WHERE project.projectid IN (SELECT project.projectid FROM project INNER JOIN projectmembers ON "
                        + " projectmembers.projectid = project.projectid WHERE userid = ?) AND calendars.timestamp> ? "
                        + " AND date(startts)>=CURRENT_DATE AND date(startts)<=(ADDDATE(CURRENT_DATE, 7)) ORDER BY startts LIMIT ? OFFSET ?";
                pstmt = conn.prepareStatement(sqlquery);
                pstmt.setString(1, userid);
                pstmt.setString(2, "1970-01-01 00:00:00");
                pstmt.setInt(3, limit);
                pstmt.setInt(4, offset);
                rsForSubQ = pstmt.executeQuery();
                try {
                    JSONObject jobj = new JSONObject();
                    while (rsForSubQ.next()) {
                        JSONObject j = new JSONObject();
                        j.put("subject", rsForSubQ.getString("subject"));
                        j.put("projectname", rsForSubQ.getString("projectname"));
                        j.put("startdate", rsForSubQ.getString("startdate"));
                        j.put("starttime", rsForSubQ.getString("starttime"));
                        j.put("priority", rsForSubQ.getString("priority"));
                        jobj.append("data", j);
                    }
                    if (jobj.has("data")) {
                        JSONObject fin = new JSONObject();
                        fin.put("count", String.valueOf(count));
                        jobj.append("msgcount", fin);
                        result = jobj.toString();
                    } else {
                        result = "{\"success\":true,\"data\":[]}";
                    }
                } catch (JSONException ex) {
                    result = "{\"success\":false,\"data\":" + ex.getMessage() + "}";
                }
                //result = kwljson.GetJsonForGrid(rsForSubQ);
                break;
            case 3: // unread personal msgs
                query = "Select count(post_id) AS count from mailmessages inner join users "
                        + "on users.userid = mailmessages.poster_id where folder = ? and to_id = ? and readflag = false ORDER BY post_time";
                pstmt = conn.prepareStatement(query);
                pstmt.setString(1, "0");
                pstmt.setString(2, userid);
                rsForSubQ = pstmt.executeQuery();
                count = 0;
                if (rsForSubQ.next()) {
                    count = rsForSubQ.getInt("count");
                }
                query = "Select post_id ,concat(fname,' ',lname) as post_fullname,userlogin.username as poster_id , post_text , post_subject ,"
                        + " DATE_FORMAT(post_time,'%D %b %y %h:%i%p') as post_time from mailmessages inner join users "
                        + "on users.userid = mailmessages.poster_id inner join userlogin on users.userid =userlogin.userid where folder = ? and to_id = ? and readflag = false ORDER BY post_time DESC";
                pstmt = conn.prepareStatement(query);
                pstmt.setString(1, "0");
                pstmt.setString(2, userid);
                //            pstmt.setInt(3, limit);
                //            pstmt.setInt(4, offset);
                rsForSubQ = pstmt.executeQuery();
                //result = kwljson.GetJsonForGrid(rsForSubQ);
                try {
                    JSONObject jobj = new JSONObject();
                    String companyid = getCompanyID(conn, userid);
                    String subdomain = CompanyHandler.getCompanySubdomainByCompanyID(conn, companyid);
                    while (rsForSubQ.next()) {
                        JSONObject j = new JSONObject();
                        j.put("post_id", rsForSubQ.getString("post_id"));
                        j.put("post_fullname", rsForSubQ.getString("post_fullname"));
                        j.put("poster_id", rsForSubQ.getString("poster_id"));
                        j.put("post_text",
                                insertSmiley(rsForSubQ.getString("post_text"), URLUtil.getPageURL(request,
                                        com.krawler.esp.web.resource.Links.loginpageFull, subdomain)));
                        j.put("post_subject", rsForSubQ.getString("post_subject"));
                        j.put("post_time", rsForSubQ.getString("post_time"));
                        jobj.append("data", j);
                    }
                    if (jobj.has("data")) {
                        JSONObject temp = new JSONObject();
                        temp.put("count", String.valueOf(count));
                        jobj.append("msgcount", temp);
                        result = jobj.toString();
                    } else {
                        result = "{\"success\":true,\"data\":[]}";
                    }
                } catch (JSONException ex) {
                    result = "{\"success\":false,\"data\":" + ex.getMessage() + "}";
                }
                break;
            case 4: // list of users's projects
                String companyid = getCompanyID(conn, userid);
                boolean isSuperUser = DashboardHandler.isSuperUser(conn, companyid, userid);
                try {
                    JSONObject projectList = new JSONObject(
                            DashboardHandler.getProjectListMember(conn, userid, 10, 0));
                    JSONArray projArray = projectList.getJSONArray("data");
                    int prc = projArray.length();
                    JSONObject jobj = new JSONObject();
                    if (prc > 0) {
                        for (int i = 0; i < projArray.length(); i++) {
                            JSONObject j = new JSONObject();
                            j.put("name", projArray.getJSONObject(i).getString("name"));
                            j.put("id", projArray.getJSONObject(i).getString("id"));
                            jobj.append("data", j);
                        }
                    }
                    if (jobj.has("data")) {
                        result = jobj.toString();
                    } else {
                        result = "{\"success\":true,\"data\":[]}";
                    }
                } catch (JSONException ex) {
                    result = "{\"success\":false,\"data\":" + ex.getMessage() + "}";
                }
                break;
            case 5: // list of project resources
                String responseText = projdb.getProjectResources(conn, request.getParameter("id"));
                try {
                    JSONObject jobj = new JSONObject();
                    if (responseText.compareTo("{data:{}}") != 0) {
                        JSONObject resJOBJ = new JSONObject(responseText);
                        JSONArray jArray = resJOBJ.getJSONArray("data");
                        int prec = jArray.length();
                        if (prec > 0) {
                            for (int i = 0; i < prec; i++) {
                                JSONObject j = new JSONObject();
                                j.put("name", jArray.getJSONObject(i).getString("resourcename"));
                                j.put("id", jArray.getJSONObject(i).getString("resourceid"));
                                jobj.append("data", j);
                            }
                        }
                    }
                    if (jobj.has("data")) {
                        result = jobj.toString();
                    } else {
                        result = "{\"success\":true,\"data\":[]}";
                    }
                } catch (JSONException ex) {
                    result = "{\"success\":false,\"data\":" + ex.getMessage() + "}";
                }
                break;
            case 6:// display project list
                companyid = getCompanyID(conn, userid);
                result = AdminServlet.getProjData(conn, request, companyid, "");
                break;
            case 7:// fetch assigned/unassigned members
                result = getAssiUnAssiProjctMembers(conn, request.getParameter("projectid"));
                break;
            case 8:// isSuperUser
                companyid = getCompanyID(conn, userid);
                boolean isSuper = DashboardHandler.isSuperUser(conn, companyid, userid);
                JSONObject temp = new JSONObject();
                JSONObject jobj = new JSONObject();
                temp.put("superuser", isSuper);
                jobj.append("data", temp);
                result = jobj.toString();
                break;
            case 9:// manage members
                String userids = request.getParameter("userid");
                if (StringUtil.isNullOrEmpty(userids)) {
                    result = "{\"result\":[{\"success\":false}], \"msg\":[{\"msgText\": \"Can not remove all project members.\"}]}";
                } else {
                    userids = userids.substring(0, (userids.length() - 1));
                    String[] uids = userids.split(",");
                    String pid = request.getParameter("projectid");
                    result = manageMembers(conn, pid, uids);
                }
                break;
            case 10: // company user list
                companyid = getCompanyID(conn, userid);
                String companyMembers = AdminServlet.getAdminUserData(conn, request, companyid, "", false);
                //                            result = "{\"result\":[{\"success\":false}], \"msg\":[{\"msgText\": \"Could not complete your request.\"}]}";
                result = "{\"result\":[{\"success\":true}],\"data\":" + companyMembers + "}";
                break;
            }
            break;

        case 2: // Update Records
            userid = getUserid(conn, request.getParameter("applicationid").toString());
            switch (mode) {
            case 1:// set read flag
                String post_id = request.getParameter("post_id");
                String query = "update mailmessages set readflag=true where post_id = ?";
                pstmt = conn.prepareStatement(query);
                pstmt.setString(1, post_id);
                int rows = pstmt.executeUpdate();
                if (rows > 0) {
                    conn.commit();
                    result = "{\"success\":true}";
                } else {
                    result = "{\"success\":false}";
                }
                break;
            case 2:// update percent value for record
                String taskid = request.getParameter("taskid");
                String pcomplete = request.getParameter("complete");
                query = "update proj_task set percentcomplete = ? where taskid = ?";
                pstmt = conn.prepareStatement(query);
                pstmt.setString(1, pcomplete);
                pstmt.setString(2, taskid);
                rows = pstmt.executeUpdate();
                if (rows > 0) {
                    conn.commit();
                    result = "{\"success\":true}";
                } else {
                    result = "{\"success\":false}";
                }
                break;
            case 3:// insert tasks
                try {
                    String projId = request.getParameter("projectid");
                    pstmt = conn.prepareStatement(
                            "select max(taskindex) as maxindex from proj_task where projectid=?");
                    pstmt.setString(1, projId);
                    rs = pstmt.executeQuery();
                    int rowindex = 0;
                    if (rs.next()) {
                        rowindex = rs.getInt(1) + 1;
                    }
                    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy/MM/dd");
                    UUID ud = new UUID(2312, 4123);
                    taskid = ud.randomUUID().toString();
                    String taskname = request.getParameter("name");
                    String stdate = request.getParameter("start");
                    String enddate = request.getParameter("end");
                    int priority = 1;
                    if (!StringUtil.isNullOrEmpty(request.getParameter("priority"))) {
                        priority = Integer.parseInt(request.getParameter("priority"));
                    }
                    String duration = "1";
                    String nonworkdays = projdb.getNonWorkWeekdays(conn, projId);
                    String Holidays = projdb.getCmpHolidaydays(conn, projId);
                    JSONObject nmweekObj = new JSONObject(nonworkdays);
                    int nonworkweekArr[] = new int[nmweekObj.getJSONArray("data").length()];
                    for (int cnt = 0; cnt < nmweekObj.getJSONArray("data").length(); cnt++) {
                        nonworkweekArr[cnt] = Integer
                                .parseInt(nmweekObj.getJSONArray("data").getJSONObject(cnt).getString("day"));
                    }
                    String holidayArr[] = new String[1];
                    holidayArr[0] = "";
                    if (Holidays.compareTo("{data:{}}") != 0) {
                        nmweekObj = new JSONObject(Holidays);
                        holidayArr = new String[nmweekObj.getJSONArray("data").length()];
                        for (int cnt = 0; cnt < nmweekObj.getJSONArray("data").length(); cnt++) {
                            holidayArr[cnt] = nmweekObj.getJSONArray("data").getJSONObject(cnt)
                                    .getString("holiday");
                        }
                    }
                    duration = projectReport.calculateWorkingDays(sdf.parse(stdate), sdf.parse(enddate),
                            nonworkweekArr, holidayArr) + "";
                    pstmt = conn.prepareStatement(
                            "INSERT INTO proj_task(taskid, taskname, duration, startdate, enddate, projectid, "
                                    + "taskindex, level, parent, actualstartdate, actualduration, percentcomplete, notes, priority, "
                                    + "isparent) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                    pstmt.setString(1, taskid);
                    pstmt.setString(2, taskname);
                    pstmt.setString(3, duration);
                    java.util.Date DateVal = sdf.parse(stdate);
                    Timestamp ts = new Timestamp(DateVal.getTime());
                    pstmt.setTimestamp(4, ts);
                    DateVal = sdf.parse(enddate);
                    ts = new Timestamp(DateVal.getTime());
                    pstmt.setTimestamp(5, ts);
                    pstmt.setString(6, projId);
                    pstmt.setString(7, String.valueOf(rowindex));
                    pstmt.setString(8, "0");
                    pstmt.setString(9, "0");
                    DateVal = sdf.parse(stdate);
                    ts = new Timestamp(DateVal.getTime());
                    pstmt.setTimestamp(10, ts);
                    pstmt.setString(11, duration);
                    pstmt.setString(12, "0");
                    pstmt.setString(13, "");
                    pstmt.setInt(14, priority);
                    pstmt.setBoolean(15, false);
                    boolean flag = pstmt.execute();
                    if (!request.getParameter("assignto").equals("")) {
                        String[] resArray = request.getParameter("assignto").split(",");
                        for (int i = 0; i < resArray.length; i++) {
                            int dur = 0;
                            String rid = resArray[i];
                            pstmt = conn.prepareStatement(
                                    "insert into proj_taskresourcemapping (taskid,resourceid,resduration) values(?,?,?)");
                            pstmt.setString(1, taskid);
                            pstmt.setString(2, rid);
                            pstmt.setInt(3, dur);
                            pstmt.execute();
                        }
                    }
                    conn.commit();
                    result = "{\"success\":[{\"result\":true}]}";
                } catch (ParseException ex) {
                    Logger.getLogger(deskeramob.class.getName()).log(Level.SEVERE, null, ex);
                    result = "{\"success\":[{\"result\":false}],\"data\":" + ex.getMessage() + "}";
                } catch (JSONException ex) {
                    result = "{\"success\":[{\"result\":false}],\"data\":" + ex.getMessage() + "}";
                }
                break;
            case 5: // import contacts
                result = importContacts(conn, request);
                break;
            case 6: // export contacts
                result = exportContacts(conn, request);
                if (!StringUtil.isNullOrEmpty(result)) {
                    result = "{\"import\":[{\"result\":true}]," + result.substring(1, (result.length() - 1))
                            + "}";
                } else {
                    result = "{\"import\":[{\"result\":true,\"error\":\"There seem to be some problem with server. Could not import contacts.\"}]}";
                }
                break;
            }
            break;

        case 3: // company updates
            switch (mode) {
            case 2: //create project
                userid = getUserid(conn, request.getParameter("applicationid").toString());
                String subdomain = CompanyHandler.getCompanySubdomainByUser(conn, userid);
                String companyid = getCompanyID(conn, userid);
                result = createProject(conn, request, companyid, subdomain, userid);
                if (StringUtil.equal("success", result)) {
                    result = "{\"success\":[{\"result\":true}]}";
                } else {
                    result = "{\"success\":[{\"result\":false,\"error\":\"" + result + "\"}]}";
                }
                break;

            case 3: //delete project
                userid = getUserid(conn, request.getParameter("applicationid").toString());
                companyid = getCompanyID(conn, userid);
                result = AdminServlet.deleteProject(conn, request, companyid, userid, "iPhone");
                if (StringUtil.equal("failure", result)) {
                    result = "{\"success\":[{\"result\":false}]}";
                    DbPool.quietRollback(conn);
                } else {
                    result = "{\"success\":[{\"result\":true}]}";
                    conn.commit();
                }
                break;
            }
            break;
        }
    } catch (JSONException ex) {
        Logger.getLogger(deskeramob.class.getName()).log(Level.SEVERE, null, ex);
        result = "{\"success\":[{\"result\":\"1\"}],\"data\":" + ex.getMessage() + "}";
    } catch (ServiceException ex) {
        result = "{\"success\":[{\"result\":\"0\"}],\"data\":" + ex.getMessage() + "}";
    } catch (SQLException ex) {
        result = "{\"success\":[{\"result\":\"0\"}],\"data\":" + ex.getMessage() + "}";
    } finally {
        DbPool.quietClose(conn);
        response.getWriter().println(result);
    }
    response.getWriter().close();
}

From source file:org.apache.jackrabbit.oak.segment.file.TarReader.java

private static Map<UUID, List<UUID>> parseGraph(ByteBuffer graphByteBuffer, boolean bulkOnly) {
    int count = graphByteBuffer.getInt(graphByteBuffer.limit() - 12);

    ByteBuffer buffer = graphByteBuffer.duplicate();
    buffer.limit(graphByteBuffer.limit() - 16);

    List<UUID> uuids = newArrayListWithCapacity(count);
    for (int i = 0; i < count; i++) {
        uuids.add(new UUID(buffer.getLong(), buffer.getLong()));
    }/*from w w w.j  a v  a  2  s  . c o m*/

    Map<UUID, List<UUID>> graph = newHashMap();
    while (buffer.hasRemaining()) {
        UUID uuid = uuids.get(buffer.getInt());
        List<UUID> list = newArrayList();
        int refid = buffer.getInt();
        while (refid != -1) {
            UUID ref = uuids.get(refid);
            if (!bulkOnly || !isDataSegmentId(ref.getLeastSignificantBits())) {
                list.add(ref);
            }
            refid = buffer.getInt();
        }
        graph.put(uuid, list);
    }
    return graph;
}

From source file:io.pravega.client.stream.impl.ControllerImplTest.java

@Test
public void testCreateTransaction() throws Exception {
    CompletableFuture<TxnSegments> transaction;
    transaction = controllerClient.createTransaction(new StreamImpl("scope1", "stream1"), 0, 0, 0);
    assertEquals(new UUID(11L, 22L), transaction.get().getTxnId());
    assertEquals(2, transaction.get().getSteamSegments().getSegments().size());
    assertEquals(new Segment("scope1", "stream1", 0),
            transaction.get().getSteamSegments().getSegmentForKey(.2));
    assertEquals(new Segment("scope1", "stream1", 1),
            transaction.get().getSteamSegments().getSegmentForKey(.8));

    transaction = controllerClient.createTransaction(new StreamImpl("scope1", "stream2"), 0, 0, 0);
    assertEquals(new UUID(33L, 44L), transaction.get().getTxnId());
    assertEquals(1, transaction.get().getSteamSegments().getSegments().size());
    assertEquals(new Segment("scope1", "stream2", 0),
            transaction.get().getSteamSegments().getSegmentForKey(.2));
    assertEquals(new Segment("scope1", "stream2", 0),
            transaction.get().getSteamSegments().getSegmentForKey(.8));

    transaction = controllerClient.createTransaction(new StreamImpl("scope1", "stream3"), 0, 0, 0);
    AssertExtensions.assertThrows("Should throw Exception", transaction, throwable -> true);
}

From source file:org.apache.nifi.web.util.SnippetUtils.java

/**
 * Generates a new type 1 id (UUID) for the current id that is specified. If
 * seed is provided, it will be incorporated into generation logic of the
 * new ID./*  w  w w.  ja va2 s. co  m*/
 * The contract of this method is as follows:
 * - The 'currentId' must never be null and it must be String representation
 *   of type-one UUID.
 * - If seed is provided, the new ID will be generated from the 'msb' extracted from
 *   the 'currentId' and the 'lsb' extracted from the UUID generated via
 *   UUID.nameUUIDFromBytes(currentId + seed).
 * - If seed is NOT provided and 'isCopy' flag is set the new ID will be generated from
 *   the 'msb' extracted from the 'currentId' and random integer as 'lsb'. In this case
 *   the new ID will always be > the previous ID essentially resulting in the new ID for
 *   the component that being copied (e.g., copy/paste).
 * - If seed is NOT provided and 'isCopy' flag is NOT set the new ID will be generated from
 *   the 'msb' extracted from the 'currentId' and random integer as 'lsb'.
 */
private String generateId(final String currentId, final String seed, boolean isCopy) {
    long msb = UUID.fromString(currentId).getMostSignificantBits();

    UUID uuid;
    if (StringUtils.isBlank(seed)) {
        long lsb = randomGenerator.nextLong();
        if (isCopy) {
            uuid = ComponentIdGenerator.generateId(msb, lsb, true); // will increment msb if necessary
        } else {
            // since msb is extracted from type-one UUID, the type-one semantics will be preserved
            uuid = new UUID(msb, lsb);
        }
    } else {
        UUID seedId = UUID.nameUUIDFromBytes((currentId + seed).getBytes(StandardCharsets.UTF_8));
        if (isCopy) {
            // will ensure the type-one semantics for new UUID generated from msb extracted from seedId
            uuid = ComponentIdGenerator.generateId(seedId.getMostSignificantBits(),
                    seedId.getLeastSignificantBits(), false);
        } else {
            uuid = new UUID(msb, seedId.getLeastSignificantBits());
        }
    }
    logger.debug("Generating UUID {} from currentId={}, seed={}, isCopy={}", uuid, currentId, seed, isCopy);
    return uuid.toString();
}

From source file:org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl.java

CompletableFuture<ReadHandle> getLedgerHandle(long ledgerId) {
    CompletableFuture<ReadHandle> ledgerHandle = ledgerCache.get(ledgerId);
    if (ledgerHandle != null) {
        return ledgerHandle;
    }//from   w  ww.  j a v  a 2 s. c  o m

    // If not present try again and create if necessary
    return ledgerCache.computeIfAbsent(ledgerId, lid -> {
        // Open the ledger for reading if it was not already opened
        if (log.isDebugEnabled()) {
            log.debug("[{}] Asynchronously opening ledger {} for read", name, ledgerId);
        }
        mbean.startDataLedgerOpenOp();

        CompletableFuture<ReadHandle> promise = new CompletableFuture<>();

        LedgerInfo info = ledgers.get(ledgerId);
        CompletableFuture<ReadHandle> openFuture = new CompletableFuture<>();
        if (info != null && info.hasOffloadContext() && info.getOffloadContext().getComplete()) {
            UUID uid = new UUID(info.getOffloadContext().getUidMsb(), info.getOffloadContext().getUidLsb());
            // TODO: improve this to load ledger offloader by driver name recorded in metadata
            openFuture = config.getLedgerOffloader().readOffloaded(ledgerId, uid,
                    OffloadUtils.getOffloadDriverMetadata(info));
        } else {
            openFuture = bookKeeper.newOpenLedgerOp().withRecovery(!isReadOnly()).withLedgerId(ledgerId)
                    .withDigestType(config.getDigestType()).withPassword(config.getPassword()).execute();
        }
        openFuture.whenCompleteAsync((res, ex) -> {
            mbean.endDataLedgerOpenOp();
            if (ex != null) {
                ledgerCache.remove(ledgerId, promise);
                promise.completeExceptionally(createManagedLedgerException(ex));
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("[{}] Successfully opened ledger {} for reading", name, ledgerId);
                }
                promise.complete(res);
            }
        }, executor.chooseThread(name));
        return promise;
    });
}

From source file:org.agnitas.util.AgnUtils.java

public static UUID convertToUUID(byte[] byteArray) {
    if (byteArray.length != 16) {
        throw new IllegalArgumentException("Length of bytearray doesn't fit for UUID");
    }/*  w ww .java  2  s. c o m*/

    long msb = 0;
    long lsb = 0;
    for (int i = 0; i < 8; i++) {
        msb = (msb << 8) | (byteArray[i] & 0xFF);
    }
    for (int i = 8; i < 16; i++) {
        lsb = (lsb << 8) | (byteArray[i] & 0xFF);
    }
    return new UUID(msb, lsb);
}

From source file:com.lef.ibeacon.service.UpdateService.java

public UUID decodeBeaconUUID(final BluetoothGattCharacteristic characteristic) {
    final byte[] data = characteristic.getValue();
    //      logw("Characteristic get value: " + data.length);            
    final long mostSigBits = (unsignedByteToLong(data[0]) << 56) + (unsignedByteToLong(data[1]) << 48)
            + (unsignedByteToLong(data[2]) << 40) + (unsignedByteToLong(data[3]) << 32)
            + (unsignedByteToLong(data[4]) << 24) + (unsignedByteToLong(data[5]) << 16)
            + (unsignedByteToLong(data[6]) << 8) + unsignedByteToLong(data[7]);
    //      logw("mostSigBits value: " + mostSigBits);
    final long leastSigBits = (unsignedByteToLong(data[8]) << 56) + (unsignedByteToLong(data[9]) << 48)
            + (unsignedByteToLong(data[10]) << 40) + (unsignedByteToLong(data[11]) << 32)
            + (unsignedByteToLong(data[12]) << 24) + (unsignedByteToLong(data[13]) << 16)
            + (unsignedByteToLong(data[14]) << 8) + unsignedByteToLong(data[15]);
    //      logw("leastSigBits value: " + leastSigBits);

    UUID uuid = new UUID(mostSigBits, leastSigBits);
    //      logw("UUID: " + uuid.toString());      
    return uuid;/*from   w  w  w .  j a v  a2s .c om*/
}

From source file:org.jaya.varanus.monitoring.Bytes.java

public static UUID toUUID(byte[] identifierBytes) {
    byte[] leastSignificativeBytes = Bytes.copy(identifierBytes, 0, identifierBytes.length / 2);
    byte[] mostSignificativeBytes = Bytes.copy(identifierBytes, identifierBytes.length / 2,
            identifierBytes.length / 2);
    long leastSignificativeBits = Bytes.toLong(leastSignificativeBytes);
    long mostSignificativeBits = Bytes.toLong(mostSignificativeBytes);
    UUID identifier = new UUID(mostSignificativeBits, leastSignificativeBits);

    return (identifier);
}