您的位置:首页 > 编程语言 > Java开发

java连接Neo4j服务器

2016-04-07 14:02 519 查看
一:Neo4j服务器安装(参考:http://docs.neo4j.org.cn/server-installation.html)

1.下载Neo4j数据,我下载的版本是: neo4j-enterprise-1.8.1-windows

2.解压 neo4j-enterprise-1.8.1-windows

3.到Neo4j的bin目录下neo4j-enterprise-1.8.1-windows\neo4j-enterprise-1.8.1\bin

4.运行 neo4j start 命令

5.打开 http://localhost:7474 看到图形化界面则安装成功!

二:测试代码(参考:http://www.neo4j.org.cn/2012/07/30/server-java-rest-client-example/)

测试代码总共有三个类:

CreateSimpleGraph.java 下载地址:https://github.com/neo4j/community/blob/1.8.M06/server-examples/src/main/java/org/neo4j/examples/server/CreateSimpleGraph.java

Relationship.java 下载地址:https://github.com/neo4j/community/blob/1.8.M06/server-examples/src/main/java/org/neo4j/examples/server/Relationship.java

TraversalDescription.java 下载地址:https://github.com/neo4j/community/blob/1.8.M06/server-examples/src/main/java/org/neo4j/examples/server/TraversalDescription.java

三:程序正常运行用到的jar包

1.neo4j-enterprise-1.8.1-windows\neo4j-enterprise-1.8.1\lib下所有jar包

2.自己下载的jar包

com.sun.jersey.jersey-core-1.4.0.jar

javax.ws.rs.jar

jersey-client-1.9.jar

四:程序代码

[java] view
plain copy

print?

package com.wzs.linux;

public class Relationship

{

public static final String OUT = "out";

public static final String IN = "in";

public static final String BOTH = "both";

private String type;

private String direction;

public String toJsonCollection()

{

StringBuilder sb = new StringBuilder();

sb.append("{ ");

sb.append(" \"type\" : \"" + type + "\"");

if (direction != null)

{

sb.append(", \"direction\" : \"" + direction + "\"");

}

sb.append(" }");

return sb.toString();

}

public Relationship(String type, String direction)

{

setType(type);

setDirection(direction);

}

public Relationship(String type)

{

this(type, null);

}

public void setType(String type)

{

this.type = type;

}

public void setDirection(String direction)

{

this.direction = direction;

}

}

[java] view
plain copy

print?

import java.net.URI;

import java.net.URISyntaxException;

import javax.ws.rs.core.MediaType;

import com.sun.jersey.api.client.Client;

import com.sun.jersey.api.client.ClientResponse;

import com.sun.jersey.api.client.WebResource;

public class CreateSimpleGraph

{

private static final String SERVER_ROOT_URI = "http://localhost:7474/db/data/";

public static void main( String[] args ) throws URISyntaxException

{

checkDatabaseIsRunning();

// START SNIPPET: nodesAndProps

URI firstNode = createNode();

addProperty( firstNode, "name", "Joe Strummer" );

URI secondNode = createNode();

addProperty( secondNode, "band", "The Clash" );

// END SNIPPET: nodesAndProps

// START SNIPPET: addRel

URI relationshipUri = addRelationship( firstNode, secondNode, "singer",

"{ \"from\" : \"1976\", \"until\" : \"1986\" }" );

// END SNIPPET: addRel

// START SNIPPET: addMetaToRel

addMetadataToProperty( relationshipUri, "stars", "5" );

// END SNIPPET: addMetaToRel

// START SNIPPET: queryForSingers

findSingersInBands( firstNode );

// END SNIPPET: queryForSingers

}

private static void findSingersInBands( URI startNode )

throws URISyntaxException

{

// START SNIPPET: traversalDesc

// TraversalDescription turns into JSON to send to the Server

TraversalDescription t = new TraversalDescription();

t.setOrder( TraversalDescription.DEPTH_FIRST );

t.setUniqueness( TraversalDescription.NODE );

t.setMaxDepth( 10 );

t.setReturnFilter( TraversalDescription.ALL );

t.setRelationships( new Relationship( "singer", Relationship.OUT ) );

// END SNIPPET: traversalDesc

// START SNIPPET: traverse

URI traverserUri = new URI( startNode.toString() + "/traverse/node" );

WebResource resource = Client.create()

.resource( traverserUri );

String jsonTraverserPayload = t.toJson();

ClientResponse response = resource.accept( MediaType.APPLICATION_JSON )

.type( MediaType.APPLICATION_JSON )

.entity( jsonTraverserPayload )

.post( ClientResponse.class );

System.out.println( String.format(

"POST [%s] to [%s], status code [%d], returned data: "

+ System.getProperty( "line.separator" ) + "%s",

jsonTraverserPayload, traverserUri, response.getStatus(),

response.getEntity( String.class ) ) );

response.close();

// END SNIPPET: traverse

}

// START SNIPPET: insideAddMetaToProp

private static void addMetadataToProperty( URI relationshipUri,

String name, String value ) throws URISyntaxException

{

URI propertyUri = new URI( relationshipUri.toString() + "/properties" );

String entity = toJsonNameValuePairCollection( name, value );

WebResource resource = Client.create()

.resource( propertyUri );

ClientResponse response = resource.accept( MediaType.APPLICATION_JSON )

.type( MediaType.APPLICATION_JSON )

.entity( entity )

.put( ClientResponse.class );

System.out.println( String.format(

"PUT [%s] to [%s], status code [%d]", entity, propertyUri,

response.getStatus() ) );

response.close();

}

// END SNIPPET: insideAddMetaToProp

private static String toJsonNameValuePairCollection( String name,

String value )

{

return String.format( "{ \"%s\" : \"%s\" }", name, value );

}

private static URI createNode()

{

// START SNIPPET: createNode

final String nodeEntryPointUri = SERVER_ROOT_URI + "node";

// http://localhost:7474/db/data/node
WebResource resource = Client.create()

.resource( nodeEntryPointUri );

// POST {} to the node entry point URI

ClientResponse response = resource.accept( MediaType.APPLICATION_JSON )

.type( MediaType.APPLICATION_JSON )

.entity( "{}" )

.post( ClientResponse.class );

final URI location = response.getLocation();

System.out.println( String.format(

"POST to [%s], status code [%d], location header [%s]",

nodeEntryPointUri, response.getStatus(), location.toString() ) );

response.close();

return location;

// END SNIPPET: createNode

}

// START SNIPPET: insideAddRel

private static URI addRelationship( URI startNode, URI endNode,

String relationshipType, String jsonAttributes )

throws URISyntaxException

{

URI fromUri = new URI( startNode.toString() + "/relationships" );

String relationshipJson = generateJsonRelationship( endNode,

relationshipType, jsonAttributes );

WebResource resource = Client.create()

.resource( fromUri );

// POST JSON to the relationships URI

ClientResponse response = resource.accept( MediaType.APPLICATION_JSON )

.type( MediaType.APPLICATION_JSON )

.entity( relationshipJson )

.post( ClientResponse.class );

final URI location = response.getLocation();

System.out.println( String.format(

"POST to [%s], status code [%d], location header [%s]",

fromUri, response.getStatus(), location.toString() ) );

response.close();

return location;

}

// END SNIPPET: insideAddRel

private static String generateJsonRelationship( URI endNode,

String relationshipType, String... jsonAttributes )

{

StringBuilder sb = new StringBuilder();

sb.append( "{ \"to\" : \"" );

sb.append( endNode.toString() );

sb.append( "\", " );

sb.append( "\"type\" : \"" );

sb.append( relationshipType );

if ( jsonAttributes == null || jsonAttributes.length < 1 )

{

sb.append( "\"" );

}

else

{

sb.append( "\", \"data\" : " );

for ( int i = 0; i < jsonAttributes.length; i++ )

{

sb.append( jsonAttributes[i] );

if ( i < jsonAttributes.length - 1 )

{ // Miss off the final comma

sb.append( ", " );

}

}

}

sb.append( " }" );

return sb.toString();

}

private static void addProperty( URI nodeUri, String propertyName,

String propertyValue )

{

// START SNIPPET: addProp

String propertyUri = nodeUri.toString() + "/properties/" + propertyName;

// http://localhost:7474/db/data/node/{node_id}/properties/{property_name}
WebResource resource = Client.create()

.resource( propertyUri );

ClientResponse response = resource.accept( MediaType.APPLICATION_JSON )

.type( MediaType.APPLICATION_JSON )

.entity( "\"" + propertyValue + "\"" )

.put( ClientResponse.class );

System.out.println( String.format( "PUT to [%s], status code [%d]",

propertyUri, response.getStatus() ) );

response.close();

// END SNIPPET: addProp

}

private static void checkDatabaseIsRunning()

{

// START SNIPPET: checkServer

WebResource resource = Client.create()

.resource( SERVER_ROOT_URI );

ClientResponse response = resource.get( ClientResponse.class );

System.out.println( String.format( "GET on [%s], status code [%d]",

SERVER_ROOT_URI, response.getStatus() ) );

response.close();

// END SNIPPET: checkServer

}

}

[java] view
plain copy

print?

import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

public class TraversalDescription

{

public static final String DEPTH_FIRST = "depth first";

public static final String NODE = "node";

public static final String ALL = "all";

private String uniqueness = NODE;

private int maxDepth = 1;

private String returnFilter = ALL;

private String order = DEPTH_FIRST;

private List<Relationship> relationships = new ArrayList<Relationship>();

public void setOrder( String order )

{

this.order = order;

}

public void setUniqueness( String uniqueness )

{

this.uniqueness = uniqueness;

}

public void setMaxDepth( int maxDepth )

{

this.maxDepth = maxDepth;

}

public void setReturnFilter( String returnFilter )

{

this.returnFilter = returnFilter;

}

public void setRelationships( Relationship... relationships )

{

this.relationships = Arrays.asList( relationships );

}

public String toJson()

{

StringBuilder sb = new StringBuilder();

sb.append( "{ " );

sb.append( " \"order\" : \"" + order + "\"" );

sb.append( ", " );

sb.append( " \"uniqueness\" : \"" + uniqueness + "\"" );

sb.append( ", " );

if ( relationships.size() > 0 )

{

sb.append( "\"relationships\" : [" );

for ( int i = 0; i < relationships.size(); i++ )

{

sb.append( relationships.get( i )

.toJsonCollection() );

if ( i < relationships.size() - 1 )

{ // Miss off the final comma

sb.append( ", " );

}

}

sb.append( "], " );

}

sb.append( "\"return filter\" : { " );

sb.append( "\"language\" : \"builtin\", " );

sb.append( "\"name\" : \"" );

sb.append( returnFilter );

sb.append( "\" }, " );

sb.append( "\"max depth\" : " );

sb.append( maxDepth );

sb.append( " }" );

return sb.toString();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: