第11課-Channel Study For Create Custom Restful Service
这节课我们一起学习利用Mirth Connect的HTTP Listener源通道与JavaScript Writer目的通道搭建自定义Restful风格webapi服务。
1.新建名为‘Custom Restful api’的信道,指定源通道与目的通道的输入输出消息格式
2.设置HTTP Listener类型源通道参数
- 把 "Response" 响应指定为 destination 1
- 输入‘Base context path’ 为
/myrestservice
- 设置 "Message Content" 为 XML Body
- 设置默认"Response Content Type" 为
text/plain; charset=UTF-8我们将在目的通道中通过channel map重写它的值为application/xml或application/json
- 设置 "Response Status Code" 响应码为
${responseStatusCode}我们将在目的通道中通过channel map重写它的值为200(成功)或500(失败)
- 在 "Response Header" 中添加一个变量 "Content-Type" ,指定其值为
${responseContentType}我们将在目的通道中通过channel map重写它的值为application/xml或application/json
3.设置JavaScript Writer目的通道参数并编写JS实现脚本
// Mirth strings don't support startsWith() in Mirth 3
// If necessary, add a method to the String prototype.
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(searchString, position){
position = position || 0;
return this.substr(position, searchString.length) === searchString;
};
} /*
Incoming message looks like this: <HttpRequest>
<RemoteAddress>71.127.40.115</RemoteAddress>
<RequestUrl>http://www.example.com:8080/myrestservice</RequestUrl>
<Method>GET</Method>
<RequestPath>foo=bar</RequestPath>
<RequestContextPath>/myrestservice/param1/param2</RequestContextPath>
<Parameters>
<foo>bar</foo>
</Parameters>
<Header>
<Host>www.example.com:8080</Host>
<Accept-Encoding>identity</Accept-Encoding>
<User-Agent>Wget/1.18 (darwin15.5.0)</User-Agent>
<Connection>keep-alive</Connection>
<Accept>application/xml</Accept>
</Header>
<Content/>
</HttpRequest> <HttpRequest>
<RemoteAddress>71.127.40.115</RemoteAddress>
<RequestUrl>http://www.example.com:8080/myrestservice</RequestUrl>
<Method>GET</Method>
<RequestPath>foo=bar</RequestPath>
<RequestContextPath>/myrestservice/param1/param2</RequestContextPath>
<Parameters>
<foo>bar</foo>
</Parameters>
<Header>
<Host>www.example.com:8080</Host>
<Accept-Encoding>identity</Accept-Encoding>
<User-Agent>Wget/1.18 (darwin15.5.0)</User-Agent>
<Connection>keep-alive</Connection>
<Accept>application/json</Accept>
</Header>
<Content/>
</HttpRequest>
*/ // Just in case we fail, set a sane responseContentType
channelMap.put('responseContentType', 'text/plain'); var msg = XML(connectorMessage.getRawData());
logger.info(msg);
// Get the REST data from the "context path" which is actually
// the "path info" of the request, so it will start with '/myrestservice'.
var rest = msg['RequestContextPath'];
logger.info(rest);
var myServicePrefix = '/myrestservice';
var minimumURLParameterCount = 4; // This is the minimum you require to do your work
var maximumExpectedURLParameterCount = 5; // however many you expect to get
var params = rest.substring(myServicePrefix).split('/', maximumExpectedURLParameterCount);
if(params.length < minimumURLParameterCount)
return Packages.com.mirth.connect.server.userutil.ResponseFactory.getErrorResponse('Too few parameters in request');
var mrn = params[1]; // params[0] will be an empty string
logger.info(mrn);
// Now, determine the client's preference for what data type to return (XML vs. JSON).
// We will default to XML.
var clientWantsJSON = false;
var responseContentType = 'text/xml'; // If we see any kind of JSON before any kind of XML, we'll use
// JSON. Otherwise, we'll use XML.
//
// Technically, this is incorrect resolution of the "Accept" header,
// but it's good enough for an example.
var mimeTypes = msg['Header']['Accept'].split(/\s*,\s*/);
for(var i=0; i<mimeTypes.length; ++i) {
var mimeType = mimeTypes[i].toString();
if(mimeType.startsWith('application/json')) {
clientWantsJSON = true;
responseContentType = 'application/json';
break;
} else if(mimeType.startsWith('application/xml')) {
clientWantsJSON = false;
responseContentType = 'application/xml';
break;
} else if(mimeType.startsWith('text/xml')) {
clientWantsJSON = false;
responseContentType = 'text/xml';
break;
}
} var xml;
var json; if(clientWantsJSON)
json = { status : '' };
else
xml = new XML('<response></response>'); try {
/*
Here is where you do whatever your service needs to actually do.
*/ if(clientWantsJSON) {
json.data = { foo: 1,
bar: 'a string',
baz: [ 'list', 'of', 'strings']
};
} else {
xml['@foo'] = 1;
xml['bar'] = 'a string';
xml['baz'][0] = 'list';
xml['baz'][1] = 'of';
xml['baz'][3] = 'strings';
} // Set the response code and content-type appropriately.
// http://www.mirthproject.org/community/forums/showthread.php?t=12678 channelMap.put('responseStatusCode', 200); if(clientWantsJSON) {
json.status = 'success';
var content = JSON.stringify(json);
channelMap.put('responseContent', content);
channelMap.put('responseContentType', responseContentType);
return content;
} else {
channelMap.put('responseContentType', responseContentType);
var content = xml.toString();
channelMap.put('responseContent', content);
return content;
}
}
catch (err)
{
channelMap.put('responseStatusCode', '500');
if(clientWantsJSON) {
json.status = 'error';
if(err.javaException) {
// If you want to unpack a Java exception, this is how you do it:
json.errorType = String(err.javaException.getClass().getName());
json.errorMessage = String(err.javaException.getMessage());
} channelMap.put('responseContentType', responseContentType); // Return an error with our "error" JSON
return Packages.com.mirth.connect.server.userutil.ResponseFactory.getErrorResponse(JSON.stringify(json));
} else {
if(err.javaException) {
xml['response']['error']['@type'] = String(err.javaException.getClass().getName());
xml['response']['error']['@message'] = String(err.javaException.getMessage());
} channelMap.put('responseContentType', responseContentType); // Return an error with our "error" XML
return Packages.com.mirth.connect.server.userutil.ResponseFactory.getErrorResponse(xml.toString());
}
}
我们通过目的通道以上JS脚本,学习到以下特别重要的知识:
- 获取输入请求的原始消息并自动格式化为XML格式:
var xml = new XML(connectorMessage.getRawData())
- 设置响应类型,如:
channelMap.put('responseContentType', 'application/json')
- 设置响应码,如:
channelMap.put('responseStatusCode', '200')
- 设置响应内容并通过JS脚本返回XML实体或者Json实体的字符串格式值
- 异常处理通过JS脚本调用Mirth的API函数Packages.com.mirth.connect.server.userutil.ResponseFactory.getErrorResponse(string)返回字符串格式错误消息
4.部署信道并测试
发送消息要区分application/json和application/xml,可以看到响应值格式会相应变化
<HttpRequest>
<RemoteAddress>71.127.40.115</RemoteAddress>
<RequestUrl>http://www.example.com:8080/myrestservice</RequestUrl>
<Method>GET</Method>
<RequestPath>foo=bar</RequestPath>
<RequestContextPath>/myrestservice/param1/param2</RequestContextPath>
<Parameters>
<foo>bar</foo>
</Parameters>
<Header>
<Host>www.example.com:8080</Host>
<Accept-Encoding>identity</Accept-Encoding>
<User-Agent>Wget/1.18 (darwin15.5.0)</User-Agent>
<Connection>keep-alive</Connection>
<Accept>application/json</Accept>
</Header>
<Content/>
</HttpRequest>
<HttpRequest>
<RemoteAddress>71.127.40.115</RemoteAddress>
<RequestUrl>http://www.example.com:8080/myrestservice</RequestUrl>
<Method>GET</Method>
<RequestPath>foo=bar</RequestPath>
<RequestContextPath>/myrestservice/param1/param2</RequestContextPath>
<Parameters>
<foo>bar</foo>
</Parameters>
<Header>
<Host>www.example.com:8080</Host>
<Accept-Encoding>identity</Accept-Encoding>
<User-Agent>Wget/1.18 (darwin15.5.0)</User-Agent>
<Connection>keep-alive</Connection>
<Accept>application/xml</Accept>
</Header>
<Content/>
</HttpRequest>
第11課-Channel Study For Create Custom Restful Service的更多相关文章
- How to Create Custom Filters in AngularJs
http://www.codeproject.com/Tips/829025/How-to-Create-Custom-Filters-in-AngularJs Introduction Filter ...
- create custom launcher icon 细节介绍
create custom launcher icon 是创建你的Android app的图标 点击下一步的时候,出现的界面就是创建你的Android的图标 Foreground: ” Foregro ...
- [转]How to Create Custom Filters in AngularJs
本文转自:http://www.codeproject.com/Tips/829025/How-to-Create-Custom-Filters-in-AngularJs Introduction F ...
- How to: Create Custom Configuration Sections Using ConfigurationSection
https://msdn.microsoft.com/en-us/library/2tw134k3.aspx You can extend ASP.NET configuration settings ...
- java中如何创建自定义异常Create Custom Exception
9.创建自定义异常 Create Custom Exception 马克-to-win:我们可以创建自己的异常:checked或unchecked异常都可以, 规则如前面我们所介绍,反正如果是chec ...
- Custom Data Service Providers
Custom Data Service Providers Introduction Data Services sits above a Data Service Provider, which i ...
- Unable to create Azure Mobile Service: Error 500
I had to go into my existing azure sql database server and under the configuration tab select " ...
- Cannot create container for service peer1.org2.example.com: Conflict. 解决方案
I have a docker-compose.yaml file defining 5 services: orderer.example.com peer0.org1.example.com pe ...
- docker启动报错解决及分析(Cannot create container for service *******: cannot mount volume over existing file, file exists /var/lib/docker/overlay2/)
现象: Cannot create container for service *******: cannot mount volume over existing file, file exists ...
- [转]Create Custom Exception Filter in ASP.NET Core
本文转自:http://www.binaryintellect.net/articles/5df6e275-1148-45a1-a8b3-0ba2c7c9cea1.aspx In my previou ...
随机推荐
- PlatformIO+ESP32+Vscode+DS18B20温度传感器(一直输出-127)
DS18B20一直输出-127 ?? 一.硬件连线 二.代码 三.遇到的问题 一.硬件连线 将相应的线接到ESP wroom 32 二.代码 先在PlatformIO的library添加onWire库 ...
- 基于Python的子进程获取键盘输入
一 概念 众所周知,python中的获取键盘输入,input函数是没办法用在子程序的,这就限制了它的用途.想要在子程序中获取键盘输入.唯有 fn=sys.stdin.fileno函数了. 二 实例解析 ...
- 没有有线网卡的笔记本如何在PVE下All in one?—NAS + Linux +win下载机
没有有线网卡的笔记本在PVE下All in one | NAS + Linux + Win下载机 (保姆级未完成版) 目录: 1.前言 2.PVE的安装 3.PVE联网前的准备工作 4.PVE使用无线 ...
- 说说你对keep-alive的理解是什么?
这里给大家分享我在网上总结出来的一些知识,希望对大家有所帮助 一.Keep-alive 是什么 keep-alive是vue中的内置组件,能在组件切换过程中将状态保留在内存中,防止重复渲染DOM ke ...
- 记录--Vue PC前端扫码登录
这里给大家分享我在网上总结出来的一些知识,希望对大家有所帮助 需求描述 目前大多数PC端应用都有配套的移动端APP,如微信,淘宝等,通过使用手机APP上的扫一扫功能去扫页面二维码图片进行登录,使得用户 ...
- 记录--教你用three.js写一个炫酷的3D登陆页面
这里给大家分享我在网上总结出来的一些知识,希望对大家有所帮助 前言: 该篇文章用到的主要技术:vue3.three.js 我们先看看成品效果: 高清大图预览(会有些慢): 座机小图预览: 废话不多说, ...
- proteus的五状态显示控制器
proteus的五状态显示控制器 1.实验原理 使用的核心器件还是4028,BCD译码器.将输入的四个信号接入输入端,输出信号选取0.1.2.4.8这五个输出状态驱动led显示.发光LED需要加入保护 ...
- multisim的操作回顾
multisim的操作回顾 1.写在前面 multisim的仿真功能还是强大的,能够有效地实现对电路功能的验证.但是,不能全局搜索器件是个大问题.对于不熟悉器件的基本分类的人来说,一排的分类足以浪费大 ...
- KingbaseES V8R6数据库运维案例之---索引坏块故障处理
案例说明: 在执行表数据查询时,出现下图所示错误,索引故障导致表无法访问,后重建索引问题解决.本案例复现了此类故障解决过程. 适用版本: KingbaseES V8R3/R6 一.创建测试环境 # 表 ...
- 理解持续测试,才算理解DevOps
软件产品的成功与否,在很大程度上取决于对市场需求的及时把控,采用DevOps可以加快产品交付速度,改善用户体验,从而有助于保持领先于竞争对手的优势. 作为敏捷开发方法论的一种扩展,DevOps强调开发 ...