原文地址:https://www.cnblogs.com/kira2will/p/5040264.html

一、环境

eclipse版本:eclipse-luna 4.4

jre版本:1.8

二、Equinox OSGi应用嵌入Jersey框架搭建REST服务

1.新建插件工程HelloWebOSGI

a.

b.

c.

d.在新建的工程中新建文件夹lib,其中放入附件中的jar包(见文末),全部添加到工程Build Path中。

2.配置运行环境

a.配置引入包、依赖插件

b.选择Run->Run Configuration,new一个环境

保留图中TargetPlatform中的16个Bundle。

c.在Run Configuration中设置参数

友情提示:如果有其他异常请查看提示信息,利用 http://www.aolsearch.com/ 查询提示信息(英文),如果发现http://stackoverflow.com/这个网站有相同提问,基本就知道答案近在咫尺了。

比如笔者遇到的问题:Root exception:java.lang.IllegalStateException: Workbench has not been created yet.

解决方法就是在http://stackoverflow.com/questions/13773582/workbench-has-not-been-created-yet-error-in-eclipse-plugin-programming中找到的。

d.在MANIFEST.MF(META-INF)文件中将lib文件夹中的包都引入如下图中。

3.添加代码

Activator_sample.java

package helloworldosgi;

import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.logging.Logger; import javax.servlet.ServletException; import org.glassfish.jersey.servlet.ServletContainer;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.osgi.service.http.HttpService;
import org.osgi.service.http.NamespaceException;
import org.osgi.util.tracker.ServiceTracker; /*
* BundleActivator:让你能够捕捉到bundle的start和stop事件,并对这两个事件作出自定义的反应。
*/
public class Activator_sample implements BundleActivator {
private BundleContext bc;
@SuppressWarnings("rawtypes")
private ServiceTracker tracker;
private HttpService httpService = null;
private static final Logger logger = Logger.getLogger(Activator.class.getName()); /**
* URL前缀
*/
public static final String CONTEXT_PATH = "/rest/json"; /*
* BundleContext:一个bundle在框架中的执行时上下文,这个上下文提供了和框架进行交互的方法。
* @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public synchronized void start(BundleContext bundleContext) throws Exception {
this.bc = bundleContext;
logger.info("STARTING HTTP SERVICE BUNDLE"); this.tracker = new ServiceTracker(this.bc, HttpService.class.getName(), null) {
@Override
public Object addingService(ServiceReference serviceRef) {
httpService = (HttpService) super.addingService(serviceRef);
registerServlets();
return httpService;
} @Override
public void removedService(ServiceReference ref, Object service) {
if (httpService == service) {
unregisterServlets();
httpService = null;
}
super.removedService(ref, service);
}
}; this.tracker.open(); logger.info("HTTP SERVICE BUNDLE STARTED");
} /*
* BundleContext:一个bundle在框架中的执行时上下文,这个上下文提供了和框架进行交互的方法。
* @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
*/
@Override
public synchronized void stop(BundleContext bundleContext) throws Exception {
this.tracker.close();
} private void registerServlets() {
try {
rawRegisterServlets();
} catch (InterruptedException | NamespaceException | ServletException ie) {
throw new RuntimeException(ie);
}
} private void rawRegisterServlets() throws ServletException, NamespaceException, InterruptedException {
logger.info("JERSEY BUNDLE: REGISTERING SERVLETS");
logger.info("JERSEY BUNDLE: HTTP SERVICE = " + httpService.toString()); // TODO - temporary workaround
// This is a workaround related to issue JERSEY-2093; grizzly (1.9.5)
// needs to have the correct context
// classloader set
ClassLoader myClassLoader = getClass().getClassLoader();
ClassLoader originalContextClassLoader = Thread.currentThread()
.getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(myClassLoader);
httpService.registerServlet(CONTEXT_PATH, new ServletContainer(),
getJerseyServletParams(), null);
httpService.registerResources(CONTEXT_PATH + "/hello", "/webroot", null);//前面必须带“/”,后面不一定
} finally {
Thread.currentThread().setContextClassLoader(
originalContextClassLoader);
}
// END of workaround - after grizzly updated to the recent version, only
// the inner call from try block will remain:
// httpService.registerServlet("/jersey-http-service", new
// ServletContainer(), getJerseyServletParams(), null); sendAdminEvent();
logger.info("JERSEY BUNDLE: SERVLETS REGISTERED");
} @SuppressWarnings("serial")
private void sendAdminEvent() {
@SuppressWarnings("rawtypes")
ServiceReference eaRef = bc.getServiceReference(EventAdmin.class
.getName());
if (eaRef != null) {
@SuppressWarnings("unchecked")
EventAdmin ea = (EventAdmin) bc.getService(eaRef);
ea.sendEvent(new Event("jersey/test/DEPLOYED",
new HashMap<String, String>() {
{
put("context-path", "/");
}
}));
bc.ungetService(eaRef);
}
} private void unregisterServlets() {
if (this.httpService != null) {
logger.info("JERSEY BUNDLE: UNREGISTERING SERVLETS");
httpService.unregister(CONTEXT_PATH);
logger.info("JERSEY BUNDLE: SERVLETS UNREGISTERED");
}
} private Dictionary<String, String> getJerseyServletParams() {
Dictionary<String, String> jerseyServletParams = new Hashtable<>();
jerseyServletParams.put("javax.ws.rs.Application",
RestApplication.class.getName());
logger.info("kira2will" + RestApplication.class.getName());
return jerseyServletParams;
} }

StatusService.java

package helloworldosgi;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger; import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType; import data.Node; @Path("/status")
public class StatusService { private static final Logger logger = Logger.getLogger(StatusService.class.getName()); @GET
@Produces(MediaType.APPLICATION_JSON)
public Node getStatus(){ List<Node> nodes = new ArrayList<Node>();
Node node = new Node("001", "60800","192.168.1.1","0","92","92","chizhou","50ms","hw");
Node nothingNode = new Node("null","null","null","null","null","null","null","null","null");
//nodes.add(node);
nodes.add(node);
logger.info(node.getName());
return node;
} @Path("/{id}")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Node getID(@PathParam("id") int id){
List<Node> nodes = new ArrayList<Node>(); nodes.add(new Node("null","null","null","null","null","null","null","null","null"));
nodes.add(new Node("001", "60600","192.168.1.1","0","92","92","tonglin","50ms","hw"));
nodes.add(new Node("002", "60600","192.168.1.1","0","92","92","tonglin","50ms","hw"));
nodes.add(new Node("003", "60600","192.168.1.1","0","92","92","tonglin","50ms","hw"));
nodes.add(new Node("004", "60600","192.168.1.1","0","92","92","tonglin","50ms","hw"));
nodes.add(new Node("005", "60600","192.168.1.1","0","92","92","tonglin","50ms","hw")); int defaultIndex = 0;
if ( (id < 1) || (id > nodes.size() - 1) ){
logger.info(nodes.get(defaultIndex).getId());
return nodes.get(defaultIndex);
}
else{
logger.info(nodes.get(id).getId());
return nodes.get(id);
}
}
}

RestApplication.java

package helloworldosgi;

import java.util.HashSet;
import java.util.Set; import javax.ws.rs.core.Application; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; public class RestApplication extends Application { @Override
public Set<Class<?>> getClasses() {
Set<Class<?>> result = new HashSet<Class<?>>(); result.add(JacksonJsonProvider.class); result.add(StatusService.class); return result;
}
}

Node.java

package data;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Node { private String id;
private String name;
private String admin_ip;
private String admin_status;
private String longitude;
private String latitude;
private String location;
private String latency;
private String vendor_name; public Node(String id,
String name,
String admin_ip,
String admin_status,
String longitude,
String latitude,
String location,
String latency,
String vendor_name
){
this.id = id;
this.name = name;
this.admin_ip = admin_ip;
this.admin_status = admin_status;
this.longitude = longitude;
this.latitude = latitude;
this.location = location;
this.latency = latency;
this.vendor_name = vendor_name;
}
public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getAdmin_ip() {
return admin_ip;
} public void setAdmin_ip(String admin_ip) {
this.admin_ip = admin_ip;
} public String getAdmin_status() {
return admin_status;
} public void setAdmin_status(String admin_status) {
this.admin_status = admin_status;
} public String getLongitude() {
return longitude;
} public void setLongitude(String longitude) {
this.longitude = longitude;
} public String getLatitude() {
return latitude;
} public void setLatitude(String latitude) {
this.latitude = latitude;
} public String getLocation() {
return location;
} public void setLocation(String location) {
this.location = location;
} public String getLatency() {
return latency;
} public void setLatency(String latency) {
this.latency = latency;
} public String getVendor_name() {
return vendor_name;
} public void setVendor_name(String vendor_name) {
this.vendor_name = vendor_name;
}
}

4.浏览器中输入 http://localhost:8080/rest/json/status 即可访问public Node getStatus() 返回值。

或者输入 http://localhost:8080/rest/json/status/2 即可访问public Node getID(@PathParam("id") int id)返回值。

关于@Path @Get @PathParam 参考 http://www.docin.com/p-317614298.html 第七页。

http://download.csdn.net/detail/kira_will/9729055

原文地址:https://www.cnblogs.com/kira2will/p/5040264.html

Equinox OSGi应用嵌入Jersey框架搭建REST服务的更多相关文章

  1. 原创:Equinox OSGi应用嵌入Jersey框架搭建REST服务

    一.环境 eclipse版本:eclipse-luna 4.4 jre版本:1.8 二.Equinox OSGi应用嵌入Jersey框架搭建REST服务 1.新建插件工程HelloWebOSGI a. ...

  2. go服务端----使用dotweb框架搭建简易服务

    使用dotweb框架搭建简易服务 go语言web框架挺多的,所谓琳琅满目,里面也有很多优秀的,比如echo.beego等,但体验下来,总是觉得哪里有点小疙瘩,后来才明白过来,echo太简单,很多日常使 ...

  3. 使用Yii2的Web框架搭建微服务框架

    方法 使用自己的Yii2镜像作为基础 使用Yii2的Web框架搭建,为了节省搭建Yii2框架的时间,直接使用现有的Yii2项目,删除了业务相关的逻辑类,将这个代码库作为搭建微服务框架的基础,本身已经积 ...

  4. Flask框架搭建REST-API服务

    一.目的 为了能够将测试工具部署成RESTful-API服务,这样就能通过接口的方式提供统一测试工具服务,使用人员就不用构建application而产生的各种环境问题.使用问题. 适合人群:Pytho ...

  5. django框架搭建web服务

    一.工具 环境:windows 7 python 2.7.7     下载地址:https://www.python.org/downloads/release/python-2713/   ps:这 ...

  6. [Visual Studio] SOA服务框架搭建

    1.服务框架搭建 2.服务模板创建 3.Nuget引用 4.客户端调用 任务点: 1.分析SOA 2.修改SOA架构名称以及关键字 3.使用Nuget添加引用 4.选择服务模板进行创建 5.尝试调用 ...

  7. 一步一步使用ABP框架搭建正式项目系列教程之本地化详解

    返回总目录<一步一步使用ABP框架搭建正式项目系列教程> 本篇目录 扯扯本地化 ABP中的本地化 小结 扯扯本地化 本节来说说本地化,也有叫国际化.全球化的,不管怎么个叫法,反正道理都是一 ...

  8. Jersey 2 + Maven + Tomcat + IntelliJ IDEA 搭建RESTful服务

    本文参考以下内容: [1] Starting out with Jersey & Apache Tomcat using IntelliJ [2] [Jersey]IntelliJ IDEA ...

  9. struts2+hibernate+spring注解版框架搭建以及简单测试(方便脑补)

    为了之后学习的日子里加深对框架的理解和使用,这里将搭建步奏简单写一下,目的主要是方便以后自己回来脑补: 1:File--->New--->Other--->Maven--->M ...

随机推荐

  1. 找到bug的根源,问五次为什么

    在学习<问题分析与解决>时学到了一种找到问题根源的方法——问五次为什么.具体内容是:当遇到一个问题,不要只看当前答案,要继续往下问,为什么,连问五次,就能够找到更深层次的问题.最近在复盘b ...

  2. 杭电ACM2014--青年歌手大奖赛_评委会打分

    青年歌手大奖赛_评委会打分 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Tot ...

  3. ElasticSearch-6.2安装head插件

    环境 Windows10企业版X64 JDK-1.8 ElasticSearch-6.2.4 node-v10.1 git客户端 步骤 安装node到K盘.如K:\nodejs. 把NODE_HOME ...

  4. Java开发笔记(二十九)大整数BigInteger

    早期的编程语言为了节约计算机的内存,给数字变量定义了各种存储规格的数值类型,比如字节型byte只占用一个字节大小,短整型short占用两个字节大小,整型int占用四个字节大小,长整型long占用八个字 ...

  5. Maven(十二)Maven 依赖详解

    依赖的传递性 注意1:在Eclipise创建的Maven项目,若依赖eclipse空间中其他自己创建的 的项目时,此时并不会报错,但是当执行mvn compile命令时还是会显示缺失败.所以依赖的其他 ...

  6. 当input框输入到限定长度时,自动focus下一个input框

     需求背景 需要输入一串15位的数字,但是要分为3个输入框,每个输入框限定长度5位,当删除当前输入框的内容时,focus到上一个输入框: 实现方法 var field = $('.phone-fiel ...

  7. 四边形不等式优化DP

    记录一下,以免忘了 对于一个形如 \[dp[i][j]=min(dp[i][k]+dp[k][j]+w[i][j])\] 的转移方程(注意取最大值时不一定满足四边形不等式) 定理1 若对于\(a \l ...

  8. 文件类型解析漏洞防御与攻击(PHP)

    简介: 解析漏洞主要是一些特殊文件被iis.Apache.Nginx等服务在某种情况下解释成脚本文件格式并得以执行而产生的漏洞,一般的思路都是用图片木马来欺骗服务器,上传webshell,达到提权的目 ...

  9. 解决注册并发问题并提高QPS

    前言:前面在本地的windows通过apache的ab工具测试了600并发下“查询指定手机是否存在再提交数据”的注册功能会出现重复提交的情况,并且在注册完成时还需要对邀请人进行奖励,记录邀请记录,对该 ...

  10. Android Studio Termanal打不开,提示java.io.IOEXception:couldn't create PTY

    打开Andorid Studio,点击Terminal提示错误;  如图: 经过一番挣扎,尝试了以下几种 方法一:打开File -> Settings -> Tools -> Ter ...