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.rhkb.cn/news/369921.html

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

相关文章

单调栈 求下一个更大数

题意&#xff1a; 现在给你n个数字: ,问从每个数字往后看&#xff0c;第一个比他大的数字的下标是多少。 题解&#xff1a; 使用一个单调递减栈即可。 #include<bits/stdc.h> using namespace std; const int N100005;int n,s[N],a[N],ans[N],top0;int main(){scan…

ASP.NET Web应用中的 Razor Pages/MVC/Web API/Blazor

如果希望使用ASP.NET Core创建新的 Web 应用程序&#xff0c;应该选择哪种方法&#xff1f;Razor Pages还是 MVC&#xff08;模型-视图-控制器&#xff09;&#xff0c;又或者使用Web API Vue/React/......。 每种方法都有各自的优点和缺点。 什么是 MVC&#xff1f; 大多数服…

高考志愿填报,选热门专业还是选自己喜欢的专业

对于每一个结束高考的学生来说&#xff0c;都要面临选专业这个严峻的挑战。选专业可以说是妥妥的大工程&#xff0c;因为这关系到接下来的几年要学什么内容&#xff0c;关键是未来的几十年要从事什么样的工作。 所以在谈及选专业这个问题的时候&#xff0c;每个人的内心都有些…

力扣(3200)- 三角形的最大高度

好方法&#xff1a; 垃圾方法&#xff1a;

Python酷库之旅-第三方库Pandas(005)

目录 一、用法精讲 7、pandas.read_clipboard函数 7-1、语法 7-2、参数 7-3、功能 7-4、返回值 7-5、说明 7-6、用法 7-6-1、代码示例 7-6-2、结果输出 8、pandas.DataFrame.to_clipboard函数 8-1、语法 8-2、参数 8-3、功能 8-4、返回值 8-5、说明 8-6、用法…

UCOS-III 任务同步机制-信号量

1. 信号量类型 1.1 二值信号量&#xff08;Binary Semaphores&#xff09; 二值信号量只有两个状态&#xff1a;可用&#xff08;1&#xff09;和不可用&#xff08;0&#xff09;。它主要用于任务之间的互斥访问或者事件通知。例如&#xff0c;当一个任务完成某个操作后&am…

pip install包出现哈希错误解决

如图&#xff0c;当遇到此类错误时&#xff0c;多半是连接不稳定导致的校验失败。我们可以在PC端&#xff0c;或Ubuntu通过浏览器下载.whl安装文件&#xff1a;直接复制报错信息中的网址到浏览器即可弹出下载窗口。

kafka的架构

一、架构图 Broker&#xff1a;一台 kafka 服务器就是一个 broker。一个kakfa集群由多个 broker 组成。一个 broker 可以容纳多个 topic。 Producer&#xff1a;消息生产者&#xff0c;就是向 kafka broker 发消息的客户端 Consumer&#xff1a;消息消费者&#xff0c;向 kaf…

Win11右键默认显示更多选项的方法

问题描述 win11系统默认右键菜单显示选项太少&#xff0c;每次需要点一下“显示更多选项”才能得到想要内容。比方说我用notepad打开一个文档&#xff0c;在win11上要先点一下"显示更多选项“&#xff0c;再选择用notepad打开&#xff0c;操作非常反人类。 Win11右键默…

小红书矩阵系统源码:赋能内容创作与电商营销的创新工具

在内容驱动的电商时代&#xff0c;小红书凭借其独特的社区氛围和用户基础&#xff0c;成为品牌营销和个人创作者不可忽视的平台。小红书矩阵系统源码&#xff0c;作为支撑这一平台的核心技术&#xff0c;提供了一系列的功能和优势&#xff0c;助力用户在小红书生态中实现更高效…

高考假期预习指南

人不走空 &#x1f308;个人主页&#xff1a;人不走空 &#x1f496;系列专栏&#xff1a;算法专题 ⏰诗词歌赋&#xff1a;斯是陋室&#xff0c;惟吾德馨 目录 &#x1f308;个人主页&#xff1a;人不走空 &#x1f496;系列专栏&#xff1a;算法专题 ⏰诗词歌…

【CSAPP】-attacklab实验

目录 实验目的与要求 实验原理与内容 实验设备与软件环境 实验过程与结果&#xff08;可贴图&#xff09; 实验总结 实验目的与要求 1. 强化机器级表示、汇编语言、调试器和逆向工程等方面基础知识&#xff0c;并结合栈帧工作原理实现简单的栈溢出攻击&#xff0c;掌握其基…

51单片机第23步_定时器1工作在模式0(13位定时器)

重点学习51单片机定时器1工作在模式0的应用。 在51单片机中&#xff0c;定时器1工作在模式0&#xff0c;它和定时器0一样&#xff0c;TL1占低5位&#xff0c;TH1占高8位&#xff0c;合计13位&#xff0c;也是向上计数。 1、定时器1工作在模式0 1)、定时器1工作在模式0的框图…

django高校教务系统-计算机毕业设计源码81661

目 录 摘要 1 绪论 1.1 研究背景 1.2目的及意义 1.3论文结构与章节安排 2 高校教务系统设计分析 2.1 可行性分析 2.1.1 技术可行性分析 2.1.2 经济可行性分析 2.1.3 法律可行性分析 2.2 系统功能分析 2.2.1 功能性分析 2.2.2 非功能性分析 2.3 系统用例分析 2.4…

TCP和IP数据包结构

一、问题引入 一般我们在谈上网速度的时候&#xff0c;专业上用带宽来描述&#xff0c;其实无论说网速或者带宽都是不准确的&#xff0c;呵呵。比如&#xff1a;1兆&#xff0c;512K……有些在学校的学生&#xff0c;也许会有疑问&#xff0c;明明我的业务是1M&#xff0c;为…

前后端的导入、导出、模板下载等写法

导入&#xff0c;导出、模板下载等的前后端写法 文章目录 导入&#xff0c;导出、模板下载等的前后端写法一、导入实现1.1 后端的导入1.2 前端的导入 二、基础的模板下载2.1 后端的模板下载-若依基础版本2.2 前端的模板下载2.3 后端的模板下载 - 基于资源文件读取2.4 excel制作…

Tech Talk:智能电视eMMC存储的五问五答

智能电视作为搭载操作系统的综合影音载体&#xff0c;以稳步扩大的市场规模走入越来越多的家庭&#xff0c;成为人们生活娱乐的重要组成部分。存储部件是智能电视不可或缺的组成部分&#xff0c;用于保存操作系统、应用程序、多媒体文件和用户数据等信息。智能电视使用eMMC作为…

ListBox自动滚动并限制显示条数

1、实现功能 限制ListBox显示的最大条数&#xff1b; ListBox自动滚动&#xff0c;显示最新行&#xff1b; 2、C#代码 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using Syst…

印尼网络安全治理能力观察

在全国国际机场的移民服务完全瘫痪 100 多个小时后&#xff0c;印尼政府承认其新成立的国家数据中心 (PDN) 遭受了网络攻击。 恶意 Lockbit 3.0 勒索软件加密了存储在中心的重要数据&#xff0c;其背后的黑客组织要求支付 800 万美元的赎金。 不幸的是&#xff0c;大多数数据…

TreeMap、HashMap 和 LinkedHashMap 的区别

TreeMap、HashMap 和 LinkedHashMap 的区别 1、HashMap2、LinkedHashMap3、TreeMap4、总结 &#x1f496;The Begin&#x1f496;点点关注&#xff0c;收藏不迷路&#x1f496; 在 Java 中&#xff0c;TreeMap、HashMap 和 LinkedHashMap 是三种常用的集合类&#xff0c;它们在…