`

Neo4j: Get Json Parameters in Extentions with Spring Data Neo4j

阅读更多

I want to write a extention to provide REST API for client to add a new user to Neo4j database, which I also use Spring Data Neo4j to OGM.  Client just sends a josn post to the extention, and just get a simple status result.

 

1. Create a maven project in eclipse  with  pom.xml  to manage related dependencies

 

2. Create Modle

package com.fadeinfadeout.modle;

import java.util.HashSet;
import java.util.Set;

import javax.xml.bind.annotation.XmlRootElement;
import org.codehaus.jackson.annotate.JsonAutoDetect;
import org.neo4j.graphdb.Direction;
import org.springframework.data.neo4j.annotation.GraphId;
import org.springframework.data.neo4j.annotation.Indexed;
import org.springframework.data.neo4j.annotation.NodeEntity;
import org.springframework.data.neo4j.annotation.RelatedTo;


 
@NodeEntity
@XmlRootElement
@JsonAutoDetect
public class User {
    private String name;

    @Indexed(unique = true)
    private String userId;

    private String phoneNumber;

    @GraphId
    private Long nodeId;
    
    @RelatedTo(type = "IS_FRIEND_OF", direction = Direction.BOTH)
    private Set<User> friends;

    public User() {
 
    }

    public User(String userId, String name, String phoneNumber) {
	this.userId = userId;
	this.name = name;
	this.phoneNumber = phoneNumber;
    }

    public Long getNodeId() {
        return nodeId;
    }

    public void setNodeId(Long nodeId) {
        this.nodeId = nodeId;
    }

    public String getName() {
	return name;
    }

    public void setName(String name) {
	this.name = name;
    }

    public String getUserId() {
	return userId;
    }

    public void setUserId(String userId) {
	this.userId = userId;
    }

    public String getPhoneNumber() {
	return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
	this.phoneNumber = phoneNumber;
    }

    public Set<User> getFriends() {
	return friends;
    }

    public void setFriends(Set<User> friends) {
	this.friends = friends;
    }

    public void addFriends(User friend) {
	if (friends == null)
	    friends = new HashSet<User>();

	friends.add(friend);
    }
    
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        User user = (User) o;

        if (nodeId != null ? !nodeId.equals(user.nodeId) : user.nodeId != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        return nodeId != null ? nodeId.hashCode() : 0;
    }
    
    public String toString(){
	return "userId="+this.userId +"\tname="+this.name+"\tpN="+this.phoneNumber;
    }

}

 

In order to using auto json wired in jersey(which is a Restful framework embeded in Neo4j to provide Remote access), you should anotate the mode class with

@XmlRootElement
@JsonAutoDetect

 

and  add dependencies in pom.xml

<dependency>
		<groupId>com.sun.jersey</groupId>
		<artifactId>jersey-json</artifactId>
		<version>1.9</version>
		<exclusions>
			<exclusion>
				<artifactId>jackson-core-asl</artifactId>
				<groupId>org.codehaus.jackson</groupId>
			</exclusion>
			<exclusion>
				<artifactId>jackson-jaxrs</artifactId>
				<groupId>org.codehaus.jackson</groupId>
			</exclusion>
			<exclusion>
				<artifactId>jersey-core</artifactId>
				<groupId>com.sun.jersey</groupId>
			</exclusion>
		</exclusions>
</dependency>

 

3. Create a spring data neo4j  repository to operate  User

package com.fadeinfadeout.repository;

import org.springframework.data.neo4j.annotation.Query;
import org.springframework.data.neo4j.repository.GraphRepository;

import com.fadeinfadeout.modle.User;

public interface UserRepository extends GraphRepository<User> {

    @Query(value = 
	    "match (n)-[r:IS_FRIEND_OF]-(friend)-[r2:IS_FRIEND_OF]-(fof) " +
		    "where n.userId) = {0} " + 
		    "return distinct fof")
    Iterable<User> getFriendsOfFriends(String userId);
}

 

4. Inorder to use SDN in Neo4j unmanaged extentions, We should inite SDN with SpringPluginInitializer

package com.fadeinfadeout.plugins;

import java.util.Collection;
import java.util.logging.Logger;

import org.apache.commons.configuration.Configuration;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.server.plugins.Injectable;
import org.springframework.data.neo4j.server.SpringPluginInitializer;
import org.springframework.data.neo4j.support.Neo4jTemplate;
import org.springframework.util.Assert;

import com.fadeinfadeout.repository.UserRepository;

public class FadeinFadeoutNeo4jPluginInitializer extends SpringPluginInitializer{
    private static final Logger logger = Logger.getLogger(FadeinFadeoutNeo4jPluginInitializer.class.getName());

    @SuppressWarnings("unchecked")
    public FadeinFadeoutNeo4jPluginInitializer() {
	super(new String[] { "META-INF/spring/application-context.xml" },
		expose("neo4jTemplate", Neo4jTemplate.class), 
		expose("userRepository", UserRepository.class));
   }
    
}

 

This  class is aimed to initialize  SDN and expose  Beans which could be used in extentions

The  full-qualified class name should be placed in file org.neo4j.server.plugins.PluginLifecycle  which located at

src/main/resources/MATA-INF/services dir.     When start neo4j server,  neo4j will pick the file and scan its contnets, then initialize related classes.

 

 

5.Create a Unmanaged Extentions to provide clients User operation API

 

package com.fadeinfadeout.unmanagedext;

import java.util.logging.Logger;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import com.fadeinfadeout.modle.User;
import com.fadeinfadeout.plugins.FadeinFadeoutNeo4jPluginInitializer;
import com.fadeinfadeout.repository.UserRepository;

@Path("/user")
public class UserCtrollerUnmanagedExt {
    private static final String ERROR_MSG = "{Result:[error]}";
    private static final String OK_MSG = "{Result:[OK]}";
    private static final Logger logger = Logger.getLogger(UserCtrollerUnmanagedExt.class.getName());

    @Context
    private UserRepository userRepo;

    @Path("/addUser")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public Response addUser(User user) {
	String userId = null;
	String name = null;
	String phoneNumber = null;

	userId = user.getUserId();
	name = user.getName();
	phoneNumber = user.getPhoneNumber();

	logger.info("Json user paramerters : " + user.toString());
	
	if (userId == null || name == null || phoneNumber == null) {
	    return Response.status(Status.NOT_ACCEPTABLE).entity(ERROR_MSG).build();
	}
	// User newUser = new User(userId, name, phoneNumber);
	 userRepo.saveOnly(user);

	return Response.status(Status.OK).entity(OK_MSG).build();
    }

}

 

To let neo4j knows the extention, you should configure it in  conf/neo4j-server.properties

 

org.neo4j.server.thirdparty_jaxrs_classes=com.fadeinfadeout=/fifo

 

Your client can use the following path to access the extention

 

curl -i -H 'content-type: application/json' -X POST 
-d '{"userId":"1","name":"zhaohj","phoneNumber":"18190752251"}'
 htt:7474/fifo/user/addUser

 

 

6. Integrate SDN in Neo4j, you should  configure dependencies in pom.xml. the following sinppets are some important dependencies

 

<dependency>
	<groupId>org.springframework.data</groupId>
	<artifactId>spring-data-neo4j-aspects</artifactId>
	<version>${neo4j.springdata.version}</version>
	<exclusions>
		<exclusion>
			<groupId>org.neo4j</groupId>
			<artifactId>neo4j-kernel</artifactId>
		</exclusion>
		<exclusion>
			<groupId>org.neo4j</groupId>
			<artifactId>neo4j</artifactId>
		</exclusion>
		<exclusion>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
		</exclusion>
		<exclusion>
			<groupId>org.aspectj</groupId>
			<artifactId>*</artifactId>
		</exclusion>

		<exclusion>
			<artifactId>geronimo-jta_1.1_spec</artifactId>
			<groupId>org.apache.geronimo.specs</groupId>
		</exclusion>
	</exclusions>
</dependency>

 

Note: 

A:Due to transitive dependices, some jars are provided by Neo4j in  lib and system/lib dir. So, you should exclude these jars from pom.xml

 

B:Because many spring jars include some meta data file in META-INF/ dir, when you build the final jar, you should merge these meta file using  maven shade plugin, otherwise some schema Handler can't found when start neo4j server

 

<build>
 <pluginManagement>
  <plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-shade-plugin</artifactId>
	<version>2.3</version>
	<executions>
		<execution>
		<phase>package</phase>
		<goals>
			<goal>shade</goal>
	        </goals>
		<configuration>
		      <transformers>
				<transformer
					implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
					<resource>META-INF/spring.handlers</resource>
				</transformer>
				<transformer
					implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
					<resource>META-INF/spring.schemas</resource>
				</transformer>
				<transformer
					implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
					<resource>META-INF/spring.tooling</resource>
				</transformer>
				<transformer
					implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
					<resource>META-INF/spring.factories</resource>
				</transformer>
				<transformer
					implementation="org.apache.maven.plugins.shade.resource.ComponentsXmlResourceTransformer" />
				<transformer
					implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
			</transformers>
		</configuration>
	</execution>
      </executions>
     </plugin>

    </plugins>
   </pluginManagement>
   <plugins>
      <plugin>
	<groupId>org.apache.maven.plugins</groupId>
		<artifactId>maven-shade-plugin</artifactId>
      </plugin>
   </plugins>
</build>

 

 

The configure SDN, you should put the SDN configuration file application-context.conf in     src/main/resoureces/MATA-INF/spring

 

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:neo4j="http://www.springframework.org/schema/data/neo4j"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd
            http://www.springframework.org/schema/data/neo4j
            http://www.springframework.org/schema/data/neo4j/spring-neo4j.xsd">


	<context:annotation-config />
	<context:spring-configured />
	<context:component-scan base-package="com.fadeinfadeout">
	</context:component-scan>
	<neo4j:config id="graphDatabaseService"
		storeDirectory="/home/zhaohj/hadoop/neo4j-community-2.1.7/data/graph.db"
		base-package="com.fadeinfadeout.modle" graphDatabaseService="graphDatabaseService" />

	<!-- Instructs Spring Data where to look for repository implementations -->
	<neo4j:repositories base-package="com.fadeinfadeout.repository" />
	<tx:annotation-driven mode="aspectj" />

</beans>

 

The final project dirs likes



 

 

 

 

 

References

https://jersey.java.net/documentation/1.9/json.html

https://inserpio.wordpress.com/2014/04/30/extending-the-neo4j-server-with-spring-data-neo4j/

http://neo4j.com/docs/stable/server-unmanaged-extensions.html

https://github.com/AtomRain/neo4j-extensions

http://docs.spring.io/spring-data/neo4j/docs/3.0.0.RELEASE/reference/html/reference_neo4j-server.html

http://examples.javacodegeeks.com/enterprise-java/rest/jersey/json-example-with-jersey-jackson/

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 大小: 51.4 KB
分享到:
评论

相关推荐

    movies-java-spring-data-neo4j:使用Spring Data Neo4j的Neo4j电影示例

    电影示例应用 如何一起使用Spring Boot,Spring Data和Neo4j。 Spring Data Neo4j可以在基于Spring的应用程序中方便地集成Neo4j。 它提供了对象图映射(OGM)功能以及Spring Data项目共有的其他功能。 笔记该项目...

    spring data Neo4j 整合demo

    spring data Neo4j 整合demo,基本整合案例,详细细节参考https://docs.spring.io/spring-data/neo4j/docs/5.1.3.RELEASE/reference/html

    vue-neo4j:vue使用D3对neo4 j进行可视化-源码开发技术-其它

    Neo4j Vue 安装步骤 克隆或下载该库到本地 下载neo4j并安装到本地,启动neo4j服务 进入到该工程的根目录,输入命令:npm run update进行npm包的导入 使用命令:npm run dev启动该工程 默认端口是:8081 neo4j账号...

    Spring Data Neo4j API(Spring Data Neo4j 开发文档).CHM

    官网 Spring Data Neo4j API。 Spring Data Neo4j 开发文档。 Spring Data Neo4j API

    neo4j整合spring data文档

    标题"neo4j整合spring data文档"指出我们要探讨的主题是关于将图数据库Neo4j与Spring Data框架集成的实践方法。Spring Data是一个强大的框架,旨在简化数据访问层的开发,它支持多种数据库,包括关系型数据库和非...

    vue-neo4j:vue使用D3对neo4j进行可视化源码开发技术-其它

    Neo4j Vue 安装步骤 克隆或下载该库到本地 下载neo4j并安装到本地,启动neo4j服务 进入到该工程的根目录,输入命令:npm run update进行npm包的导入 使用命令:npm run dev启动该工程 默认端口是:8081 neo4j账号...

    Spring Data:Spring Data Modern Data Access for Enterprise Java

    7. Neo4j: A Graph Database 8. Redis: A Key/Value Store Part IV. Rapid Application Development 9. Persistence Layers with Spring Roo 10. REST Repository Exporter Part V. Big Data 11. Spring for Apache ...

    Beginning.Neo4j.1484212

    With example data models, best practices, and an application putting everything together, this book will give you everything you need to really get started with Neo4j. Neo4j is being used by social ...

    vue-neo4j:vue使用D3对neo4j进行可视化

    Neo4j Vue安装步骤克隆或下载该库到本地下载neo4j并安装到本地,启动neo4j服务进入到该工程的根目录,输入命令:npm run update进行npm包的导入使用命令:npm run dev启动该工程默认端口是:8081 neo4j账号信息: ...

    sails-restful-neo4j:SailsWaterline RESTful Neo4j 适配器

    connections = { default : 'restful-neo4j' , restful - neo4j : { module : 'sails-restful-neo4j' , type : 'json' , // expected response type (json | string | http) host : 'foo.myneo4j.com' , //

    spring-data-neo4j

    ### Spring Data Neo4j 关键知识点解析 #### 一、Spring与Spring Data Spring Data Neo4j 是基于Spring框架和Spring Data项目构建的,旨在简化Neo4j图数据库的访问和操作。Spring Data Neo4j提供了对Neo4j的集成...

    neo4j-jdbc:带有BOLT协议的Neo4j 3.x的Neo4j JDBC驱动程序

    该驱动程序支持各种类型的数据库传输: 通过使用jdbc:neo4j:bolt://&lt;host&gt;:&lt;port&gt;/的Bolt协议(3.0.x至3.2.x) 通过使用jdbc:neo4j:http://&lt;host&gt;:&lt;port&gt;/的HTTP协议(2.x +) 展望未来,还将支持: 直接文件连接...

    spring-data-neo4j-4.0官方开发手册

    Spring Data Neo4j是Spring Data项目的一个模块,用于简化在Neo4j图数据库上的数据访问。Spring Data Neo4j 4.0版本相较于早期版本有了显著变化,提供了新的特性、改进和增强。本文档是Spring Data Neo4j 4.0的官方...

    spring-neo4j:Spring Boot中的Neo4j

    spring.data.neo4j.username=neo4j spring.data.neo4j.password=my_password ``` **四、定义实体类** 在Neo4j中,实体通常表示为节点或关系。在Spring Data Neo4j(SDN)中,你可以使用注解来定义这些实体。例如,...

    spring-graph-neo4j:Neo4j的春天

    标题中的“spring-graph-neo4j:Neo4j的春天”暗示了我们将探讨Spring框架与图数据库Neo4j的结合使用。在Java开发领域,Spring框架是一个广泛使用的开源框架,它提供了一整套用于构建企业级应用的服务和工具。而Neo4j...

    spring-data-neo4j-master.zip

    《Spring Data Neo4j深度解析》 Spring Data Neo4j(SDN)是Spring框架的一个扩展,它为使用Neo4j图形数据库提供了便利。这个压缩包"spring-data-neo4j-master.zip"包含了完整的源码,是研究和开发基于Spring Data ...

    Neo4j-spring-data数据库例子

    Spring Data Neo4j是Spring Data项目的一部分,它提供了一种简单的方式来与Neo4j集成,使得在Java应用中操作图形数据库变得轻松。这个例子展示了如何利用Spring Data Neo4j在Spring框架下进行数据存取操作。 首先,...

    neo4j-community-3.5.12-windows.zip

    **Neo4J社区版3.5.12 Windows安装与使用指南** Neo4J是一款流行的图数据库管理系统,尤其适用于处理复杂关系数据。图数据库利用图形结构来存储和查询数据,其核心理念是节点、边(关系)和属性,这使得在处理网络、...

    spring-security-acl-neo4j:带有 Neo4j 图形数据库的 Spring Security Acl 支持库

    spring-security-acl-neo4j 带有 Neo4j 图形数据库的 Spring Security Acl 支持库动机该项目背后的动机是通过消除使用传统 RDBMS 作为后端数据存储创建的瓶颈来提高 Spring Security ACL 的性能。 阅读这篇了解更多...

    neo4j-for-springdata-master.zip

    本项目"neo4j-for-springdata-master.zip"显然是一个关于如何在Spring Boot应用中使用Spring Data Neo4j进行基本的创建(Create)、读取(Read)、更新(Update)和删除(Delete)操作的示例。 首先,让我们深入...

Global site tag (gtag.js) - Google Analytics