Spring Boot集成olingo快速入门demo

1.什么是olingo?

Apache Olingo 是个 Java 库,用来实现 Open Data Protocol (OData)。 Apache Olingo 包括服务客户端和 OData 服务器方面。

Open Data Protocol (开放数据协议,OData)

是用来查询和更新数据的一种Web协议,其提供了把存在于应用程序中的数据暴露出来的方式。OData运用且构建于很多 Web技术之上,比如HTTP、Atom Publishing Protocol(AtomPub)和JSON,提供了从各种应用程序、服务和存储库中访问信息的能力。OData被用来从各种数据源中暴露和访问信息, 这些数据源包括但不限于:关系数据库、文件系统、内容管理系统和传统Web站点。

2.代码工程

实验目标

利用olingo实现oData协议

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><parent><artifactId>springboot-demo</artifactId><groupId>com.et</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>olingo</artifactId><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-autoconfigure</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>org.apache.olingo</groupId><artifactId>olingo-odata2-core</artifactId><version>2.0.11</version><exclusions><exclusion><groupId>javax.ws.rs</groupId><artifactId>javax.ws.rs-api</artifactId></exclusion></exclusions></dependency><dependency><groupId>org.apache.olingo</groupId><artifactId>olingo-odata2-jpa-processor-core</artifactId><version>2.0.11</version></dependency><dependency><groupId>org.apache.olingo</groupId><artifactId>olingo-odata2-jpa-processor-ref</artifactId><version>2.0.11</version><exclusions><exclusion><groupId>org.eclipse.persistence</groupId><artifactId>eclipselink</artifactId></exclusion></exclusions></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jersey</artifactId></dependency></dependencies><profiles><profile><id>local</id><activation><activeByDefault>true</activeByDefault></activation><properties><activatedProperties>local</activatedProperties></properties><dependencies><dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><scope>runtime</scope></dependency></dependencies></profile><profile><id>cloud</id><activation><activeByDefault>false</activeByDefault></activation><properties><activatedProperties>cloud</activatedProperties></properties></profile></profiles><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>

config

package com.et.olingo.config;import com.et.olingo.service.OdataJpaServiceFactory;
import org.apache.olingo.odata2.api.ODataServiceFactory;
import org.apache.olingo.odata2.core.rest.ODataRootLocator;
import org.apache.olingo.odata2.core.rest.app.ODataApplication;
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.stereotype.Component;import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.Path;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.Context;
import javax.ws.rs.ext.Provider;
import java.io.IOException;@Component
@ApplicationPath("/odata")
public class JerseyConfig extends ResourceConfig {public JerseyConfig(OdataJpaServiceFactory serviceFactory, EntityManagerFactory entityManagerFactory) {ODataApplication oDataApplication = new ODataApplication();oDataApplication.getClasses().forEach( c -> {if ( !ODataRootLocator.class.isAssignableFrom(c)) {register(c);}});register(new ODataServiceRootLocator(serviceFactory));register(new EntityManagerFilter(entityManagerFactory));}@Path("/")public static class ODataServiceRootLocator extends ODataRootLocator {private OdataJpaServiceFactory serviceFactory;@Injectpublic ODataServiceRootLocator (OdataJpaServiceFactory serviceFactory) {this.serviceFactory = serviceFactory;}@Overridepublic ODataServiceFactory getServiceFactory() {return this.serviceFactory;}}@Providerpublic static class EntityManagerFilter implements ContainerRequestFilter,ContainerResponseFilter {public static final String EM_REQUEST_ATTRIBUTE =EntityManagerFilter.class.getName() + "_ENTITY_MANAGER";private final EntityManagerFactory entityManagerFactory;@Contextprivate HttpServletRequest httpRequest;public EntityManagerFilter(EntityManagerFactory entityManagerFactory) {this.entityManagerFactory = entityManagerFactory;}@Overridepublic void filter(ContainerRequestContext containerRequestContext) throws IOException {EntityManager entityManager = this.entityManagerFactory.createEntityManager();httpRequest.setAttribute(EM_REQUEST_ATTRIBUTE, entityManager);if (!"GET".equalsIgnoreCase(containerRequestContext.getMethod())) {entityManager.getTransaction().begin();}}@Overridepublic void filter(ContainerRequestContext requestContext,ContainerResponseContext responseContext) throws IOException {EntityManager entityManager = (EntityManager) httpRequest.getAttribute(EM_REQUEST_ATTRIBUTE);if (!"GET".equalsIgnoreCase(requestContext.getMethod())) {EntityTransaction entityTransaction = entityManager.getTransaction(); //we do not commit because it's just a READif (entityTransaction.isActive() && !entityTransaction.getRollbackOnly()) {entityTransaction.commit();}}entityManager.close();}}}

controller

package com.et.olingo.controller;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.HashMap;
import java.util.Map;@RestController
public class HelloWorldController {@RequestMapping("/hello")public Map<String, Object> showHelloWorld(){Map<String, Object> map = new HashMap<>();map.put("msg", "HelloWorld");return map;}
}

entity

138327882-76404655-f383-46e6-82af-677560b5ccee

service

package com.et.olingo.service;import com.et.olingo.entity.Child;
import org.apache.olingo.odata2.api.edm.EdmException;
import org.apache.olingo.odata2.api.ep.EntityProviderException;
import org.apache.olingo.odata2.api.exception.ODataException;
import org.apache.olingo.odata2.api.exception.ODataNotFoundException;
import org.apache.olingo.odata2.api.processor.ODataResponse;
import org.apache.olingo.odata2.api.uri.info.*;
import org.apache.olingo.odata2.jpa.processor.api.ODataJPAContext;
import org.apache.olingo.odata2.jpa.processor.api.ODataJPADefaultProcessor;
import org.apache.olingo.odata2.jpa.processor.api.exception.ODataJPAModelException;
import org.apache.olingo.odata2.jpa.processor.api.exception.ODataJPARuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.io.InputStream;
import java.util.List;public class CustomODataJpaProcessor extends ODataJPADefaultProcessor {private Logger logger = LoggerFactory.getLogger(getClass());public CustomODataJpaProcessor(ODataJPAContext oDataJPAContext) {super(oDataJPAContext);}@Overridepublic ODataResponse readEntitySet(final GetEntitySetUriInfo uriParserResultView, final String contentType) throws ODataJPAModelException, ODataJPARuntimeException, EdmException {logger.info("READ: Entity Set {} called", uriParserResultView.getTargetEntitySet().getName());try {List<Object> jpaEntities = jpaProcessor.process(uriParserResultView);return responseBuilder.build(uriParserResultView, jpaEntities, contentType);} finally {this.close();}}@Overridepublic ODataResponse readEntity(final GetEntityUriInfo uriParserResultView, final String contentType) throws ODataJPAModelException, ODataJPARuntimeException, ODataNotFoundException, EdmException {ODataResponse response = null;if (uriParserResultView.getKeyPredicates().size() > 1) {logger.info("READ: Entity {} called with key {} and key {}", uriParserResultView.getTargetEntitySet().getName(), uriParserResultView.getKeyPredicates().get(0).getLiteral(), uriParserResultView.getKeyPredicates().get(1).getLiteral());} else {logger.info("READ: Entity {} called with key {}", uriParserResultView.getTargetEntitySet().getName(), uriParserResultView.getKeyPredicates().get(0).getLiteral());}try {Object readEntity = jpaProcessor.process(uriParserResultView);response = responseBuilder.build(uriParserResultView, readEntity, contentType);} finally {this.close();}return response;}@Overridepublic ODataResponse createEntity(final PostUriInfo uriParserResultView, final InputStream content, final String requestContentType, final String contentType) throws ODataJPAModelException, ODataJPARuntimeException, ODataNotFoundException, EdmException, EntityProviderException {logger.info("POST: Entity {} called", uriParserResultView.getTargetEntitySet().getName());ODataResponse response = null;try {Object createdEntity = jpaProcessor.process(uriParserResultView, content, requestContentType);if (createdEntity.getClass().equals(Child.class)) {response = postProcessCreateChild(createdEntity, uriParserResultView, contentType);} else {response = responseBuilder.build(uriParserResultView, createdEntity, contentType);}} finally {this.close();}return response;}@Overridepublic ODataResponse updateEntity(final PutMergePatchUriInfo uriParserResultView, final InputStream content,final String requestContentType, final boolean merge, final String contentType) throws ODataException, ODataJPAModelException, ODataJPARuntimeException, ODataNotFoundException {logger.info("PUT: Entity {} called with key {}", uriParserResultView.getTargetEntitySet().getName(), uriParserResultView.getKeyPredicates().get(0).getLiteral());ODataResponse response = null;try {Object updatedEntity = jpaProcessor.process(uriParserResultView, content, requestContentType);response = responseBuilder.build(uriParserResultView, updatedEntity);} finally {this.close();}return response;}@Overridepublic ODataResponse deleteEntity(DeleteUriInfo uriParserResultView, String contentType) throws ODataException {logger.info("DELETE: Entity {} called with key {}", uriParserResultView.getTargetEntitySet().getName(), uriParserResultView.getKeyPredicates().get(0).getLiteral());ODataResponse oDataResponse = null;try {this.oDataJPAContext.setODataContext(this.getContext());Object deletedEntity = this.jpaProcessor.process(uriParserResultView, contentType);oDataResponse = this.responseBuilder.build(uriParserResultView, deletedEntity);} finally {this.close();}return oDataResponse;}private ODataResponse postProcessCreateChild(Object createdEntity, PostUriInfo uriParserResultView, String contentType) throws ODataJPARuntimeException, ODataNotFoundException {Child child = (Child) createdEntity;if (child.getSurname() == null || child.getSurname().equalsIgnoreCase("")) {if (child.getMother().getSurname() != null && !child.getMother().getSurname().equalsIgnoreCase("")) {child.setSurname(child.getMother().getSurname());} else if (child.getMother().getSurname() != null && !child.getFather().getSurname().equalsIgnoreCase("")) {child.setSurname(child.getFather().getSurname());} else {child.setSurname("Gashi");}}return responseBuilder.build(uriParserResultView, createdEntity, contentType);}}
package com.et.olingo.service;import com.et.olingo.config.JerseyConfig;
import org.apache.olingo.odata2.api.ODataService;
import org.apache.olingo.odata2.api.ODataServiceFactory;
import org.apache.olingo.odata2.api.edm.provider.EdmProvider;
import org.apache.olingo.odata2.api.exception.ODataException;
import org.apache.olingo.odata2.api.processor.ODataContext;
import org.apache.olingo.odata2.api.processor.ODataSingleProcessor;
import org.apache.olingo.odata2.jpa.processor.api.ODataJPAContext;
import org.apache.olingo.odata2.jpa.processor.api.exception.ODataJPARuntimeException;
import org.apache.olingo.odata2.jpa.processor.api.factory.ODataJPAAccessFactory;
import org.apache.olingo.odata2.jpa.processor.api.factory.ODataJPAFactory;import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;public class CustomODataServiceFactory extends ODataServiceFactory {private ODataJPAContext oDataJPAContext;private ODataContext oDataContext;@Overridepublic final ODataService createService(final ODataContext context) throws ODataException {oDataContext = context;oDataJPAContext = initializeODataJPAContext();validatePreConditions();ODataJPAFactory factory = ODataJPAFactory.createFactory();ODataJPAAccessFactory accessFactory = factory.getODataJPAAccessFactory();if (oDataJPAContext.getODataContext() == null) {oDataJPAContext.setODataContext(context);}ODataSingleProcessor oDataSingleProcessor = new CustomODataJpaProcessor(oDataJPAContext);EdmProvider edmProvider = accessFactory.createJPAEdmProvider(oDataJPAContext);return createODataSingleProcessorService(edmProvider, oDataSingleProcessor);}private void validatePreConditions() throws ODataJPARuntimeException {if (oDataJPAContext.getEntityManager() == null) {throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.ENTITY_MANAGER_NOT_INITIALIZED, null);}}public final ODataJPAContext getODataJPAContext()throws ODataJPARuntimeException {if (oDataJPAContext == null) {oDataJPAContext = ODataJPAFactory.createFactory().getODataJPAAccessFactory().createODataJPAContext();}if (oDataContext != null)oDataJPAContext.setODataContext(oDataContext);return oDataJPAContext;}protected ODataJPAContext initializeODataJPAContext() throws ODataJPARuntimeException {ODataJPAContext oDataJPAContext = this.getODataJPAContext();ODataContext oDataContext = oDataJPAContext.getODataContext();HttpServletRequest request = (HttpServletRequest) oDataContext.getParameter(ODataContext.HTTP_SERVLET_REQUEST_OBJECT);EntityManager entityManager = (EntityManager) request.getAttribute(JerseyConfig.EntityManagerFilter.EM_REQUEST_ATTRIBUTE);oDataJPAContext.setEntityManager(entityManager);oDataJPAContext.setPersistenceUnitName("default");oDataJPAContext.setContainerManaged(true);return oDataJPAContext;}
}
package com.et.olingo.service;import org.springframework.stereotype.Component;@Component
public class OdataJpaServiceFactory extends CustomODataServiceFactory {//need this wrapper class for the spring framework, otherwise we face issues when auto wiring directly the CustomODataServiceFactory
}

application.yaml

spring.h2.console.enabled=true
spring.h2.console.path=/console

以上只是一些关键代码,所有代码请参见下面代码仓库

代码仓库

  • GitHub - Harries/springboot-demo: a simple springboot demo with some components for example: redis,solr,rockmq and so on.

3.测试

启动spring Boot应用

元数据查看

http://localhost:8080/odata/$metadata

138900236-f6ba4cca-c3e4-49ea-97c3-e80e5835aa7d

插入

167310946-febc1bc1-e898-4d31-aa94-efb423e69d1d

查询

167310988-142c61c2-49ab-487d-927e-0f6edd1e6376

4.引用

  • https://github.com/ECasio/olingo-spring-example
  • Apache Olingo Library
  • Spring Boot集成olingo快速入门demo | Harries Blog™

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/41180.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【吊打面试官系列-MyBatis面试题】MyBatis 实现一对多有几种方式,怎么操作的?

大家好&#xff0c;我是锋哥。今天分享关于 【MyBatis 实现一对多有几种方式,怎么操作的&#xff1f;】面试题&#xff0c;希望对大家有帮助&#xff1b; MyBatis 实现一对多有几种方式,怎么操作的&#xff1f; 有联合查询和嵌套查询。联合查询是几个表联合查询,只查询一次,通过…

观察矩阵(View Matrix)、投影矩阵(Projection Matrix)、视口矩阵(Window Matrix)及VPM矩阵及它们之间的关系

V表示摄像机的观察矩阵&#xff08;View Matrix&#xff09;&#xff0c;它的作用是把对象从世界坐标系变换到摄像机坐标系。因此&#xff0c;对于世界坐标系下的坐标值worldCoord(x0, y0, z0)&#xff0c;如果希望使用观察矩阵VM将其变换为摄像机坐标系下的坐标值localCoord(x…

Node.js-path 模块

path 模块 path 模块提供了 操作路径 的功能&#xff0c;如下是几个较为常用的几个 API&#xff1a; 代码实例&#xff1a; const path require(path);//获取路径分隔符 console.log(path.sep);//拼接绝对路径 console.log(path.resolve(__dirname, test));//解析路径 let pa…

vulhub-activemq(CVE-2016-3088)

在 Apache ActiveMQ 5.12.x~5.13.x 版本中&#xff0c;默认关闭了 fileserver 这个应用&#xff08;不过&#xff0c;可以在conf/jetty.xml 中开启&#xff09;&#xff1b;在 5.14.0 版本后&#xff0c;彻底删除了 fileserver 应用。【所以在渗透测试过程中要确定好 ActiveMQ …

数据结构1:C++实现变长数组

数组作为线性表的一种&#xff0c;具有内存连续这一特点&#xff0c;可以通过下标访问元素&#xff0c;并且下标访问的时间复杂的是O(1)&#xff0c;在数组的末尾插入和删除元素的时间复杂度同样是O(1)&#xff0c;我们使用C实现一个简单的边长数组。 数据结构定义 class Arr…

华为OD机试 - 来自异国的客人(Java 2024 D卷 100分)

华为OD机试 2024D卷题库疯狂收录中&#xff0c;刷题点这里 专栏导读 本专栏收录于《华为OD机试&#xff08;JAVA&#xff09;真题&#xff08;D卷C卷A卷B卷&#xff09;》。 刷的越多&#xff0c;抽中的概率越大&#xff0c;每一题都有详细的答题思路、详细的代码注释、样例测…

新手教学系列——前后端分离API优化版

在之前的文章《Vue 前后端分离开发:懒人必备的API SDK》中,我介绍了通过Object对象自动生成API的方法。然而,之前的代码存在一些冗余之处。今天,我将分享一个改进版本,帮助你更高效地管理API。 改进版API SDK 首先,让我们来看一下改进后的代码: import request from …

【反悔贪心 反悔堆】1642. 可以到达的最远建筑

本文涉及知识点 反悔贪心 反悔堆 LeetCode1642. 可以到达的最远建筑 给你一个整数数组 heights &#xff0c;表示建筑物的高度。另有一些砖块 bricks 和梯子 ladders 。 你从建筑物 0 开始旅程&#xff0c;不断向后面的建筑物移动&#xff0c;期间可能会用到砖块或梯子。 当…

MATLAB 2024b 更新了些什么?

MATLAB 2024b版本已经推出了预览版&#xff0c;本期介绍一些MATLAB部分的主要的更新内容。 帮助浏览器被移除 在此前的版本&#xff0c;当我们从MATLAB中访问帮助文档时&#xff0c;默认会通过MATLAB的帮助浏览器&#xff08;Help browser&#xff09;。 2024b版本开始&…

【Unity数据交互】如何Unity中读取Ecxel中的数据

&#x1f468;‍&#x1f4bb;个人主页&#xff1a;元宇宙-秩沅 &#x1f468;‍&#x1f4bb; hallo 欢迎 点赞&#x1f44d; 收藏⭐ 留言&#x1f4dd; 加关注✅! &#x1f468;‍&#x1f4bb; 本文由 秩沅 原创 &#x1f468;‍&#x1f4bb; 专栏交流&#x1f9e7;&…

医院挂号系统小程序的设计

管理员账户功能包括&#xff1a;系统首页&#xff0c;个人中心&#xff0c;患者管理&#xff0c;医生管理&#xff0c;专家信息管理&#xff0c;科室管理&#xff0c;预约信息管理&#xff0c;系统管理 微信端账号功能包括&#xff1a;系统首页&#xff0c;专家信息&#xff0…

数据结构算法-排序(一)-冒泡排序

什么是冒泡排序 冒泡排序&#xff1a;在原数组中通过相邻两项元素的比较&#xff0c;交换而完成的排序算法。 算法核心 数组中相邻两项比较、交换。 算法复杂度 时间复杂度 实现一次排序找到最大值需要遍历 n-1次(n为数组长度) 需要这样的排序 n-1次。 需要 (n-1) * (n-1) —…

【Linux进阶】文件系统7——文件系统简单操作

1.磁盘与目录的容量 现在我们知道磁盘的整体数据是在超级区块中&#xff0c;但是每个文件的容量则在inode 当中记载。 那在命令行模式下面该如何显示这几个数据&#xff1f;下面就让我们来谈一谈这两个命令&#xff1a; df&#xff1a;列出文件系统的整体磁盘使用量&#xf…

Poker Game, Run Fast

Poker Game, Run Fast 扑克&#xff1a;跑得快 分门别类&#xff1a; 单张从小到大默认 A < 2 < 3 < 4 < 5 < 6 < 7 < 8 < 9 < 10 < J < Q < K 跑得快&#xff1a;单张从小到大 3 < 4 < 5 < 6 < 7 < 8 < 9 < 10 &…

javaweb个人主页设计(html+css+js)

目录 1 前言和要求 1.1 前言 1.2 设计要求 2 预览 2.1 主页页面 2.2 个人简介 2.3 个人爱好 2.4 个人成绩有代码&#xff0c;但是图片已省略&#xff0c;可以根据自己情况添加 2.5 收藏夹 3 代码实现 3.1 主页 3.2 个人简介 3.3 个人爱好 3.4 个人成绩&#xff…

求职成功率的算法,与葫芦娃救爷爷的算法,有哪些相同与不同

1 本节概述 通过在B站百刷葫芦娃这部儿时剧&#xff0c;我觉得可以从中梳理出一些算法&#xff0c;甚至可以用于求职这个场景。所以&#xff0c;大家可以随便问我葫芦娃的一些剧情和感悟&#xff0c;我都可以做一些回答。 2 葫芦娃救爷爷有哪些算法可言&#xff1f; 我们知道…

身体(body)的觉醒

佛&#xff0c;是一个梵文的汉语音译词&#xff0c;指觉醒者。 何谓觉醒&#xff1f;什么的觉醒&#xff1f;其实很简单&#xff0c;就是身体的觉醒。 佛的另一个名字&#xff0c;叫菩提&#xff0c;佛就是菩提&#xff0c;菩提老祖&#xff0c;就是佛祖。 body&#xff0c;即…

Oracle RAC 19c 打补丁至最新版本-19.23.0.0.0

实验环境-我是从19.0.0.0直接打到19.23.0.0.0&#xff0c;适合刚部署好的集群打补丁直接到最新版本。 查看当前环境 查询集群中运行的 Oracle Clusterware 软件的 activex 版 查询本地节点上二进制文件中存储的 Oracle Clusterware 软件的版本 查询本地服务器上 OHAS 和 Oracle…

U.S.News发布全美最佳本科AI专业排名

10 加州大学圣迭戈分校 University of California, San Diego UCSD的人工智能项目从事广泛的理论和实验研究&#xff0c;学校的优势领域包括机器学习、不确定性下的推理和认知建模。除了理论学习&#xff0c;UCSD教授非常注重把计算机知识运用到自然语言处理、数据挖掘、计算…

20240707 每日AI必读资讯

&#x1f9e0;中国生成式AI专利数量超过美国 6 倍 - 中国在2014年至2023年期间申请的生成式AI专利数量达到38210个&#xff0c;超过了美国的6倍。 - 腾讯、平安保险集团和百度是GenAI专利数量最多的中国公司。 - 中国的顶级学术机构和技术生态为生成式AI的发展提供了强大支持…