Java Code Examples for com.tinkerpop.blueprints.impls.orient.OrientGraph#shutdown()

The following examples show how to use com.tinkerpop.blueprints.impls.orient.OrientGraph#shutdown() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractCommentRule.java    From light with Apache License 2.0 6 votes vote down vote up
protected String getCommentTreeDb(String rid, String sortedBy, String sortDir) {
    String sql = "select from Comment where in_HasComment[0] = " + rid + " ORDER BY " + sortedBy + " " + sortDir;
    String json = null;
    OrientGraph graph = ServiceLocator.getInstance().getGraph();
    try {
        OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<ODocument>(sql);
        List<ODocument> list = graph.getRawGraph().command(query).execute();
        if(list.size() > 0) {
            json = OJSONWriter.listToJSON(list, "rid,fetchPlan:[*]in_HasComment:-2 [*]out_ReportSpam:-2 [*]out_UpVote:-2 [*]out_DownVote:-2 in_Create[]:0 [*]out_Create:-2 [*]out_Update:-2 [*]out_HasComment:-1");
            // need to fixed the in_Create within the json using json path.
            DocumentContext dc = JsonPath.parse(json);
            MapFunction propsFunction = new StripPropsMapFunction();
            dc.map("$..in_UpVote[*]", propsFunction);
            dc.map("$..in_DownVote[*]", propsFunction);
            dc.map("$..in_ReportSpam[*]", propsFunction);

            MapFunction createFunction = new StripInCreateMapFunction();
            json = dc.map("$..in_Create[0]", createFunction).jsonString();
        }
    } catch (Exception e) {
        logger.error("Exception:", e);
    } finally {
        graph.shutdown();
    }
    return json;
}
 
Example 2
Source File: AbstractRuleRule.java    From light with Apache License 2.0 6 votes vote down vote up
protected void updRule(Map<String, Object> data) throws Exception {
    OrientGraph graph = ServiceLocator.getInstance().getGraph();
    try {
        graph.begin();
        Vertex rule = graph.getVertexByKey("Rule.ruleClass", data.get("ruleClass"));
        if(rule != null) {
            String sourceCode = (String)data.get("sourceCode");
            if(sourceCode != null && !sourceCode.equals(rule.getProperty("sourceCode"))) {
                rule.setProperty("sourceCode", sourceCode);
            }
            rule.setProperty("updateDate", data.get("updateDate"));
            Vertex updateUser = graph.getVertexByKey("User.userId", data.get("updateUserId"));
            if(updateUser != null) {
                updateUser.addEdge("Update", rule);
            }
            // there is no need to put updated rule into compileMap.
        }
        graph.commit();
    } catch (Exception e) {
        logger.error("Exception:", e);
        graph.rollback();
        throw e;
    } finally {
        graph.shutdown();
    }
}
 
Example 3
Source File: BranchRule.java    From light with Apache License 2.0 6 votes vote down vote up
protected void upBranchDb(String branchType, Map<String, Object> data) throws Exception {
    String className = branchType.substring(0, 1).toUpperCase() + branchType.substring(1);
    String index = className + ".categoryId";
    OrientGraph graph = ServiceLocator.getInstance().getGraph();
    try{
        graph.begin();
        OrientVertex updateUser = (OrientVertex)graph.getVertexByKey("User.userId", data.remove("updateUserId"));
        OrientVertex branch = (OrientVertex)graph.getVertexByKey(index, data.get("categoryId"));
        if(branch != null && updateUser != null) {
            // remove DownVote edge if there is.
            for (Edge edge : updateUser.getEdges(branch, Direction.OUT, "DownVote")) {
                if(edge.getVertex(Direction.IN).equals(branch)) graph.removeEdge(edge);
            }
            updateUser.addEdge("UpVote", branch);
        }
        graph.commit();
    } catch (Exception e) {
        logger.error("Exception:", e);
        graph.rollback();
    } finally {
        graph.shutdown();
    }
}
 
Example 4
Source File: AbstractDbRule.java    From light with Apache License 2.0 6 votes vote down vote up
protected String exportEvent(String path) {
    final String[] result = new String[1];
    OrientGraph graph = ServiceLocator.getInstance().getGraph();
    try{
        OCommandOutputListener listener = new OCommandOutputListener() {
            @Override
            public void onMessage(String iText) {
                result[0] = result[0] + iText;
            }
        };
        ODatabaseExport export = new ODatabaseExport(graph.getRawGraph(), path, listener);
        export.exportDatabase();
        export.close();
    } catch(IOException ioe) {
        ioe.printStackTrace();
    } finally {
        graph.shutdown();
    }
    return result[0];
}
 
Example 5
Source File: AbstractCatalogRule.java    From light with Apache License 2.0 6 votes vote down vote up
protected String getProductDb() {
    String json = null;
    String sql = "select from product";
    OrientGraph graph = ServiceLocator.getInstance().getGraph();
    try {
        OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<ODocument>(sql);
        List<ODocument> products = graph.getRawGraph().command(query).execute();
        if(products.size() > 0) {
            json = OJSONWriter.listToJSON(products, null);
        }
    } catch (Exception e) {
        logger.error("Exception:", e);
    } finally {
        graph.shutdown();
    }
    return json;
}
 
Example 6
Source File: AbstractCatalogRule.java    From light with Apache License 2.0 6 votes vote down vote up
@Override
protected List<String> getCategoryEntityListDb(String categoryRid, String sortedBy, String sortDir) {
    List<String> entityList = null;
    String sql = "select @rid from (traverse out_Own, out_HasProduct from ?) where @class = 'Product' order by " + sortedBy + " " + sortDir;
    OrientGraph graph = ServiceLocator.getInstance().getGraph();
    try {
        OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<ODocument>(sql);
        List<ODocument> entities = graph.getRawGraph().command(query).execute(categoryRid);
        if(entities.size() > 0) {
            entityList = new ArrayList<String>();
            for(ODocument entity: entities) {
                entityList.add(((ODocument)entity.field("rid")).field("@rid").toString());
            }
        }
    } catch (Exception e) {
        logger.error("Exception:", e);
    } finally {
        graph.shutdown();
    }
    return entityList;
}
 
Example 7
Source File: AbstractRuleRule.java    From light with Apache License 2.0 6 votes vote down vote up
protected void updPublisher(Map<String, Object> data) throws Exception {
    String ruleClass = (String)data.get("ruleClass");
    OrientGraph graph = ServiceLocator.getInstance().getGraph();
    try {
        graph.begin();
        Vertex rule = graph.getVertexByKey("Rule.ruleClass", ruleClass);
        if(rule != null) {
            rule.setProperty("isPublisher", data.get("isPublisher"));
            rule.setProperty("updateDate", data.get("updateDate"));
            Map<String, Object> ruleMap = ServiceLocator.getInstance().getMemoryImage("ruleMap");
            ConcurrentMap<String, Map<String, Object>> cache = (ConcurrentMap<String, Map<String, Object>>)ruleMap.get("cache");
            if(cache != null) {
                cache.remove(ruleClass);
            }
        }
        graph.commit();
    } catch (Exception e) {
        logger.error("Exception:", e);
        graph.rollback();
        throw e;
    } finally {
        graph.shutdown();
    }
}
 
Example 8
Source File: AbstractUserRule.java    From light with Apache License 2.0 5 votes vote down vote up
protected boolean isUserInDbByEmail(String email) {
    boolean userInDb = false;
    OrientGraph graph = ServiceLocator.getInstance().getGraph();
    try {
        Vertex user = graph.getVertexByKey("User.email", email);
        if(user != null) {
            userInDb = true;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        graph.shutdown();
    }
    return userInDb;
}
 
Example 9
Source File: AbstractCommentRule.java    From light with Apache License 2.0 5 votes vote down vote up
protected String getComment(Map<String, Object> data, Map<String, Object> criteria) {
    String json = null;
    StringBuilder sb = new StringBuilder("SELECT FROM (TRAVERSE out_HasComment FROM ").append(data.get("@rid")).append(") ");
    String whereClause = DbService.getWhereClause(criteria);
    if(whereClause != null && whereClause.length() > 0) {
        sb.append(whereClause);
    }
    String sortedBy = (String)criteria.get("sortedBy");
    String sortDir = (String)criteria.get("sortDir");
    if(sortedBy != null) {
        sb.append(" ORDER BY ").append(sortedBy);
        if(sortDir != null) {
            sb.append(" ").append(sortDir);
        }
    }
    Integer pageSize = (Integer)criteria.get("pageSize");
    Integer pageNo = (Integer)criteria.get("pageNo");
    if(pageNo != null && pageSize != null) {
        sb.append(" SKIP ").append((pageNo - 1) * pageSize);
        sb.append(" LIMIT ").append(pageSize);
    }
    //System.out.println("sql=" + sb);
    OrientGraph graph = ServiceLocator.getInstance().getGraph();
    try {
        OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<ODocument>(sb.toString());
        List<ODocument> list = graph.getRawGraph().command(query).execute();
        if(list.size() > 0) {
            json = OJSONWriter.listToJSON(list, null);
        }
    } catch (Exception e) {
        logger.error("Exception:", e);
    } finally {
        graph.shutdown();
    }
    return json;
}
 
Example 10
Source File: AbstractRuleRule.java    From light with Apache License 2.0 5 votes vote down vote up
protected String updateValidation(Map<String, Object> inputMap, Map<String, Object> eventData) {
    Map<String, Object> data = (Map<String, Object>)inputMap.get("data");
    Map<String, Object> user = (Map<String, Object>) inputMap.get("user");
    String rid = (String)data.get("@rid");
    String ruleClass = (String)data.get("ruleClass");
    String error = null;
    String host = (String)user.get("host");
    if(host != null) {
        if(!host.equals(data.get("host"))) {
            error = "You can only update rule for host: " + host;
            inputMap.put("responseCode", 403);
        } else {
            // make sure the ruleClass contains the host.
            if(host != null && !ruleClass.contains(host)) {
                // you are not allowed to update rule as it is not owned by the host.
                error = "ruleClass is not owned by the host: " + host;
                inputMap.put("responseCode", 403);
            }
        }
    }
    if(error == null) {
        OrientGraph graph = ServiceLocator.getInstance().getGraph();
        try {
            Vertex rule = DbService.getVertexByRid(graph, rid);
            if(rule == null) {
                error = "Rule with @rid " + rid + " cannot be found";
                inputMap.put("responseCode", 404);
            } else {
                eventData.put("ruleClass", ruleClass);
                eventData.put("updateUserId", user.get("userId"));
            }
        } catch (Exception e) {
            logger.error("Exception:", e);
            throw e;
        } finally {
            graph.shutdown();
        }
    }
    return error;
}
 
Example 11
Source File: AbstractRuleRule.java    From light with Apache License 2.0 5 votes vote down vote up
protected String getRuleDropdown(String host) {
    String sql = "SELECT FROM Rule";
    if(host != null) {
        sql = sql + " WHERE host = '" + host + "' OR host IS NULL";
    }
    String json = null;
    OrientGraph graph = ServiceLocator.getInstance().getGraph();
    try {
        OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<>(sql);
        List<ODocument> rules = graph.getRawGraph().command(query).execute();
        if(rules.size() > 0) {
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
            for(ODocument doc: rules) {
                Map<String, String> map = new HashMap<String, String>();
                String ruleClass = doc.field("ruleClass");
                map.put("label", ruleClass);
                map.put("value", ruleClass);
                list.add(map);
            }
            json = mapper.writeValueAsString(list);
        }

    } catch (Exception e) {
        logger.error("Exception:", e);
        //throw e;
    } finally {
        graph.shutdown();
    }
    return json;
}
 
Example 12
Source File: DelMenuRule.java    From light with Apache License 2.0 5 votes vote down vote up
public boolean execute (Object ...objects) throws Exception {
    Map<String, Object> inputMap = (Map<String, Object>) objects[0];
    Map<String, Object> data = (Map<String, Object>) inputMap.get("data");
    Map<String, Object> user = (Map<String, Object>) inputMap.get("user");
    String rid = (String)data.get("@rid");
    String error = null;

    String host = (String)user.get("host");
    if(host != null && !host.equals(data.get("host"))) {
        error = "User can only delete menu for host: " + host;
        inputMap.put("responseCode", 403);
    } else {
        OrientGraph graph = ServiceLocator.getInstance().getGraph();
        try {
            Vertex menu = DbService.getVertexByRid(graph, rid);
            if(menu == null) {
                error = "Menu with @rid " + rid + " cannot be found";
                inputMap.put("responseCode", 404);
            } else {
                Map eventMap = getEventMap(inputMap);
                Map<String, Object> eventData = (Map<String, Object>)eventMap.get("data");
                inputMap.put("eventMap", eventMap);
                eventData.put("host", menu.getProperty("host"));// unique key
            }
        } catch (Exception e) {
            logger.error("Exception:", e);
            throw e;
        } finally {
            graph.shutdown();
        }
    }
    if(error != null) {
        inputMap.put("result", error);
        return false;
    } else {
        return true;
    }
}
 
Example 13
Source File: AbstractPageRule.java    From light with Apache License 2.0 5 votes vote down vote up
protected void impPage(Map<String, Object> data) throws Exception {
    OrientGraph graph = ServiceLocator.getInstance().getGraph();
    String pageId = (String)data.get("pageId");
    try {
        graph.begin();
        OrientVertex page = (OrientVertex)graph.getVertexByKey("Page.pageId", pageId);
        if(page != null) {
            graph.removeVertex(page);
        }
        Vertex createUser = graph.getVertexByKey("User.userId", data.remove("createUserId"));
        page = graph.addVertex("class:Page", data);
        createUser.addEdge("Create", page);
        graph.commit();
        String json = page.getRecord().toJSON();
        Map<String, Object> pageMap = ServiceLocator.getInstance().getMemoryImage("pageMap");
        ConcurrentMap<Object, Object> cache = (ConcurrentMap<Object, Object>)pageMap.get("cache");
        if(cache == null) {
            cache = new ConcurrentLinkedHashMap.Builder<Object, Object>()
                    .maximumWeightedCapacity(1000)
                    .build();
            pageMap.put("cache", cache);
        }
        CacheObject co = (CacheObject)cache.get(pageId);
        if(co != null) {
            co.setEtag(page.getProperty("@version").toString());
            co.setData(json);
        } else {
            cache.put(pageId, new CacheObject(page.getProperty("@version").toString(), json));
        }
    } catch (Exception e) {
        logger.error("Exception:", e);
        graph.rollback();
        throw e;
    } finally {
        graph.shutdown();
    }
}
 
Example 14
Source File: DownCommentRule.java    From light with Apache License 2.0 5 votes vote down vote up
public boolean execute (Object ...objects) throws Exception {
    Map<String, Object> inputMap = (Map<String, Object>)objects[0];
    Map<String, Object> data = (Map<String, Object>)inputMap.get("data");
    Map<String, Object> user = (Map<String, Object>) inputMap.get("user");
    String rid = (String)data.get("@rid");
    String entityRid = (String)data.get("entityRid");
    String error = null;
    OrientGraph graph = ServiceLocator.getInstance().getGraph();
    try {
        // check if the comment exists
        OrientVertex comment = (OrientVertex) DbService.getVertexByRid(graph, rid);
        if(comment == null ) {
            error = "Comment @rid " + rid + " cannot be found";
            inputMap.put("responseCode", 404);
        } else {
            Map eventMap = getEventMap(inputMap);
            Map<String, Object> eventData = (Map<String, Object>)eventMap.get("data");
            inputMap.put("eventMap", eventMap);
            eventData.put("commentId", comment.getProperty("commentId"));
            eventData.put("userId", user.get("userId"));
            clearCommentCache(entityRid);
        }
    } catch (Exception e) {
        logger.error("Exception:", e);
        throw e;
    } finally {
        graph.shutdown();
    }
    if(error != null) {
        inputMap.put("result", error);
        return false;
    } else {
        return true;
    }
}
 
Example 15
Source File: AbstractUserRule.java    From light with Apache License 2.0 5 votes vote down vote up
protected void updUser(Map<String, Object> data) throws Exception {
    OrientGraph graph = ServiceLocator.getInstance().getGraph();
    try {
        graph.begin();
        Vertex user =  graph.getVertexByKey("User.userId", data.get("userId"));
        if(user != null) {
            String firstName = (String)data.get("firstName");
            if(firstName != null && !firstName.equals(user.getProperty("firstName"))) {
                user.setProperty("firstName", firstName);
            }
            String lastName = (String)data.get("lastName");
            if(lastName != null && !lastName.equals(user.getProperty("lastName"))) {
                user.setProperty("lastName", lastName);
            }
            // TODO update shipping address and payment address here.
            Map<String, Object> shippingAddress = (Map<String, Object>)data.get("shippingAddress");
            if(shippingAddress != null) {
                user.setProperty("shippingAddress", shippingAddress);
            }
            Map<String, Object> paymentAddress = (Map<String, Object>)data.get("paymentAddress");
            if(paymentAddress != null) {
                user.setProperty("paymentAddress", paymentAddress);
            }
            user.setProperty("updateDate", data.get("updateDate"));
        }
        graph.commit();
    } catch (Exception e) {
        logger.error("Exception:", e);
        graph.rollback();
        throw e;
    } finally {
        graph.shutdown();
    }
}
 
Example 16
Source File: BranchRule.java    From light with Apache License 2.0 5 votes vote down vote up
protected void addBranchDb(String branchType, Map<String, Object> data) throws Exception {
    String className = branchType.substring(0, 1).toUpperCase() + branchType.substring(1);
    String host = (String)data.get("host");
    OrientGraph graph = ServiceLocator.getInstance().getGraph();
    try{
        graph.begin();
        Vertex createUser = graph.getVertexByKey("User.userId", data.remove("createUserId"));
        List<String> parentIds = (List<String>)data.remove("in_Own");
        List<String> childrenIds = (List<String>)data.remove("out_Own");
        OrientVertex branch = graph.addVertex("class:" + className, data);
        createUser.addEdge("Create", branch);
        // parent
        if(parentIds != null && parentIds.size() == 1) {
            OrientVertex parent = getBranchByHostId(graph, branchType, host, parentIds.get(0));
            if(parent != null) {
                parent.addEdge("Own", branch);
            }
        }
        // children
        if(childrenIds != null) {
            for(String childId: childrenIds) {
                OrientVertex child = getBranchByHostId(graph, branchType, host, childId);
                if(child != null) {
                    branch.addEdge("Own", child);
                }
            }
        }
        graph.commit();
    } catch (Exception e) {
        logger.error("Exception:", e);
        graph.rollback();
    } finally {
        graph.shutdown();
    }
}
 
Example 17
Source File: AbstractConfigRule.java    From light with Apache License 2.0 4 votes vote down vote up
public boolean addHostConfig (Object ...objects) throws Exception {
    Map<String, Object> inputMap = (Map<String, Object>) objects[0];
    Map<String, Object> data = (Map<String, Object>) inputMap.get("data");
    Map<String, Object> user = (Map<String, Object>) inputMap.get("user");
    String configId = (String) data.get("configId");
    String host = (String) data.get("host");
    String error = null;
    String userHost = (String)user.get("host");
    if(userHost != null && !userHost.equals(host)) {
        error = "You can only add config from host: " + host;
        inputMap.put("responseCode", 401);
    } else {
        OrientGraph graph = ServiceLocator.getInstance().getGraph();
        try {
            ODocument config = getODocumentByHostId(graph, "configHostIdIdx", host, configId);
            if(config != null) {
                error = "configId " + configId + " exists on host " + host;
                inputMap.put("responseCode", 400);
            } else {
                Map eventMap = getEventMap(inputMap);
                Map<String, Object> eventData = (Map<String, Object>)eventMap.get("data");
                inputMap.put("eventMap", eventMap);
                eventData.putAll((Map<String, Object>) inputMap.get("data"));
                eventData.put("createDate", new java.util.Date());
                eventData.put("createUserId", user.get("userId"));
                // replace properties
                String properties = (String)data.get("properties");
                if(properties != null) {
                    Map<String, Object> map = mapper.readValue(properties,
                            new TypeReference<HashMap<String, Object>>() {
                            });
                    eventData.put("properties", map);
                }
            }
        } catch (Exception e) {
            logger.error("Exception:", e);
            throw e;
        } finally {
            graph.shutdown();
        }
    }
    if(error != null) {
        inputMap.put("result", error);
        return false;
    } else {
        return true;
    }
}
 
Example 18
Source File: DelAccessRule.java    From light with Apache License 2.0 4 votes vote down vote up
public boolean execute (Object ...objects) throws Exception {
    Map<String, Object> inputMap = (Map<String, Object>) objects[0];
    Map<String, Object> data = (Map<String, Object>) inputMap.get("data");
    Map<String, Object> user = (Map<String, Object>) inputMap.get("user");
    String rid = (String)data.get("@rid");
    int inputVersion = (int)data.get("@version");
    String ruleClass = (String)data.get("ruleClass");
    String error = null;

    if(user == null) {
        error = "Login is required";
        inputMap.put("responseCode", 401);
    } else {
        List roles = (List)user.get("roles");
        if(!roles.contains("owner") && !roles.contains("admin") && !roles.contains("ruleAdmin")) {
            error = "Role owner or admin or ruleAdmin is required to delete rule";
            inputMap.put("responseCode", 403);
        } else {
            String host = (String)user.get("host");
            if(host != null && !host.equals(data.get("host"))) {
                error = "User can only delete access control from host: " + host;
                inputMap.put("responseCode", 403);
            } else {
                // check if the access control exist or not.
                OrientGraph graph = ServiceLocator.getInstance().getGraph();
                try {
                    Vertex access = DbService.getVertexByRid(graph, rid);
                    if(access == null) {
                        error = "Access control with @rid " + rid + " cannot be found";
                        inputMap.put("responseCode", 404);
                    } else {
                        int storedVersion = access.getProperty("@version");
                        if(inputVersion != storedVersion) {
                            error = "Deleting version " + inputVersion + " doesn't match stored version " + storedVersion;
                            inputMap.put("responseCode", 400);
                        } else {
                            Map eventMap = getEventMap(inputMap);
                            Map<String, Object> eventData = (Map<String, Object>)eventMap.get("data");
                            inputMap.put("eventMap", eventMap);
                            eventData.put("ruleClass", ruleClass);
                            eventData.put("updateDate", new java.util.Date());
                            eventData.put("updateUserId", user.get("userId"));
                        }
                    }
                } catch (Exception e) {
                    logger.error("Exception:", e);
                    throw e;
                } finally {
                    graph.shutdown();
                }
            }
        }
    }

    if(error != null) {
        inputMap.put("result", error);
        return false;
    } else {
        return true;
    }
}
 
Example 19
Source File: AddPageRule.java    From light with Apache License 2.0 4 votes vote down vote up
public boolean execute (Object ...objects) throws Exception {
    Map<String, Object> inputMap = (Map<String, Object>)objects[0];
    HttpServerExchange exchange = (HttpServerExchange)inputMap.get("exchange");
    Map<String, Object> data = (Map<String, Object>)inputMap.get("data");
    String pageId = (String)data.get("pageId");
    String host = (String)data.get("host");
    String error = null;
    Map<String, Object> user = (Map<String, Object>) inputMap.get("user");
    String userHost = (String)user.get("host");
    if(userHost != null) {
        if (!userHost.equals(host)) {
            error = "You can only add page from host: " + host;
            inputMap.put("responseCode", 403);
        }
    } else {
        // remove host as this is the owner
        data.remove("host");
    }
    OrientGraph graph = ServiceLocator.getInstance().getGraph();
    try {
        CacheObject co = getPageById(graph, pageId);
        if(co != null) {
            error = "Page with the same id exists";
            inputMap.put("responseCode", 400);
        } else {
            Map eventMap = getEventMap(inputMap);
            Map<String, Object> eventData = (Map<String, Object>)eventMap.get("data");
            inputMap.put("eventMap", eventMap);
            eventData.putAll(data);
            eventData.put("createDate", new java.util.Date());
            eventData.put("createUserId", user.get("userId"));
        }
    } catch (Exception e) {
        logger.error("Exception:", e);
        throw e;
    } finally {
        graph.shutdown();
    }
    if(error != null) {
        inputMap.put("result", error);
        return false;
    } else {
        return true;
    }
}
 
Example 20
Source File: DownPostRule.java    From light with Apache License 2.0 4 votes vote down vote up
public boolean execute (Object ...objects) throws Exception {
    Map<String, Object> inputMap = (Map<String, Object>)objects[0];
    Map<String, Object> data = (Map<String, Object>)inputMap.get("data");
    Map<String, Object> user = (Map<String, Object>) inputMap.get("user");
    String rid = (String)data.get("@rid");
    String error = null;
    OrientGraph graph = ServiceLocator.getInstance().getGraph();
    try {
        OrientVertex post = (OrientVertex) DbService.getVertexByRid(graph, rid);
        OrientVertex voteUser = (OrientVertex)graph.getVertexByKey("User.userId", user.get("userId"));
        if(post == null) {
            error = "@rid " + rid + " cannot be found";
            inputMap.put("responseCode", 404);
        } else {
            // TODO check if the current user has down voted the post before.
            boolean voted = false;
            for (Edge edge : voteUser.getEdges(post, Direction.OUT, "DownVote")) {
                if(edge.getVertex(Direction.IN).equals(post)) voted = true;
            }
            if(voted) {
                error = "You have down voted the post already";
                inputMap.put("responseCode", 400);
            } else {
                Map eventMap = getEventMap(inputMap);
                Map<String, Object> eventData = (Map<String, Object>)eventMap.get("data");
                inputMap.put("eventMap", eventMap);
                eventData.put("entityId", post.getProperty("entityId"));
                eventData.put("updateUserId", user.get("userId"));
            }
        }
    } catch (Exception e) {
        logger.error("Exception:", e);
        throw e;
    } finally {
        graph.shutdown();
    }
    if(error != null) {
        inputMap.put("result", error);
        return false;
    } else {
        return true;
    }
}