Java 类org.neo4j.graphdb.DynamicRelationshipType 实例源码

项目:neo4j-lucene5-index    文件:RelatedNodesQuestionTest.java   
@Test
public void question5346011()
{
    GraphDatabaseService service = new TestGraphDatabaseFactory().newImpermanentDatabase();
    try ( Transaction tx = service.beginTx() )
    {
        RelationshipIndex index = service.index().forRelationships( "exact" );
        // ...creation of the nodes and relationship
        Node node1 = service.createNode();
        Node node2 = service.createNode();
        String a_uuid = "xyz";
        Relationship relationship = node1.createRelationshipTo( node2, DynamicRelationshipType.withName( "related" ) );
        index.add( relationship, "uuid", a_uuid );
        // query
        IndexHits<Relationship> hits = index.get( "uuid", a_uuid, node1, node2 );
        assertEquals( 1, hits.size() );
        tx.success();
    }
    service.shutdown();
}
项目:neo4j-lucene5-index    文件:TestLuceneIndex.java   
@Test
public void makeSureYouCanRemoveFromRelationshipIndex()
{
    Node n1 = graphDb.createNode();
    Node n2 = graphDb.createNode();
    Relationship r = n1.createRelationshipTo( n2, DynamicRelationshipType.withName( "foo" ) );
    RelationshipIndex index = graphDb.index().forRelationships( "rel-index" );
    String key = "bar";
    index.remove( r, key, "value" );
    index.add( r, key, "otherValue" );
    for ( int i = 0; i < 2; i++ )
    {
        assertThat( index.get( key, "value" ), isEmpty() );
        assertThat( index.get( key, "otherValue" ), contains( r ) );
        restartTx();
    }
}
项目:neo4j-lucene5-index    文件:RecoveryTest.java   
public static void main( String[] args )
{
    GraphDatabaseService db = new TestGraphDatabaseFactory().newEmbeddedDatabase( args[0] );
    try ( Transaction tx = db.beginTx() )
    {
        Index<Relationship> index = db.index().forRelationships( "myIndex" );
        Node node = db.createNode();
        Relationship relationship = db.createNode().createRelationshipTo( node,
                DynamicRelationshipType.withName( "KNOWS" ) );

        index.add( relationship, "key", "value" );
        tx.success();
    }

    db.shutdown();
    System.exit( 0 );
}
项目:dswarm-graph-neo4j    文件:PropertyEnrichGDMWorker.java   
public PropertyEnrichGDMWorker(final String prefixedResourceUriArg, final long resourceHashArg, final GraphDatabaseService databaseArg, final
NamespaceIndex namespaceIndexArg) throws DMPGraphException {

    prefixedResourceUri = prefixedResourceUriArg;
    resourceHash = resourceHashArg;
    database = databaseArg;
    namespaceIndex = namespaceIndexArg;
    nodeHandler = new CBDNodeHandler();
    startNodeHandler = new CBDStartNodeHandler();
    relationshipHandler = new CBDRelationshipHandler();

    final String prefixedRDFTypeURI = namespaceIndex.createPrefixedURI(RDF.type.getURI());
    final String prefixedRDFSClassURI = namespaceIndex.createPrefixedURI(RDFS.Class.getURI());

    prefixedRDFType = DynamicRelationshipType.withName(prefixedRDFTypeURI);
    prefixedRDFSClass = DynamicLabel.label(prefixedRDFSClassURI);
}
项目:csvtreeloader    文件:CSVTreeBuilder.java   
public void initializeWith(String treeSpec, Map<String,ColumnSpec> columns, List<String> leafProperties, String leafPropertiesColumn) throws UnsupportedEncodingException {
    TreeNodeBuilder parentBuilder = null;
    for (String columnSpec : URLDecoder.decode(treeSpec,"US-ASCII").split("->")) {
        String[] cs = columnSpec.split("-");
        String columnLabel = cs[0];
        RelationshipType child = cs.length > 1 ? DynamicRelationshipType.withName(cs[1]) : DEFAULT_CHILD;
        ColumnSpec column = columns.get(columnLabel);
        if (column == null) {
            throw new RuntimeException("Invalid tree '" + name + "': no such column '" + columnLabel + "'");
        } else {
            TreeNodeBuilder builder = TreeNodeBuilder.makeFor(column, parentBuilder, child, db, engine);
            this.builders.add(builder);
            parentBuilder = builder;
        }
    }
    if (parentBuilder != null) {
        parentBuilder.addProperties(leafProperties, leafPropertiesColumn);
    }
}
项目:bookish    文件:CategoryService.java   
public List<Category> getAll() {
    List<Category> categories = new ArrayList<Category>();
    for(Category cat : catRepo.findAllByTraversal(getCategoryRoot(), Traversal.description()
            .breadthFirst()
            .evaluator(Evaluators.fromDepth(1))
            .expand(Traversal
                .expanderForTypes(DynamicRelationshipType
                .withName(RelTypes.PARENT_CATEGORY), 
                          Direction.INCOMING).addNodeFilter(new Predicate<Node>() {
                                @Override
                                public boolean accept(Node item) {
                                    return !StringUtils.isEmpty(item.getProperty("name"));
                                }
                        }
                        )))) {
        if(cat != null && cat.getName() != null) { //TODO: Figure out why a null element appears in this traversal
            categories.add(cat);
        }
    }
    return categories;
}
项目:extended-objects    文件:AbstractEmbeddedNeo4jDatastore.java   
@Override
public DatastoreMetadataFactory<NodeMetadata<EmbeddedLabel>, EmbeddedLabel, RelationshipMetadata<EmbeddedRelationshipType>, EmbeddedRelationshipType> getMetadataFactory() {
    return new AbstractNeo4jMetadataFactory<EmbeddedLabel, EmbeddedRelationshipType>() {

        protected EmbeddedLabel createLabel(String value) {
            return new EmbeddedLabel(value);
        }


        protected EmbeddedRelationshipType createRelationshipType(String name) {
            return new EmbeddedRelationshipType(DynamicRelationshipType.withName(name));
        }

        @Override
        protected boolean isBatchableDefault() {
            return false;
        }
    };
}
项目:EvilCoder    文件:DDGPatcher.java   
private void addNewEdges(DDGDifference diff)
{
    List<DefUseRelation> relsToAdd = diff.getRelsToAdd();
    for (DefUseRelation rel : relsToAdd)
    {

        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put("var", rel.symbol);
        RelationshipType relType = DynamicRelationshipType
                .withName(EdgeTypes.REACHES);

        Neo4JDBInterface.addRelationship((Long) rel.src, (Long) rel.dst,
                relType, properties, true); //JANNIK: added flag
    }
}
项目:EvilCoder    文件:DefUseCFGPatcher.java   
public void writeChangesToDatabase()
{
    if (defUseCFG == null)
    {
        return;
    }

    for (DefUseLink link : newlyAddedLinks)
    {
        Long fromId = link.statement;
        Long toId = (Long) defUseCFG.getIdForSymbol(link.symbol);

        if (toId == null)
        {
            Map<String, Object> properties = new HashMap<String, Object>();
            Node statementNode = Neo4JDBInterface.getNodeById(link.statement);

            properties.put("functionId", statementNode.getProperty("functionId"));
            properties.put("type", "Symbol");
            properties.put("code", link.symbol);

            Node symbolNode = Neo4JDBInterface.addNode(properties);
            toId = (Long) symbolNode.getId();
        }

        RelationshipType relType = DynamicRelationshipType
                .withName(EdgeTypes.DEF);
        Neo4JDBInterface.addRelationship(fromId, toId, relType, null, true); //JANNIK: added flag
    }


}
项目:federator    文件:Neo4J.java   
@Override
public String insert(Entity entity, Set<Value> values) throws ParseException, Exception {

    try (Transaction tx = graphDb.beginTx()) {

        if (values == null || values.isEmpty() || values.size() == 0)
            throw new Exception("Cannot insert an empty list");

        Node node = graphDb.createNode();
        node.addLabel(DynamicLabel.label(entity.getId()));
        node.addLabel(DynamicLabel.label(entity.getName()));

        for (Value value : values) {
            node.setProperty(value.getField().getFieldName(), value.getValue());

            if (value.getType().equals("entity")) {

                Node related = graphDb.getNodeById(Long.valueOf(value.getValue()));

                node.createRelationshipTo(related,
                        DynamicRelationshipType.withName(value.getField().getFieldName()));
            }
        }

        tx.success();

        return entity.getId();
    }
}
项目:neo4j-lucene5-index    文件:TestLuceneIndex.java   
@Test
public void testNodeLocalRelationshipIndex()
{
    RelationshipIndex index = relationshipIndex(
            LuceneIndexImplementation.EXACT_CONFIG );

    RelationshipType type = DynamicRelationshipType.withName( "YO" );
    Node startNode = graphDb.createNode();
    Node endNode1 = graphDb.createNode();
    Node endNode2 = graphDb.createNode();
    Relationship rel1 = startNode.createRelationshipTo( endNode1, type );
    Relationship rel2 = startNode.createRelationshipTo( endNode2, type );
    index.add( rel1, "name", "something" );
    index.add( rel2, "name", "something" );

    for ( int i = 0; i < 2; i++ )
    {
        assertThat( index.query( "name:something" ), contains( rel1, rel2 ) );
        assertThat( index.query( "name:something", null, endNode1 ), contains( rel1 ) );
        assertThat( index.query( "name:something", startNode, endNode2 ), contains( rel2 ) );
        assertThat( index.query( null, startNode, endNode1 ), contains( rel1 ) );
        assertThat( index.get( "name", "something", null, endNode1 ), contains( rel1 ) );
        assertThat( index.get( "name", "something", startNode, endNode2 ), contains( rel2 ) );
        assertThat( index.get( null, null, startNode, endNode1 ), contains( rel1 ) );

        restartTx();
    }

    rel2.delete();
    rel1.delete();
    startNode.delete();
    endNode1.delete();
    endNode2.delete();
    index.delete();
}
项目:neo4j-lucene5-index    文件:TestLuceneIndex.java   
@Test
public void getOrCreateRelationshipWithUniqueFactory() throws Exception
{
    final String key = "name";
    final String value = "Mattias";

    final Node root = graphDb.createNode();
    final Index<Relationship> index = relationshipIndex( LuceneIndexImplementation.EXACT_CONFIG );
    final DynamicRelationshipType type = DynamicRelationshipType.withName( "SINGLE" );
    UniqueFactory<Relationship> factory = new UniqueFactory.UniqueRelationshipFactory( index )
    {
        @Override
        protected Relationship create( Map<String, Object> properties )
        {
            assertEquals( value, properties.get( key ) );
            assertEquals( 1, properties.size() );
            return root.createRelationshipTo( graphDatabase().createNode(), type );
        }
    };

    Relationship unique = factory.getOrCreate( key, value );
    assertEquals( unique, root.getSingleRelationship( type, Direction.BOTH ) );
    assertNotNull( unique );

    assertEquals( unique, index.get( key, value ).getSingle() );

    assertEquals( unique, factory.getOrCreate( key, value ) );
    assertEquals( unique, root.getSingleRelationship( type, Direction.BOTH ) );
    assertEquals( unique, index.get( key, value ).getSingle() );

    finishTx( false );
}
项目:neo4j-lucene5-index    文件:TestAutoIndexing.java   
@Test
public void testRelationshipAutoIndexFromAPISanity()
{
    final String propNameToIndex = "test";
    AutoIndexer<Relationship> autoIndexer = graphDb.index().getRelationshipAutoIndexer();
    autoIndexer.startAutoIndexingProperty( propNameToIndex );
    autoIndexer.setEnabled( true );
    newTransaction();

    Node node1 = graphDb.createNode();
    Node node2 = graphDb.createNode();
    Node node3 = graphDb.createNode();

    Relationship rel12 = node1.createRelationshipTo( node2,
            DynamicRelationshipType.withName( "DYNAMIC" ) );
    Relationship rel23 = node2.createRelationshipTo( node3,
            DynamicRelationshipType.withName( "DYNAMIC" ) );

    rel12.setProperty( propNameToIndex, "rel12" );
    rel23.setProperty( propNameToIndex, "rel23" );

    newTransaction();

    assertEquals(
            rel12,
            autoIndexer.getAutoIndex().get( propNameToIndex,
                    "rel12" ).getSingle() );
    assertEquals(
            rel23,
            autoIndexer.getAutoIndex().get( propNameToIndex,
                    "rel23" ).getSingle() );
}
项目:neo4j-lucene5-index    文件:TestAutoIndexing.java   
@Test
public void testDefaultsAreSeparateForNodesAndRelationships()
        throws Exception
{
    stopDb();
    config = new HashMap<>();
    config.put( GraphDatabaseSettings.node_keys_indexable.name(), "propName" );
    config.put( GraphDatabaseSettings.node_auto_indexing.name(), "true" );
    // Now only node properties named propName should be indexed.
    startDb();

    newTransaction();

    Node node1 = graphDb.createNode();
    Node node2 = graphDb.createNode();
    node1.setProperty( "propName", "node1" );
    node2.setProperty( "propName", "node2" );
    node2.setProperty( "propName_", "node2" );

    Relationship rel = node1.createRelationshipTo( node2,
            DynamicRelationshipType.withName( "DYNAMIC" ) );
    rel.setProperty( "propName", "rel1" );

    newTransaction();

    ReadableIndex<Node> autoIndex = graphDb.index().getNodeAutoIndexer().getAutoIndex();
    assertEquals( node1, autoIndex.get( "propName", "node1" ).getSingle() );
    assertEquals( node2, autoIndex.get( "propName", "node2" ).getSingle() );
    assertFalse( graphDb.index().getRelationshipAutoIndexer().getAutoIndex().get(
            "propName", "rel1" ).hasNext() );
}
项目:neo4j-lucene5-index    文件:TestAutoIndexing.java   
@Test
public void testRemoveRelationshipRemovesDocument()
{
    AutoIndexer<Relationship> autoIndexer = graphDb.index().getRelationshipAutoIndexer();
    autoIndexer.startAutoIndexingProperty( "foo" );
    autoIndexer.setEnabled( true );

    newTransaction();

    Node node1 = graphDb.createNode();
    Node node2 = graphDb.createNode();
    Relationship rel = node1.createRelationshipTo( node2, DynamicRelationshipType.withName( "foo" ) );
    rel.setProperty( "foo", "bar" );

    newTransaction();

    assertThat( graphDb.index().forRelationships( "relationship_auto_index" ).query( "_id_:*" ).size(),
            equalTo( 1 ) );

    newTransaction();

    rel.delete();

    newTransaction();

    assertThat( graphDb.index().forRelationships( "relationship_auto_index" ).query( "_id_:*" ).size(),
            equalTo( 0 ) );
}
项目:zerograph    文件:Database.java   
private RelationshipType getRelationshipType(String name) {
    if (typeCache.containsKey(name)) {
        return typeCache.get(name);
    } else {
        DynamicRelationshipType relationshipType = DynamicRelationshipType.withName(name);
        typeCache.put(name, relationshipType);
        return relationshipType;
    }
}
项目:zerograph    文件:ResourceTest.java   
protected Relationship createRel(NodeTemplateInterface start, RelTemplateInterface rel, NodeTemplateInterface end) {
    Node startNode = createNode(start);
    Node endNode = createNode(end);
    Relationship created = startNode.createRelationshipTo(endNode, DynamicRelationshipType.withName(rel.getType()));
    addProperties(created, rel.getProperties());
    return created;
}
项目:assertj-neo4j    文件:RelationshipAssert_doesNotHaveType_Test.java   
@Test
public void should_fail_if_relationship_has_given_type() {
  expectedException.expect(AssertionError.class);

  DynamicRelationshipType relationshipType = DynamicRelationshipType.withName("FOLLOWS");
  given_relationship_has_type(relationshipType);

  assertThat(relationship).doesNotHaveType(relationshipType);
}
项目:assertj-neo4j    文件:RelationshipAssert_hasType_Test.java   
@Test
public void should_pass_if_relationship_has_type() {
  RelationshipType relationshipType = DynamicRelationshipType.withName("LINKS");

  given_relationship_has_type(relationshipType);

  assertThat(relationship).hasType(relationshipType);
}
项目:assertj-neo4j    文件:RelationshipAssert_hasType_Test.java   
@Test
public void should_fail_if_relationship_does_not_have_any_type_name() {
  expectedException.expect(IllegalStateException.class);
  expectedException.expectMessage("The actual relationship type name should not be null");

  given_relationship_has_type(mock(RelationshipType.class));

  assertThat(relationship).hasType(DynamicRelationshipType.withName("FOLLOWS"));
}
项目:Oracle2Neo4j    文件:NeoDb.java   
public synchronized void insertEdge(long[] id, String typeName, Map<String, Object> properties) {
    this.inserter.createRelationship(id[0], id[1], DynamicRelationshipType.withName(typeName), properties);
}
项目:neo4j-talend-component    文件:Neo4jBatchInserterRelationship.java   
/**
 * Create the relationship.
 *
 * @param incoming   Talend incoming object
 * @param columnList Attribute list of Talend object
 */
public void create(Object incoming, List<String> columnList) {
    try {
        Long startNode = this.batchDb.findNodeInBatchIndex(startIndexName, this.getObjectProperty(incoming, startIndexField));
        Long endNode = this.batchDb.findNodeInBatchIndex(endIndexName, this.getObjectProperty(incoming, endIndexField));
        Map<String, Object> properties = constructMapFromObject(incoming, columnList);

        if (startNode != null && endNode != null) {

            String type = (String) this.getObjectProperty(incoming, relationshipTypeField);
            if (StringUtils.isNotEmpty(type)) {

                properties.remove(relationshipTypeField);
                properties.remove(startIndexField);
                properties.remove(endIndexField);

                if (direction.endsWith("OUTGOING")) {
                    this.batchDb.getInserter()
                            .createRelationship(startNode, endNode, DynamicRelationshipType.withName(type),
                                    properties);
                } else {
                    this.batchDb.getInserter()
                            .createRelationship(endNode, startNode, DynamicRelationshipType.withName(type),
                                    properties);
                }
            } else {
                log.trace("Ignoring incoming object {" + properties.toString() + "} due to none relation type");
            }
        } else {
            String msg = "Can't find start node " + startNode + " or end node " + endNode;
            if (skipOnError) {
                log.trace(msg);
            } else {
                throw new RuntimeException(msg);
            }
        }

    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}
项目:lumen    文件:LumenPersistenceImportLabelsApp.java   
public void importLabels(File dbPath, final File file) throws IOException {
        log.info("Importing {} ({} KiB) to {} ...", file, NUMBER.format(DefaultGroovyMethods.asType(file.length() / 1024, Long.class)), dbPath);
        long importeds = 0l;

        final BatchInserter inserter = BatchInserters.inserter(dbPath);
        try {
            final Label resourceLabel = DynamicLabel.label("Resource");
            final Label labelLabel = DynamicLabel.label("Label");
            inserter.createDeferredConstraint(resourceLabel).assertPropertyIsUnique("href").create();

            // PLEASE create the label indexes on last step, not now! to speed up imports on later stages
//            inserter.createDeferredSchemaIndex(resourceLabel).on('prefLabel').create()
//            inserter.createDeferredSchemaIndex(resourceLabel).on('isPreferredMeaningOf').create()
//            inserter.createDeferredSchemaIndex(labelLabel).on('v').create()

            final DynamicRelationshipType rdfsLabel = DynamicRelationshipType.withName("rdfs_label");

            try (final Scanner scanner = new Scanner(file, StandardCharsets.UTF_8.name())) {
                scanner.useDelimiter("\u0001");// Ctrl+A (SOH)
                while (true) {
                    final Object line;
                    try {
                        line = scanner.next();
                    } catch (NoSuchElementException ex) {
                        break;
                    }

                    final IndexedResource res = mapper.readValue((String) line, IndexedResource.class);
                    if (res.getPrefLabel() == null && res.getLabels() != null && !res.getLabels().isEmpty()) {
                        res.setPrefLabel(res.getLabels().get(0).getValue());
                        res.getLabels().remove(0);
                    }

                    final Map<String, Object> props = new HashMap<>();
                    if (res.getPrefLabel() != null) {
                        props.put("prefLabel", res.getPrefLabel());
                    }

                    if (res.getIsPreferredMeaningOf() != null) {
                        props.put("isPreferredMeaningOf", res.getIsPreferredMeaningOf());
                    }

                    final long resNode = inserter.createNode(props, resourceLabel);
                    for (IndexedResource.LocalizedLabel it : res.getLabels()) {
                        final Map<String, Object> labelProps = new HashMap<>();

                        if (it.getLanguage() != null) {
                            labelProps.put("l", it.getLanguage());
                        }

                        final long labelNode = inserter.createNode(labelProps, labelLabel);
                        inserter.createRelationship(resNode, labelNode, rdfsLabel, new LinkedHashMap());
                    }
                    importeds++;

                    if (importeds % 10000 == 0) {
                        log.info("Imported {} resource nodes +prefLabel +isPreferredMeaningOf +label relationships from {}", NUMBER.format(importeds), file);
                    }

                }

            }
        } catch (Exception e) {
            throw new RuntimeException("Cannot process", e);
        } finally {
            log.info("Shutting down batchInserter after importing {} resource nodes from {} ...", NUMBER.format(importeds), file);
            inserter.shutdown();
        }

        log.info("Completed importing {} resource nodes +prefLabel +isPreferredMeaningOf +label relationships from {}", NUMBER.format(importeds), file);
    }
项目:neo4j-lucene5-index    文件:ImdbDocTest.java   
@BeforeClass
public static void setUpDb()
{
    graphDb = new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().newGraphDatabase();
    try ( Transaction tx = graphDb.beginTx() )
    {
        // START SNIPPET: createIndexes
        IndexManager index = graphDb.index();
        Index<Node> actors = index.forNodes( "actors" );
        Index<Node> movies = index.forNodes( "movies" );
        RelationshipIndex roles = index.forRelationships( "roles" );
        // END SNIPPET: createIndexes

        // START SNIPPET: createNodes
        // Actors
        Node reeves = graphDb.createNode();
        reeves.setProperty( "name", "Keanu Reeves" );
        actors.add( reeves, "name", reeves.getProperty( "name" ) );
        Node bellucci = graphDb.createNode();
        bellucci.setProperty( "name", "Monica Bellucci" );
        actors.add( bellucci, "name", bellucci.getProperty( "name" ) );
        // multiple values for a field, in this case for search only
        // and not stored as a property.
        actors.add( bellucci, "name", "La Bellucci" );
        // Movies
        Node theMatrix = graphDb.createNode();
        theMatrix.setProperty( "title", "The Matrix" );
        theMatrix.setProperty( "year", 1999 );
        movies.add( theMatrix, "title", theMatrix.getProperty( "title" ) );
        movies.add( theMatrix, "year", theMatrix.getProperty( "year" ) );
        Node theMatrixReloaded = graphDb.createNode();
        theMatrixReloaded.setProperty( "title", "The Matrix Reloaded" );
        theMatrixReloaded.setProperty( "year", 2003 );
        movies.add( theMatrixReloaded, "title", theMatrixReloaded.getProperty( "title" ) );
        movies.add( theMatrixReloaded, "year", 2003 );
        Node malena = graphDb.createNode();
        malena.setProperty( "title", "Malèna" );
        malena.setProperty( "year", 2000 );
        movies.add( malena, "title", malena.getProperty( "title" ) );
        movies.add( malena, "year", malena.getProperty( "year" ) );
        // END SNIPPET: createNodes

        // START SNIPPET: createRelationships
        // we need a relationship type
        DynamicRelationshipType ACTS_IN = DynamicRelationshipType.withName( "ACTS_IN" );
        // create relationships
        Relationship role1 = reeves.createRelationshipTo( theMatrix, ACTS_IN );
        role1.setProperty( "name", "Neo" );
        roles.add( role1, "name", role1.getProperty( "name" ) );
        Relationship role2 = reeves.createRelationshipTo( theMatrixReloaded, ACTS_IN );
        role2.setProperty( "name", "Neo" );
        roles.add( role2, "name", role2.getProperty( "name" ) );
        Relationship role3 = bellucci.createRelationshipTo( theMatrixReloaded, ACTS_IN );
        role3.setProperty( "name", "Persephone" );
        roles.add( role3, "name", role3.getProperty( "name" ) );
        Relationship role4 = bellucci.createRelationshipTo( malena, ACTS_IN );
        role4.setProperty( "name", "Malèna Scordia" );
        roles.add( role4, "name", role4.getProperty( "name" ) );
        // END SNIPPET: createRelationships

        tx.success();
    }

    try ( Transaction tx = graphDb.beginTx() )
    {
        String title = "Movie and Actor Graph";
        try ( PrintWriter pw = AsciiDocGenerator.getPrintWriter( "target/docs/dev", title ) )
        {
            pw.println( AsciidocHelper.createGraphVizDeletingReferenceNode( title, graphDb, "initial" ) );
            pw.flush();
        }
    }
}
项目:neo4j-biorelation    文件:BioRelationFunction.java   
public Integer shortestDistance( Node source, Node target, Integer depth, String type, String direction ) {

    PathFinder<org.neo4j.graphdb.Path> finder;

    if ( type.equals("go") ) {

        // The relationships we will follow
        RelationshipType isa = DynamicRelationshipType.withName( "is_a" );
        RelationshipType partof = DynamicRelationshipType.withName( "part_of" );

        if ( direction.equals( "direction" ) ) {    
            finder = GraphAlgoFactory.shortestPath( PathExpanders.forTypesAndDirections( isa, Direction.OUTGOING, partof, Direction.OUTGOING ), depth );
        } else {
            finder = GraphAlgoFactory.shortestPath( PathExpanders.forTypesAndDirections( isa, Direction.BOTH, partof, Direction.BOTH ), depth );
        }

    } else {

        // The relationships we will follow
        RelationshipType parent = DynamicRelationshipType.withName( "has_parent" );

        if ( direction.equals( "direction" ) ) {    
            finder = GraphAlgoFactory.shortestPath( PathExpanders.forTypeAndDirection( parent, Direction.OUTGOING ), depth );
        } else {
            finder = GraphAlgoFactory.shortestPath( PathExpanders.forType( parent ), depth );

        }
    }


    Iterable<org.neo4j.graphdb.Path> ListPaths = finder.findAllPaths( source, target );

    Iterator<org.neo4j.graphdb.Path> itr = ListPaths.iterator();

    while ( itr.hasNext() ) {

        Integer hoplength = itr.next().length();
        if ( hoplength < depth ) {
            depth = hoplength;
        }
    }

    return depth;
}
项目:neo4j-biorelation    文件:BioRelationFunction.java   
public ArrayList<Long> shortestPathNodes( Node source, Node target, Integer depth, String type, String direction ) {

    ArrayList<Long> pathNodes = new ArrayList<Long>();

    PathFinder<org.neo4j.graphdb.Path> finder;

    BioRelationHelper helper = new BioRelationHelper(); 

    if ( type.equals("go") ) {

        // The relationships we will follow
        RelationshipType isa = DynamicRelationshipType.withName( "is_a" );
        RelationshipType partof = DynamicRelationshipType.withName( "part_of" );

        if ( direction.equals( "direction" ) ) {    
            finder = GraphAlgoFactory.shortestPath( PathExpanders.forTypesAndDirections( isa, Direction.OUTGOING, partof, Direction.OUTGOING ), depth );
        } else {
            finder = GraphAlgoFactory.shortestPath( PathExpanders.forTypesAndDirections( isa, Direction.BOTH, partof, Direction.BOTH ), depth );
        }

    } else {

        // The relationships we will follow
        RelationshipType parent = DynamicRelationshipType.withName( "has_parent" );

        if ( direction.equals( "direction" ) ) {    
            finder = GraphAlgoFactory.shortestPath( PathExpanders.forTypeAndDirection( parent, Direction.OUTGOING ), depth );
        } else {
            finder = GraphAlgoFactory.shortestPath( PathExpanders.forType( parent ), depth );

        }
    }

    Iterable<org.neo4j.graphdb.Path> ListPaths = finder.findAllPaths( source, target );

    Iterator<org.neo4j.graphdb.Path> itr = ListPaths.iterator();

    while ( itr.hasNext() ) {

        org.neo4j.graphdb.Path nodePath = itr.next();
        Integer hoplength = nodePath.length();
        if ( hoplength < depth ) {
            depth = hoplength;
            pathNodes.clear(); // Clear arrayList
            Iterable<Node> ListNodes = nodePath.nodes();

            pathNodes = helper.nodes2Array( ListNodes ); 
        }
    }

    return pathNodes;
}
项目:assertj-neo4j    文件:RelationshipAssert_doesNotHaveType_represented_as_string_Test.java   
@Test
public void should_pass_if_relationship_has_not_given_type_name() {
  given_relationship_has_type_name("LINKS");

  assertThat(relationship).doesNotHaveType(DynamicRelationshipType.withName("UNLINKS"));
}
项目:assertj-neo4j    文件:RelationshipAssert_doesNotHaveType_represented_as_string_Test.java   
private void given_relationship_has_type_name(String name) {
  when(relationship.getType()).thenReturn(DynamicRelationshipType.withName(name));
}
项目:assertj-neo4j    文件:RelationshipAssert_doesNotHaveType_Test.java   
@Test
public void should_pass_if_relationship_has_not_given_type() {
  given_relationship_has_type(DynamicRelationshipType.withName("LINKS"));

  assertThat(relationship).doesNotHaveType(DynamicRelationshipType.withName("UNLINKS"));
}
项目:assertj-neo4j    文件:RelationshipAssert_hasType_represented_as_string_Test.java   
private void given_relationship_has_type_name(String type) {
  when(relationship.getType()).thenReturn(DynamicRelationshipType.withName(type));
}
项目:dswarm-graph-neo4j    文件:EntityEvaluator.java   
@Override
public Evaluation evaluate(final Path path) {

    if (path.length() > relativeAttributePathSizeAttributePathSize) {

        return Evaluation.EXCLUDE_AND_PRUNE;
    }

    if (path.length() > currentHierarchy) {

        currentHierarchy++;
    }

    if (path.length() < currentHierarchy) {

        return Evaluation.EXCLUDE_AND_CONTINUE;
    }

    final Relationship lastRelationship = path.lastRelationship();
    final String attributeURI = relativeAttributePathAttributes.get(currentHierarchy - 1).getUri();

    // TODO: this was for debugging, or?
    //lastRelationship.getType().name();
    //Paths.pathToString(path, new PathPrinter());

    if (!lastRelationship.isType(DynamicRelationshipType.withName(attributeURI))) {

        return Evaluation.EXCLUDE_AND_PRUNE;
    }

    if (currentHierarchy < relativeAttributePathSizeAttributePathSize) {

        return Evaluation.EXCLUDE_AND_CONTINUE;
    }

    return Evaluation.INCLUDE_AND_PRUNE;
}
项目:dswarm-graph-neo4j    文件:BaseNeo4jHandler.java   
/**
 * TODO: refactor this to protected
 *
 * @param subjectNodeId
 * @param predicateURI
 * @param objectNodeId
 * @param optionalSubjectNodeType
 * @param optionalSubjectURI
 * @param optionalStatementUUID
 * @param optionalResourceUri
 * @param optionalQualifiedAttributes
 * @param hash
 * @return
 * @throws org.dswarm.graph.DMPGraphException
 */
public long addRelationship(final long subjectNodeId, final String predicateURI, final long objectNodeId,
                            final Optional<NodeType> optionalSubjectNodeType, final Optional<Long> optionalSubjectURI,
                            final Optional<String> optionalStatementUUID, final Optional<Long> optionalResourceUri,
                            final Optional<Map<String, Object>> optionalQualifiedAttributes, final long hash) throws DMPGraphException {

    final String finalStatementUUID;

    if (optionalStatementUUID.isPresent()) {

        finalStatementUUID = optionalStatementUUID.get();
    } else {

        finalStatementUUID = UUID.randomUUID().toString();
    }

    final Map<String, Object> relProperties = processor.prepareRelationship(finalStatementUUID, optionalQualifiedAttributes);

    addResourcePropertyToRelationship(subjectNodeId, relProperties, optionalSubjectNodeType, optionalSubjectURI, optionalResourceUri);

    final RelationshipType relType = DynamicRelationshipType.withName(predicateURI);

    final long relId = processor.getBatchInserter().createRelationship(subjectNodeId, objectNodeId, relType, relProperties);

    // TODO: for now we only keey the hash
    processor.addToStatementIndex(hash);
    processor.addStatementToIndex(relId, finalStatementUUID);

    addedRelationships++;

    return relId;
}
项目:dswarm-graph-neo4j    文件:BasicNeo4jProcessor.java   
public Relationship prepareRelationship(final Node subjectNode, final String predicateURI, final Node objectNode, final long statementUUID,
        final Optional<Map<String, Object>> optionalQualifiedAttributes, final Optional<Long> optionalIndex, final VersionHandler versionHandler) {

    final RelationshipType relType = DynamicRelationshipType.withName(predicateURI);
    final Relationship rel = subjectNode.createRelationshipTo(objectNode, relType);

    rel.setProperty(GraphStatics.UUID_PROPERTY, statementUUID);

    if (optionalQualifiedAttributes.isPresent()) {

        final Map<String, Object> qualifiedAttributes = optionalQualifiedAttributes.get();

        if (qualifiedAttributes.containsKey(GraphStatics.ORDER_PROPERTY)) {

            rel.setProperty(GraphStatics.ORDER_PROPERTY, qualifiedAttributes.get(GraphStatics.ORDER_PROPERTY));
        }

        if(optionalIndex.isPresent()) {

            rel.setProperty(GraphStatics.INDEX_PROPERTY, optionalIndex.get());
        } else if (qualifiedAttributes.containsKey(GraphStatics.INDEX_PROPERTY)) {

            rel.setProperty(GraphStatics.INDEX_PROPERTY, qualifiedAttributes.get(GraphStatics.INDEX_PROPERTY));
        }

        // TODO: versioning handling only implemented for data models right now

        if (qualifiedAttributes.containsKey(GraphStatics.EVIDENCE_PROPERTY)) {

            rel.setProperty(GraphStatics.EVIDENCE_PROPERTY, qualifiedAttributes.get(GraphStatics.EVIDENCE_PROPERTY));
        }

        if (qualifiedAttributes.containsKey(GraphStatics.CONFIDENCE_PROPERTY)) {

            rel.setProperty(GraphStatics.CONFIDENCE_PROPERTY, qualifiedAttributes.get(GraphStatics.CONFIDENCE_PROPERTY));
        }
    }

    return rel;
}
项目:mondo-hawk    文件:Neo4JNode.java   
public static RelationshipType getNewRelationshipType(final String name) {

        return DynamicRelationshipType.withName(name);

    }
项目:dswarm-graph-neo4j    文件:Neo4jDeltaGDMHandler.java   
private Relationship addRelationship(final Node subjectNode, final String predicateName, final Node objectNode,
        final Optional<Long> optionalResourceHash,
        final org.dswarm.graph.json.Node subject, final long resourceHash, final Long statementUUID, final Long order, final long index,
        final org.dswarm.graph.json.NodeType subjectNodeType, final org.dswarm.graph.json.NodeType objectNodeType) throws DMPGraphException {

    final StringBuilder sb = new StringBuilder();

    final String subjectIdentifier = getIdentifier(subjectNode, subjectNodeType);
    final String objectIdentifier = getIdentifier(objectNode, objectNodeType);

    sb.append(subjectNodeType.toString()).append(":").append(subjectIdentifier).append(" ").append(predicateName).append(" ")
            .append(objectNodeType.toString()).append(":").append(objectIdentifier).append(" ");

    final long hash = HashUtils.generateHash(sb.toString());

    final Relationship rel;

    final IndexHits<Relationship> hits = statementHashes.get(GraphStatics.HASH, hash);

    if (hits == null || !hits.hasNext()) {

        final RelationshipType relType = DynamicRelationshipType.withName(predicateName);
        rel = subjectNode.createRelationshipTo(objectNode, relType);

        final long finalStatementUUID;

        if (statementUUID == null) {

            finalStatementUUID = HashUtils.generateHash(UUID.randomUUID().toString());
        } else {

            finalStatementUUID = statementUUID;
        }

        rel.setProperty(GraphStatics.UUID_PROPERTY, finalStatementUUID);

        if (order != null) {

            rel.setProperty(GraphStatics.ORDER_PROPERTY, order);
        }

        rel.setProperty(GraphStatics.INDEX_PROPERTY, index);

        statementHashes.add(rel, GraphStatics.HASH, hash);
        statementUUIDs.add(rel, GraphStatics.UUID, finalStatementUUID);

        addedRelationships++;

        addResourceProperty(subjectNode, subject, rel, optionalResourceHash, resourceHash);
    } else {

        rel = hits.next();
    }

    if (hits != null) {

        hits.close();
    }

    return rel;
}