Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added MTOM support for binary data #1054

Merged
merged 3 commits into from Mar 27, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
42 changes: 36 additions & 6 deletions src/http.ts
Expand Up @@ -5,8 +5,10 @@

import * as debugBuilder from 'debug';
import * as httpNtlm from 'httpntlm';
import * as _ from 'lodash';
import * as req from 'request';
import * as url from 'url';
import * as uuid from 'uuid/v4';
import { IHeaders, IOptions } from './types';

const debug = debugBuilder('node-soap');
Expand All @@ -16,6 +18,13 @@ export interface IExOptions {
[key: string]: any;
}

export interface IAttachment {
name: string;
contentId: string;
mimetype: string;
body: ReadableStream;
}

export type Request = req.Request;

/**
Expand All @@ -41,7 +50,7 @@ export class HttpClient {
* @param {Object} exoptions Extra options
* @returns {Object} The http request object for the `request` module
*/
public buildRequest(rurl: string, data: any, exheaders?: IHeaders, exoptions?: IExOptions): any {
public buildRequest(rurl: string, data: any, exheaders?: IHeaders, exoptions: IExOptions = {}): any {
const curl = url.parse(rurl);
const secure = curl.protocol === 'https:';
const host = curl.hostname;
Expand All @@ -53,12 +62,13 @@ export class HttpClient {
'Accept': 'text/html,application/xhtml+xml,application/xml,text/xml;q=0.9,*/*;q=0.8',
'Accept-Encoding': 'none',
'Accept-Charset': 'utf-8',
'Connection': exoptions && exoptions.forever ? 'keep-alive' : 'close',
'Connection': exoptions.forever ? 'keep-alive' : 'close',
'Host': host + (isNaN(port) ? '' : ':' + port),
};
const mergeOptions = ['headers'];
const attachments: IAttachment[] = exoptions.attachments || [];

if (typeof data === 'string') {
if (typeof data === 'string' && attachments.length === 0) {
headers['Content-Length'] = Buffer.byteLength(data, 'utf8');
headers['Content-Type'] = 'application/x-www-form-urlencoded';
}
Expand All @@ -75,10 +85,30 @@ export class HttpClient {
followAllRedirects: true,
};

options.body = data;
if (attachments.length > 0) {
const start = uuid();
headers['Content-Type'] =
'multipart/related; type="application/xop+xml"; start="<' + start + '>"; start-info="text/xml"; boundary=' + uuid();
const multipart: any[] = [{
'Content-Type': 'application/xop+xml; charset=UTF-8; type="text/xml"',
'Content-ID': '<' + start + '>',
'body': data,
}];
attachments.forEach((attachment) => {
multipart.push({
'Content-Type': attachment.mimetype,
'Content-Transfer-Encoding': 'binary',
'Content-ID': '<' + attachment.contentId + '>',
'Content-Disposition': 'attachment; filename="' + attachment.name + '"',
'body': attachment.body,
});
});
options.multipart = multipart;
} else {
options.body = data;
}

exoptions = exoptions || {};
for (const attr in exoptions) {
for (const attr in _.omit(exoptions, ['attachments'])) {
if (mergeOptions.indexOf(attr) !== -1) {
for (const header in exoptions[attr]) {
options[attr][header] = exoptions[attr][header];
Expand Down
78 changes: 78 additions & 0 deletions test/client-test.js
Expand Up @@ -136,6 +136,84 @@ var fs = require('fs'),
});
});

describe('Binary attachments handling', function () {
var server = null;
var hostname = '127.0.0.1';
var port = 15099;
var baseUrl = 'http://' + hostname + ':' + port;
var attachment = {
mimetype: 'image/png',
contentId: 'file_0',
name: 'nodejs.png',
body: fs.createReadStream(__dirname + '/static/nodejs.png')
};

function parsePartHeaders(part) {
const headersAndBody = part.split(/\r\n\r\n/);
const headersParts = headersAndBody[0].split(/\r\n/);
const headers = {};
headersParts.forEach(header => {
let index;
if ((index = header.indexOf(':')) > -1) {
headers[header.substring(0, index)] = header.substring(index + 1).trim();
}
});
return headers;
}

it('should send binary attachments using XOP + MTOM', function (done) {
server = http.createServer((req, res) => {
const bufs = [];
req.on('data', function (chunk) {
bufs.push(chunk);
});
req.on('end', function () {
const body = Buffer.concat(bufs).toString().trim();
const headers = req.headers;
const boundary = headers['content-type'].match(/boundary="?([^"]*"?)/)[1];
const parts = body.split(new RegExp('--' + boundary + '-{0,2}'))
.filter(part => part)
.map(parsePartHeaders);
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ contentType: headers['content-type'], parts: parts }), 'utf8');
});
}).listen(port, hostname, function () {

soap.createClient(__dirname + '/wsdl/attachments.wsdl', meta.options, function (initError, client) {
assert.ifError(initError);

client.MyOperation({}, function (error, response, body) {
assert.ifError(error);
const contentType = {};
body.contentType.split(/;\s?/).forEach(dir => {
const keyValue = dir.match(/(.*)="?([^"]*)?/);
if (keyValue && keyValue.length > 2) {
contentType[keyValue[1].trim()] = keyValue[2].trim();
} else {
contentType.rootType = dir;
}
});
assert.equal(contentType.rootType, 'multipart/related');
assert.equal(body.parts.length, 2);

const dataHeaders = body.parts[0];
assert(dataHeaders['Content-Type'].indexOf('application/xop+xml') > -1);
assert.equal(dataHeaders['Content-ID'], contentType.start);

const attachmentHeaders = body.parts[1];
assert.equal(attachmentHeaders['Content-Type'], attachment.mimetype);
assert.equal(attachmentHeaders['Content-Transfer-Encoding'], 'binary');
assert.equal(attachmentHeaders['Content-ID'], '<' + attachment.contentId + '>');
assert(attachmentHeaders['Content-Disposition'].indexOf(attachment.name) > -1);

server.close();
done();
}, { attachments: [attachment] });
}, baseUrl);
});
});
});


describe('Headers in request and last response', function () {
var server = null;
Expand Down
@@ -0,0 +1,8 @@
{
"attachments": [{
"mimetype": "plain/txt",
"contentId": "file_0",
"name": "data.txt",
"body": "some data"
}]
}
@@ -0,0 +1,7 @@
{
"field1": "field 1 value",
"field2": "another value",
"attachment": {
"$xml": "<inc:Include href=\"cid:file_0\" xmlns:inc=\"http://www.w3.org/2004/08/xop/include\"/>"
}
}
@@ -0,0 +1 @@
{}
@@ -0,0 +1,51 @@
<?xml version="1.0" encoding="UTF-8"?>
<definitions name="MyService" targetNamespace="http://www.example.com/v1" xmlns="http://www.example.com/v1" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/">
<types>
<schema targetNamespace="http://www.example.com/v1" xmlns="http://www.example.com/v1">
<element name="MultipartRequest">
<complexType>
<sequence>
<element type="string" name="field1" minOccurs="1" maxOccurs="1" />
<element type="string" name="field2" minOccurs="1" maxOccurs="1" />
<element type="attachments" name="attachments" minOccurs="0" maxOccurs="1" />
</sequence>
</complexType>
<complexType name="attachments">
<sequence>
<element name="data" type="xsd:base64Binary" xmime:expectedContentTypes="application/octet-stream" minOccurs="0" maxOccurs="unbounded" />
</sequence>
</complexType>
</element>
</schema>
</types>
<message name="InputMessage">
<part name="parameter" element="MultipartRequest">
</part>
</message>
<message name="OutputMessage" />
<portType name="MyServicePortType">
<operation name="attachments">
<input message="InputMessage">
</input>
<output message="OutputMessage">
</output>
</operation>
</portType>
<binding name="MyServiceBinding" type="MyServicePortType">
<binding style="document" transport="http://schemas.xmlsoap.org/soap/http" />
<operation name="attachments">
<operation soapAction="attachments" />
<input>
<body use="literal" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
</input>
<output>
<body use="literal" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
</output>
</operation>
</binding>
<service name="MyService">
<port name="MyServicePort" binding="MyServiceBinding">
<address location="http://www.example.com/v1" />
</port>
</service>
</definitions>
Binary file added test/static/nodejs.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
51 changes: 51 additions & 0 deletions test/wsdl/attachments.wsdl
@@ -0,0 +1,51 @@
<?xml version="1.0" encoding="UTF-8"?>
<definitions name="MyService" targetNamespace="http://www.example.com/v1" xmlns="http://www.example.com/v1" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/">
<types>
<schema attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://www.example.com/v1" xmlns="http://www.example.com/v1">
<element name="Request">
<complexType>
<sequence>
<element type="string" name="field1" minOccurs="1" maxOccurs="1" />
<element type="string" name="field2" minOccurs="1" maxOccurs="1" />
<element type="attachments" name="attachments" minOccurs="0" maxOccurs="1" />
</sequence>
</complexType>
<complexType name="attachments">
<sequence>
<element name="data" type="xsd:base64Binary" xmime:expectedContentTypes="application/octet-stream" minOccurs="0" maxOccurs="unbounded" />
</sequence>
</complexType>
</element>
</schema>
</types>
<message name="InputMessage">
<part name="parameter" element="Request">
</part>
</message>
<message name="OutputMessage" />
<portType name="MyServicePortType">
<operation name="MyOperation">
<input message="InputMessage">
</input>
<output message="OutputMessage">
</output>
</operation>
</portType>
<binding name="MyServiceBinding" type="MyServicePortType">
<binding style="document" transport="http://schemas.xmlsoap.org/soap/http" />
<operation name="MyOperation">
<operation soapAction="MyOperation" />
<input>
<body use="literal" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
</input>
<output>
<body use="literal" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
</output>
</operation>
</binding>
<service name="MyService">
<port name="MyServicePort" binding="MyServiceBinding">
<address location="http://www.example.com/v1" />
</port>
</service>
</definitions>