Maven构建OSGI+HttpServer应用

2024-02-07 07:20

本文主要是介绍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):
命令行访问页面:

浏览器访问页面:

这篇关于Maven构建OSGI+HttpServer应用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/686961

相关文章

CentOS系统Maven安装教程分享

《CentOS系统Maven安装教程分享》本文介绍了如何在CentOS系统中安装Maven,并提供了一个简单的实际应用案例,安装Maven需要先安装Java和设置环境变量,Maven可以自动管理项目的... 目录准备工作下载并安装Maven常见问题及解决方法实际应用案例总结Maven是一个流行的项目管理工具

使用maven依赖详解

《使用maven依赖详解》本文主要介绍了Maven的基础知识,包括Maven的简介、仓库类型、常用命令、场景举例、指令总结、依赖范围、settings.xml说明等,同时,还详细讲解了Maven依赖的... 目录1. maven基础1.1 简介1.2 仓库类型1.3 常用命令1.4 场景举例1.5 指令总结

nginx-rtmp-module构建流媒体直播服务器实战指南

《nginx-rtmp-module构建流媒体直播服务器实战指南》本文主要介绍了nginx-rtmp-module构建流媒体直播服务器实战指南,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有... 目录1. RTMP协议介绍与应用RTMP协议的原理RTMP协议的应用RTMP与现代流媒体技术的关系2

5分钟获取deepseek api并搭建简易问答应用

《5分钟获取deepseekapi并搭建简易问答应用》本文主要介绍了5分钟获取deepseekapi并搭建简易问答应用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需... 目录1、获取api2、获取base_url和chat_model3、配置模型参数方法一:终端中临时将加

JavaScript中的isTrusted属性及其应用场景详解

《JavaScript中的isTrusted属性及其应用场景详解》在现代Web开发中,JavaScript是构建交互式应用的核心语言,随着前端技术的不断发展,开发者需要处理越来越多的复杂场景,例如事件... 目录引言一、问题背景二、isTrusted 属性的来源与作用1. isTrusted 的定义2. 为

SpringBoot项目中Maven剔除无用Jar引用的最佳实践

《SpringBoot项目中Maven剔除无用Jar引用的最佳实践》在SpringBoot项目开发中,Maven是最常用的构建工具之一,通过Maven,我们可以轻松地管理项目所需的依赖,而,... 目录1、引言2、Maven 依赖管理的基础概念2.1 什么是 Maven 依赖2.2 Maven 的依赖传递机

Python调用另一个py文件并传递参数常见的方法及其应用场景

《Python调用另一个py文件并传递参数常见的方法及其应用场景》:本文主要介绍在Python中调用另一个py文件并传递参数的几种常见方法,包括使用import语句、exec函数、subproce... 目录前言1. 使用import语句1.1 基本用法1.2 导入特定函数1.3 处理文件路径2. 使用ex

关于Maven生命周期相关命令演示

《关于Maven生命周期相关命令演示》Maven的生命周期分为Clean、Default和Site三个主要阶段,每个阶段包含多个关键步骤,如清理、编译、测试、打包等,通过执行相应的Maven命令,可以... 目录1. Maven 生命周期概述1.1 Clean Lifecycle1.2 Default Li

关于Maven中pom.xml文件配置详解

《关于Maven中pom.xml文件配置详解》pom.xml是Maven项目的核心配置文件,它描述了项目的结构、依赖关系、构建配置等信息,通过合理配置pom.xml,可以提高项目的可维护性和构建效率... 目录1. POM文件的基本结构1.1 项目基本信息2. 项目属性2.1 引用属性3. 项目依赖4. 构

将Python应用部署到生产环境的小技巧分享

《将Python应用部署到生产环境的小技巧分享》文章主要讲述了在将Python应用程序部署到生产环境之前,需要进行的准备工作和最佳实践,包括心态调整、代码审查、测试覆盖率提升、配置文件优化、日志记录完... 目录部署前夜:从开发到生产的心理准备与检查清单环境搭建:打造稳固的应用运行平台自动化流水线:让部署像