Maven构建OSGI+HttpServer应用

Maven构建OSGI+HttpServer应用

官网(https://eclipse.dev/equinox/server/http_in_equinox.php)介绍有两种方式:

一种是基于”org.eclipse.equinox.http”包的轻量级实现,另一种是基于”org.eclipse.equinox.http.jetty”包(基于jetty的Servlet)实现。

使用 "org.eclipse.equinox.http" 包(例如:http-1.0.100-v20070423.jar),可以将我们自定义的服务(servlet或静态资源页面)注册到这个 HttpService 中去,实现自定义的HTTP服务。

"org.osgi.service.http" 包(例如:org.osgi.service.http-1.2.2.jar)内部会内嵌一个 HttpService Interface,而"org.eclipse.equinox.http" 包(http-1.0.100-v20070423.jar)提供了一个上述Interface的 HttpService实现类,因此,一旦这个osgi bundle (http-1.0.100-v20070423.jar)启动了,就会有一个内嵌的 http 服务被启动,默认地址是 http://localhost,端口为 80,可以通过指定参数 “org.osgi.service.http.port”来修改默认端口。

"org.eclipse.equinox.http" 包(http-1.0.100-v20070423.jar)内有一个上面那个 HttpService Interface 的实现类:

想要提供我们自定义的 HttpService服务,就要将我们的服务(servlet或静态资源页面)注册到这个 HttpService 中去,需要用到 "org.osgi.service.http" 包中的 HttpService 类的两个注册方法:

1)注册静态资源:
registerResources(String alias, String name, HttpContext httpContext)

2)注册 Servlet 类:
registerServlet(String alias, Servlet servlet, Dictionary initparams, HttpContext httpContext)

所以要想提供我自己的WebService实现,我们就需要:

提供自定义的WebService实现的步骤如下:
1)获取 httpService 对象;
2)编码提供 servlet 和 webpage 的实现;
3)将 servlet 和 webpage 注册到 HttpService 服务中去(同时指定对应的 alias);
4)访问;

新建manve项目:

创建package、class、和编码:
1)Java package:com.xxx.osgi.httpserver.demo、com.xxx.osgi.httpserver.servlet
2)Java class文件:Activator.java、MyServlet.java

Activator.java:

package com.xxx.osgi.httpserver.demo;import com.xxx.osgi.httpserver.servlet.MyServlet;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.ServiceReference;
import org.osgi.service.http.HttpContext;
import org.osgi.service.http.HttpService;import java.util.LinkedList;
import java.util.List;/*** @author Frank* @date 2023/12/26*/
public class Activator implements BundleActivator {private static BundleContext bundleContext;private HttpService httpService;private List<Bundle> bundles;static BundleContext getBundleContext() {return bundleContext;}public void start(BundleContext bundleContext) throws Exception {Activator.bundleContext = bundleContext;installBundles(bundleContext, false); // install other bundlesServiceReference serviceReference = bundleContext.getServiceReference(HttpService.class.getName());httpService = (HttpService) bundleContext.getService(serviceReference);// 注册HttpContext httpContext = httpService.createDefaultHttpContext();// 注册静态页面,设置别名"/osgi",所有对"/osgi"的请求映射到"/webpage/index.html"httpService.registerResources("/osgi", "/webpage/index.html", httpContext);System.out.println("start ok");// 注册 servlet,设置servlet别名"/test",所有对'/test"的请求映射到myServlet的实现MyServlet myServlet = new MyServlet();httpService.registerServlet("/test", myServlet, null, httpContext);}public void stop(BundleContext bundleContext) throws Exception {installBundles(bundleContext, true); //uninstall other bundleshttpService.unregister("/osgi");httpService.unregister("/test");Activator.bundleContext = null;System.out.println("stop ok");}public void installBundles(BundleContext context, boolean uninstall) {List<String> bundleFiles = new LinkedList<String>();List<Bundle> installedBundles = new LinkedList<Bundle>();//install my other bundles// System.out.printf("1 %s\n", FileLocator.getBundleFile(FrameworkUtil.getBundle(Activator.class)).getAbsolutePath());// System.out.printf("2 %s\n", FileLocator.getBundleFile(context.getBundle()).getAbsolutePath());// System.out.printf("3 %s\n", context.getBundle().getLocation());// String baseDir = FileLocator.getBundleFile(context.getBundle()).getParentFile().getAbsolutePath();String baseDir = context.getBundle().getLocation().replaceFirst("/[^/]*.jar","/");bundleFiles.add(baseDir + "helloworld-server-1.0.0-SNAPSHOT.jar");if (!uninstall) {// install & start bundlesfor (String bundleFile : bundleFiles) {try {Bundle bundle = context.installBundle(bundleFile);installedBundles.add(bundle);bundle.start();} catch (BundleException e) {if (!e.getMessage().contains("A bundle is already installed")) {throw new RuntimeException(e);}}}bundles = installedBundles;System.out.printf("all bundles (cnt = %d) installed and started!", bundles.size());} else {// stop & uninstall bundlesfor (Bundle bundle : bundles) {try {context.getBundle(bundle.getBundleId()).stop();context.getBundle(bundle.getBundleId()).uninstall();} catch (BundleException e) {throw new RuntimeException(e);}}System.out.printf("all bundles (cnt = %d) stopped and uninstalled!", bundles.size());}}
}

MyServlet.java:

package com.xxx.osgi.httpserver.servlet;import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Logger;public class MyServlet extends HttpServlet implements Servlet {private Logger logger = Logger.getLogger(this.getClass().getName());@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.getWriter().write("MyServlet return: Method=" + req.getMethod() + ", URI=" + req.getRequestURI());}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.getWriter().write("MyServlet return: Method=" + req.getMethod() + ", URI=" + req.getRequestURI());}
}

3)创建静态页面文件:webpage/index.html

<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>jetty test</title>
</head>
<body>
<h2>OSGI HttpServer/Jetty Test</h2>
<font color="green"> register static resource/pages: </font><br>
registerResources(String alias, String name, HttpContext httpContext) <br><br><font color="green">register servlet class: </font><br>
registerServlet(String alias, Servlet servlet, Dictionary initparams, HttpContext httpContext)
</body>
</html>

4)创建&编辑 pom.xml 文件

pom文件中定义了OSGI框架和版本、编码中所需的依赖以及osgi menifest和osgi打包配置:

<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"><modelVersion>4.0.0</modelVersion><groupId>com.xxx.osgi</groupId><artifactId>osgi-httpserver-demo</artifactId><version>1.0.0-SNAPSHOT</version><packaging>bundle</packaging><name>osgi-httpserver-demo</name><url>http://maven.apache.org</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><java.version>1.8</java.version><maven.compiler.source>1.8</maven.compiler.source><maven.compiler.target>1.8</maven.compiler.target></properties><dependencies><dependency><!-- 该版本 maven 仓库找不到,如果要用该版本可以在 Project Structure->Project Settings->Modules 中设置:--><!-- 设置 OSGI:General->Configure OSGI Core Library->Use Library 指定本地 jar 文件静态添加 osgi lib  --><!--<groupId>org.eclipse</groupId><artifactId>osgi</artifactId><version>3.18.600.v20231110-1900</version><scope>provided</scope>--><!-- 该版本maven仓库可以找到,可以用这个版本。在 pom 中指定 osgi lib 的 dependency 依赖 --><groupId>org.eclipse</groupId><artifactId>osgi</artifactId><version>3.10.0-v20140606-1445</version><scope>provided</scope></dependency><!-- START: httpServer required bundles --><!-- org.osgi.service.cm_1.6.1.202109301733.jar --><dependency><groupId>org.osgi</groupId><artifactId>org.osgi.service.cm</artifactId><version>1.6.1</version></dependency><!-- javax.servlet-3.0.0.v201112011016.jar --><dependency><groupId>org.eclipse.jetty.orbit</groupId><artifactId>javax.servlet</artifactId><version>3.0.0.v201112011016</version></dependency><!-- http-1.0.100-v20070423.jar --><dependency><groupId>org.eclipse.equinox</groupId><artifactId>http</artifactId><version>1.0.100-v20070423</version></dependency><!-- org.osgi.service.http-1.2.2.jar --><dependency><groupId>org.osgi</groupId><artifactId>org.osgi.service.http</artifactId><version>1.2.2</version></dependency><!-- END: httpServer required bundles --><!-- for: org.eclipse.core.runtime.FileLocator --><!-- common-3.6.200-v20130402-1505.jar / org.eclipse.equinox.common.source_3.18.200.v20231106-1826.jar --><dependency><groupId>org.eclipse.equinox</groupId><artifactId>common</artifactId><version>3.6.200-v20130402-1505</version></dependency></dependencies><build><plugins><plugin><!-- osgi 打包配置,使用 maven-bundle-plugin 插件进行 osgi 打包 bundle jar --><!-- 使用maven-bundle-plugin打包方式时指定manifest文件不生效,但可在 instructions 中配置 manifest 参数 --><groupId>org.apache.felix</groupId><artifactId>maven-bundle-plugin</artifactId><version>3.5.0</version><extensions>true</extensions><configuration><instructions><!-- 把依赖的普通jar和bundle jar也一起打包进去(/lib目录下),bundle jar 服务依赖还要在 Import-Package 中指定 --><Embed-Dependency>*;scope=compile|runtime</Embed-Dependency><Embed-Directory>lib</Embed-Directory><Embed-Transitive>true</Embed-Transitive><!-- BEGIN: 把本地静态资源目录也打包进去 --><Include-Resource>webpage=webpage</Include-Resource><!-- END: 把本地静态资源目录webpage也打包进去(到webpage目录、相当于目录拷贝) --><Bundle-ClassPath>.,{maven-dependencies}</Bundle-ClassPath><Bundle-Name>${project.name}</Bundle-Name><Bundle-SymbolicName>$(replace;${project.artifactId};-;_)</Bundle-SymbolicName><Bundle-Version>${project.version}</Bundle-Version><Bundle-Activator>com.xxx.osgi.httpserver.demo.Activator</Bundle-Activator><DynamicImport-Package>*</DynamicImport-Package><Import-Package>javax.servlet,javax.servlet.http,org.osgi.service.http;resolution:="optional"</Import-Package><Export-Package></Export-Package></instructions></configuration></plugin></plugins></build>
</project>

整体项目的代码结构如下:

准备运行依赖的bundles:

org.osgi.service.cm_1.6.1.202109301733.jar
javax.servlet-3.0.0.v201112011016.jar
org.osgi.service.http-1.2.2.jar
http-1.0.100-v20070423.jar
 

直接在 configuration/config.ini 初始化启动配置中加入依赖 bundles 或者启动 osgi 以后执行 install 安装依赖 bundles:
install plugins/org.osgi.service.cm_1.6.1.202109301733.jar
install other_bundles/javax.servlet-3.0.0.v201112011016.jar
install other_bundles/org.osgi.service.http-1.2.2.jar
install other_bundles/http-1.0.100-v20070423.jar
start 5 6 7 8 

注意,多条命名install时有先后顺序依赖,也可以放在一条命令执行多个 bundle 的install(无顺序依赖)
install plugins/org.osgi.service.cm_1.6.1.202109301733.jar other_bundles/javax.servlet-3.0.0.v201112011016.jar other_bundles/org.osgi.service.http-1.2.2.jar other_bundles/http-1.0.100-v20070423.jar
 

“org.osgi.service.http”的HttpService Interface的实现类bundle “org.eclipse.equinox.http”启动后,HttpService服务就启动了、查看HttpService监听端口已开启(如果equinox的配置文件或启动参数没有指定 org.osgi.service.http.port=8080 的话,默认是监听的是 80 端口):

项目编译打包:
执行命令打包
mvn clean package

拷贝项目编译打包生成的jar文件到osgi运行环境:

执行osgi-httpserver-demo jar包(install & start):

项目bundle 9已经启动、bundle9内代码install & start 的其他bundel 10 也都start成功,状态为ACTIVE了。

httpServer 访问测试(访问 localhost:8080/osgi 和 localhost:8080/test):
命令行访问页面:

浏览器访问页面:

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

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

相关文章

基于SpringBoot+Vue的实验室管理系统

末尾获取源码作者介绍&#xff1a;大家好&#xff0c;我是墨韵&#xff0c;本人4年开发经验&#xff0c;专注定制项目开发 更多项目&#xff1a;CSDN主页YAML墨韵 学如逆水行舟&#xff0c;不进则退。学习如赶路&#xff0c;不能慢一步。 目录 一、项目简介 二、开发技术与环…

​​​​​​​CleanMyMac X有什么优势?到底好不好用?

当你的Mac开始变得缓慢或者存储空间告急时&#xff0c;这通常是一个清理磁盘空间的信号。无论是工作文件、个人照片、还是各种应用程序&#xff0c;随着时间的推移&#xff0c;它们都可能在你的硬盘上积累了大量数据。有效地管理这些文件不仅可以提高你的工作效率&#xff0c;还…

12.0 Zookeeper 数据同步流程

在 Zookeeper 中&#xff0c;主要依赖 ZAB 协议来实现分布式数据一致性。 ZAB 协议分为两部分&#xff1a; 消息广播崩溃恢复 消息广播 Zookeeper 使用单一的主进程 Leader 来接收和处理客户端所有事务请求&#xff0c;并采用 ZAB 协议的原子广播协议&#xff0c;将事务请求…

Python进阶--下载想要的格言(基于格言网的Python爬虫程序)

注&#xff1a;由于上篇帖子&#xff08;Python进阶--爬取下载人生格言(基于格言网的Python3爬虫)-CSDN博客&#xff09;篇幅长度的限制&#xff0c;此篇帖子对上篇做一个拓展延伸。 目录 一、爬取格言网中想要的内容的url 1、找到想要的内容 2、抓包分析&#xff0c;找到想…

如何更改默认浏览器?

打开设置---应用---默认应用 点击你想要设置为默认浏览器的应用&#xff08;假设为Microsoft Edge&#xff09;&#xff0c;点击设置默认值就可以了。

艺术创作和生活的关系

艺术出现在生产劳作中并体现出人们生活、工作、学习中&#xff0c;使人们在不受限制随意发挥缔造发明能力的体现&#xff0c;独立的精神活动领域在它逐渐演变进步的历程中越来越明显&#xff0c;也是一个人精神思想生活中很重要的一部分。艺术随着社会发展而发展。一件完美的艺…

【Kubernetes】kubectl top pod 异常?

目录 前言一、表象二、解决方法1、导入镜像包2、编辑yaml文件3、解决问题 三、优化改造1.修改配置文件2.检查api-server服务是否正常3.测试验证 总结 前言 各位老铁大家好&#xff0c;好久不见&#xff0c;卑微涛目前从事kubernetes相关容器工作&#xff0c;感兴趣的小伙伴相互…

2月6日作业

1.现有无序序列数组为23,24,12,5,33,5347&#xff0c;请使用以下排序实现编程 函数1:请使用冒泡排序实现升序排序 函数2:请使用简单选择排序实现升序排序 函数3:请使用快速排序实现升序排序 函数4:请使用插入排序实现升序排序 #include<stdio.h> #include<string.h&…

微信小程序解决华为手机保存图片到相册失败

1.新增隐私设置 2.优化代码 新增uni.authorize判断 _saveCode() {let that this;console.log(点击了保存图片)console.log(this.result)uni.authorize({scope: scope.writePhotosAlbum,success(e) {console.log(e)if (this.result ! "") {uni.saveImageToPhotosAlb…

VMware虚拟机清理瘦身

用了一段时间VMware虚拟机之后&#xff0c;发现内存越来越小&#xff0c;也没装什么软件。。。 1.查询磁盘空间分布 虚拟机中磁盘空间查询 先看一下哪些地方占用的空间大&#xff0c;进行排查。 2.排查VMware复制文件产生的缓存路径 VMware复制文件有一个特点&#xff0c;以…

SpringBoo+Vue构建简洁日志文件查看系统

点击下载《SpringBooVue构建日志文件查看系统&#xff08;源代码&#xff09;》 1. 前言 想必经常做java开发的小伙伴&#xff0c;其大多数服务都是运行在linux系统上的&#xff0c;当遇到一些比较棘手的bug需要处理时&#xff0c;经常要上服务器去捞日志&#xff0c;然后通过…

单片机学习笔记---串口通信(1)

目录 通信的基本概念 通信的方式 1.按照数据传送的方式&#xff0c;可分为串行通信和并行通信。 1.1串行通信 1.2并行通信 2.按照通信的数据同步方式&#xff0c;又可以分为异步通信和同步通信。 2.1 异步通信 2.2同步通信 3.按照数据的传输方向&#xff0c;又可以分为…

恒创科技:怎么看云主机的性价比

随着云计算技术的不断发展&#xff0c;云主机已经成为越来越多企业和个人用户的首选计算资源。然而&#xff0c;在选择云主机时&#xff0c;性价比是一个非常重要的考虑因素。那么&#xff0c;怎么看云主机的性价比呢&#xff1f; 通常来说&#xff0c;云主机的成本主要包括硬…

博途PLC报警字FC(字寄存器按位访问)

博途PLC的字寄存器按位访问和拆分,请查看下面文章链接: https://rxxw-control.blog.csdn.net/article/details/121727057https://rxxw-control.blog.csdn.net/article/details/121727057西门子触摸屏报警都是以字为地址访问,所以离散报警信号我们需要将其组合为报警字输出,…

jsp教务管理系统Myeclipse开发mysql数据库web结构java编程计算机网页项目

一、源码特点 JSP 教务管理系统是一套完善的java web信息管理系统&#xff0c;对理解JSP java编程开发语言有帮助&#xff0c;系统具有完整的源代码和数据库&#xff0c;系统主要采用B/S模式开发。开发环境为 TOMCAT7.0,Myeclipse8.5开发&#xff0c;数据库为Mysql5.0&…

Python操作Word表格对齐、单元格对齐

通过Table的alignment可以设置表格居左对齐、居中对齐、居右对齐。通过Cell的vertical_alignment可以设置垂直位置。通过单元格里段落的alignment可以设置文本的左右对齐方式。 import docx from docx.enum.table import WD_TABLE_ALIGNMENT, WD_CELL_VERTICAL_ALIGNMENT from…

鸿蒙(HarmonyOS)项目方舟框架(ArkUI)之Video媒体组件

鸿蒙&#xff08;HarmonyOS&#xff09;项目方舟框架&#xff08;ArkUI&#xff09;之Video媒体组件 一、操作环境 操作系统: Windows 10 专业版、IDE:DevEco Studio 3.1、SDK:HarmonyOS 3.1 二、Video媒体组件 用于播放视频文件并控制其播放状态的组件。 子组件 无 接口…

uniapp 使用renderjs引入echarts

效果图&#xff1a; 1.1renderjs引入echarts 组件zmui-echarts.vue&#xff1a; <template><view class"zmui-echarts" :prop"option" :change:prop"echarts.delay"></view> </template><script>export defaul…

go modules使用

创建项目 在使用GoLand创建项目的时候&#xff0c;会自动创建对应的go.mod文件。 创建完后 创建文件 创建一个main.go的文件&#xff0c;里面print一个hello world。 在运行时可以设置是否采取先生成文件再运行。 为空的话则不输出。 下面的Environment为设置运行的环境…

【Ubuntu 20.04/22.04 LTS】最新 esp-matter SDK 软件编译环境搭建步骤

仓库链接&#xff1a;esp-matter SDK官方软件说明&#xff1a;ESP Matter Programming Guide官方参考文档&#xff1a;使用 Matter-SDK 快速搭建 Matter 环境 (Linux) 环境要求 Ubuntu 20.04 或 Ubuntu22.04网络环境支持访问 Gihub 在安装 esp-matter SDK 软件编译环境之前&a…