/*
  * It will remove a property from an embedded node if it exists.
  * After deleting the property, if the node does not have any more properties and relationships (except for an incoming one),
  * it will delete the embedded node as well.
  */
 private void removePropertyForEmbedded(Node embeddedNode, String[] embeddedColumnSplit, int i) {
   if (i == embeddedColumnSplit.length - 1) {
     // Property
     String property = embeddedColumnSplit[embeddedColumnSplit.length - 1];
     if (embeddedNode.hasProperty(property)) {
       embeddedNode.removeProperty(property);
     }
   } else {
     Iterator<Relationship> iterator =
         embeddedNode
             .getRelationships(Direction.OUTGOING, withName(embeddedColumnSplit[i]))
             .iterator();
     if (iterator.hasNext()) {
       removePropertyForEmbedded(iterator.next().getEndNode(), embeddedColumnSplit, i + 1);
     }
   }
   if (!embeddedNode.getPropertyKeys().iterator().hasNext()) {
     // Node without properties
     Iterator<Relationship> iterator = embeddedNode.getRelationships().iterator();
     if (iterator.hasNext()) {
       Relationship relationship = iterator.next();
       if (!iterator.hasNext()) {
         // Node with only one relationship and no properties,
         // we can remove it:
         // It means we have removed all the properties from the embedded node
         // and it is NOT an intermediate node like
         // (entity) --> (embedded1) --> (embedded2)
         relationship.delete();
         embeddedNode.delete();
       }
     }
   }
 }
 public void writeField(Node entity, JsonGenerator jg) throws IOException {
   jg.writeStartObject();
   for (String field : entity.getPropertyKeys()) {
     Object value = entity.getProperty(field);
     writeValue(field, value, jg);
   }
   jg.writeEndObject();
   jg.flush();
 }
 public void dumpGraphToConsole() {
   for (Node n : GlobalGraphOperations.at(db).getAllNodes()) {
     Iterable<String> propertyKeys = n.getPropertyKeys();
     for (String key : propertyKeys) {
       System.out.print(key + " : ");
       System.out.println(n.getProperty(key));
     }
   }
 }
Exemple #4
0
  // ----- private methods -----
  private void extractProperties(final Node node) {

    for (final String key : node.getPropertyKeys()) {

      final Object value = node.getProperty(key);
      if (value != null) {
        properties.put(key, value.getClass());
      }
    }
  }
 public void dumpNode(Node node) {
   if (node == null) {
     System.out.println("Null Node");
     return;
   }
   System.out.println(String.format("Node ID [%d]", node.getId()));
   for (String key : node.getPropertyKeys()) {
     System.out.print(key + " : ");
     System.out.println(node.getProperty(key));
   }
 }
Exemple #6
0
  public Map<String, Object> _getProperties(Node node) {
    Iterable<String> keys = node.getPropertyKeys();
    Map<String, Object> pars = null;

    for (String key : keys) {
      if (null == pars) pars = new HashMap<String, Object>();

      pars.put(key, node.getProperty(key));
    }

    return pars;
  }
  @Test
  public void testNodeGetProperties() {
    Node node1 = getGraphDb().getNodeById(node1Id);

    assertTrue(!node1.hasProperty(null));
    Iterator<Object> values = node1.getPropertyValues().iterator();
    values.next();
    values.next();
    Iterator<String> keys = node1.getPropertyKeys().iterator();
    keys.next();
    keys.next();
    assertTrue(node1.hasProperty(key1));
    assertTrue(node1.hasProperty(key2));
  }
 public Map<String, Object> getNodeProperties(long nodeId) throws DatabaseBlockedException {
   Transaction tx = database.graph.beginTx();
   try {
     Node node = database.graph.getNodeById(nodeId);
     Map<String, Object> allProperties = new HashMap<String, Object>();
     for (String propertyKey : node.getPropertyKeys()) {
       allProperties.put(propertyKey, node.getProperty(propertyKey));
     }
     tx.success();
     return allProperties;
   } finally {
     tx.finish();
   }
 }
  @Test
  public void shouldBeAbleToRemoveNodeProperties() throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("foo", "bar");
    properties.put("number", 15);
    long nodeId = createNode(properties);
    actions.removeAllNodeProperties(nodeId);

    Transaction tx = database.getGraph().beginTx();
    try {
      Node node = database.getGraph().getNodeById(nodeId);
      assertEquals(false, node.getPropertyKeys().iterator().hasNext());
      tx.success();
    } finally {
      tx.finish();
    }
  }
 public void getAllNodes(String query, String tag) {
   System.out.println(tag);
   System.out.println("-----------------------");
   Result result = graphDb.execute(query);
   while (result.hasNext()) {
     Map<String, Object> map = result.next();
     for (Map.Entry<String, Object> entry : map.entrySet()) {
       System.out.println("key:" + entry.getKey() + ", value" + entry.getValue());
       Node node1 = (Node) entry.getValue();
       Iterator<String> keys = node1.getPropertyKeys().iterator();
       while (keys.hasNext()) {
         System.out.println(keys.next());
       }
     }
   }
   System.out.println("-----------------------");
 }
Exemple #11
0
  public static void exportFromDB(GraphDatabaseService graphDatabaseService) {

    GlobalGraphOperations graphOperations = GlobalGraphOperations.at(graphDatabaseService);
    Node refNode = graphDatabaseService.getReferenceNode();
    for (Node node : graphOperations.getAllNodes()) {

      StringBuffer stringBuffer = new StringBuffer();
      stringBuffer.append("{");
      for (String key : node.getPropertyKeys()) {
        String value = (String) node.getProperty(key);
        stringBuffer.append(String.format("%s : %s", key, value));
      }
      for (Relationship rel : node.getRelationships(Direction.OUTGOING)) {}

      stringBuffer.append("}");
    }
  }
  public String getAttributeJSON(String varName) {
    // EDITING THE STRING
    String output = "var " + varName + " = {";

    String AttributeObjectString = "";
    for (String key : theNode.getPropertyKeys()) {
      if (DefaultTemplate.keepAttribute(key))
        AttributeObjectString +=
            ",\""
                + key
                + "\":\""
                + DefaultTemplate.Sanitize(theNode.getProperty(key).toString())
                + "\"";
    }
    if (AttributeObjectString.isEmpty()) output += "};\n";
    else output += AttributeObjectString.substring(1) + "};\n";
    return output;
  }
 public String sumNodeContents(Node node) {
   StringBuffer result = new StringBuffer();
   for (Relationship rel : node.getRelationships()) {
     if (rel.getStartNode().equals(node)) {
       result.append(
           rel.getStartNode() + " ---[" + rel.getType().name() + "]--> " + rel.getEndNode());
     } else {
       result.append(
           rel.getStartNode() + " <--[" + rel.getType().name() + "]--- " + rel.getEndNode());
     }
     result.append("\n");
   }
   for (String key : node.getPropertyKeys()) {
     for (Object value : propertyValueAsArray(node.getProperty(key))) {
       result.append("*" + key + "=[" + value + "]");
       result.append("\n");
     }
   }
   return result.toString();
 }
  protected static String findTitle(GraphDatabaseShellServer server, Session session, Node node) {
    String keys = (String) session.get(AbstractClient.TITLE_KEYS_KEY);
    if (keys == null) {
      return null;
    }

    String[] titleKeys = keys.split(Pattern.quote(","));
    Pattern[] patterns = new Pattern[titleKeys.length];
    for (int i = 0; i < titleKeys.length; i++) {
      patterns[i] = Pattern.compile(titleKeys[i]);
    }
    for (Pattern pattern : patterns) {
      for (String nodeKey : node.getPropertyKeys()) {
        if (matches(pattern, nodeKey, false, false)) {
          return trimLength(session, format(node.getProperty(nodeKey), false));
        }
      }
    }
    return null;
  }
  protected void verifyData(int nodeCount, GraphDatabaseService db) {
    // Verify that all the labels are in place
    Set<Label> expectedLabels = new HashSet<>();
    for (String label : LABELS) {
      expectedLabels.add(DynamicLabel.label(label));
    }
    GlobalGraphOperations globalOps = GlobalGraphOperations.at(db);
    Set<Label> allLabels = Iterables.toSet(globalOps.getAllLabels());
    assertThat(allLabels, is(expectedLabels));

    // Sample some nodes for deeper inspection of their contents
    Random random = new Random();
    for (int i = 0; i < nodeCount / 10; i++) {
      Node node = db.getNodeById(random.nextInt(nodeCount));
      int count = count(node.getRelationships());
      assertEquals("For node " + node, count, node.getDegree());
      for (String key : node.getPropertyKeys()) {
        node.getProperty(key);
        Set<Label> actualLabels = Iterables.toSet(node.getLabels());
        assertThat(actualLabels, is(expectedLabels));
      }
    }
  }
Exemple #16
0
 @Override
 @SuppressWarnings("unchecked")
 /**
  * Read a record from the database. Each field/value pair from the result will be stored in a
  * HashMap.
  *
  * @param table The name of the table
  * @param key The record key of the record to read.
  * @param fields The list of fields to read, or null for all of them
  * @param result A HashMap of field/value pairs for the result
  * @return Zero on success, a non-zero error code on error or "not found".
  */
 public int read(
     String table, String key, Set<String> fields, HashMap<String, ByteIterator> result) {
   try {
     IndexHits<Node> hits = index().get("_id", key);
     Node node = hits.getSingle();
     if (node == null) {
       return 1;
     }
     if (fields != null) {
       for (String field : fields) {
         String value = node.getProperty(field).toString();
         result.put(field, new StringByteIterator(value));
       }
     } else {
       for (String field : node.getPropertyKeys()) {
         String value = node.getProperty(field).toString();
         result.put(field, new StringByteIterator(value));
       }
     }
     return 0;
   } catch (Exception e) {
     e.printStackTrace();
     return 1;
   }
 }
Exemple #17
0
  @Override
  protected Continuation exec(AppCommandParser parser, Session session, Output out)
      throws ShellException, RemoteException {
    assertCurrentIsNode(session);

    Node node = this.getCurrent(session).asNode();
    boolean caseInsensitiveFilters = parser.options().containsKey("i");
    boolean looseFilters = parser.options().containsKey("l");
    boolean quiet = parser.options().containsKey("q");

    // Order
    TraversalDescription description = Traversal.description();
    String order = parser.options().get("o");
    if (order != null) {
      description = description.order(parseOrder(order));
    }

    // Relationship types / expander
    String relationshipTypes = parser.options().get("r");
    if (relationshipTypes != null) {
      Map<String, Object> types = parseFilter(relationshipTypes, out);
      description =
          description.expand(
              toExpander(getServer().getDb(), null, types, caseInsensitiveFilters, looseFilters));
    }

    // Uniqueness
    String uniqueness = parser.options().get("u");
    if (uniqueness != null) {
      description = description.uniqueness(parseUniqueness(uniqueness));
    }

    // Depth limit
    String depthLimit = parser.options().get("d");
    if (depthLimit != null) {
      description = description.evaluator(toDepth(parseInt(depthLimit)));
    }

    String filterString = parser.options().get("f");
    Map<String, Object> filterMap = filterString != null ? parseFilter(filterString, out) : null;
    String commandToRun = parser.options().get("c");
    Collection<String> commandsToRun = new ArrayList<String>();
    if (commandToRun != null) {
      commandsToRun.addAll(Arrays.asList(commandToRun.split(Pattern.quote("&&"))));
    }
    for (Path path : description.traverse(node)) {
      boolean hit = false;
      if (filterMap == null) {
        hit = true;
      } else {
        Node endNode = path.endNode();
        Map<String, Boolean> matchPerFilterKey = new HashMap<String, Boolean>();
        for (String key : endNode.getPropertyKeys()) {
          for (Map.Entry<String, Object> filterEntry : filterMap.entrySet()) {
            String filterKey = filterEntry.getKey();
            if (matchPerFilterKey.containsKey(filterKey)) {
              continue;
            }

            if (matches(
                newPattern(filterKey, caseInsensitiveFilters),
                key,
                caseInsensitiveFilters,
                looseFilters)) {
              Object value = endNode.getProperty(key);
              String filterPattern =
                  filterEntry.getValue() != null ? filterEntry.getValue().toString() : null;
              if (matches(
                  newPattern(filterPattern, caseInsensitiveFilters),
                  value.toString(),
                  caseInsensitiveFilters,
                  looseFilters)) {
                matchPerFilterKey.put(filterKey, true);
              }
            }
          }
        }

        if (matchPerFilterKey.size() == filterMap.size()) {
          hit = true;
        }
      }
      if (hit) {
        if (commandsToRun.isEmpty()) {
          printPath(path, quiet, session, out);
        } else {
          printAndInterpretTemplateLines(
              commandsToRun,
              false,
              true,
              NodeOrRelationship.wrap(path.endNode()),
              getServer(),
              session,
              out);
        }
      }
    }
    return Continuation.INPUT_COMPLETE;
  }
Exemple #18
0
 private void appendPropertySetters(PrintWriter out, Node node) {
   for (String prop : node.getPropertyKeys()) {
     out.println(
         "set " + identifier(node) + "." + quote(prop) + "=" + toString(node.getProperty(prop)));
   }
 }
  public Concept getByNode(Node node) {
    Concept concept = new Concept();
    if (node != null) {

      concept.setNodeId(node.getId());

      Iterable<String> iterable = node.getPropertyKeys();
      for (String key : iterable) {

        if (key.equals(NamespaceConstants.CONCEPT_ID)) {
          concept.setId(node.getProperty(NamespaceConstants.CONCEPT_ID).toString());
          continue;
        }

        if (key.equals(NamespaceConstants.NAME)) {
          concept.setName(node.getProperty(NamespaceConstants.NAME).toString());
          continue;
        }

        if (key.equals(NamespaceConstants.TYPE)) {
          concept.setType(node.getProperty(NamespaceConstants.TYPE).toString());
          continue;
        }

        if (key.equals(NamespaceConstants.URI)) {
          concept.setUri(node.getProperty(NamespaceConstants.URI).toString());
          continue;
        }

        if (key.equals(NamespaceConstants.DATE_CREATED)) {
          concept.setDateCreated(
              Long.parseLong(node.getProperty(NamespaceConstants.DATE_CREATED).toString()));
          continue;
        }

        if (key.equals(NamespaceConstants.DATE_UPDATED)) {
          concept.setDateUpdated(
              Long.parseLong(node.getProperty(NamespaceConstants.DATE_UPDATED).toString()));
          continue;
        }

        if (key.equals(NamespaceConstants.DATE_ENRICHED)) {
          concept.setDateEnriched(
              Long.parseLong(node.getProperty(NamespaceConstants.DATE_ENRICHED).toString()));
          continue;
        }

        if (key.equals(NamespaceConstants.ENRICHED)) {
          concept.setEnriched(
              Boolean.parseBoolean(node.getProperty(NamespaceConstants.ENRICHED).toString()));
          continue;
        }

        if (key.equals(NamespaceConstants.ENRICH_COUNTER)) {
          concept.setEnrichCounter(
              Integer.parseInt(node.getProperty(NamespaceConstants.ENRICH_COUNTER).toString()));
          continue;
        }

        if (key.equals(NamespaceConstants.URI_COUNTER)) {
          concept.setUriCounter(
              Integer.parseInt(node.getProperty(NamespaceConstants.URI_COUNTER).toString()));
          continue;
        }

        //					if (key.equals(NamespaceConstants.GEO_LAT)){
        //						concept.(node.getProperty(NamespaceConstants.GEO_LAT).toString());
        //						continue;
        //					}

        concept.addProperty(key, node.getProperty(key));
      }
    }
    return concept;
  }
Exemple #20
0
 private boolean hasProperties(Node node) {
   return node.getPropertyKeys().iterator().hasNext();
 }