diff --git a/.vscode/launch.json b/.vscode/launch.json deleted file mode 100644 index 08628c066..000000000 --- a/.vscode/launch.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - // Use IntelliSense to learn about possible attributes. - // Hover to view descriptions of existing attributes. - // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 - "version": "0.2.0", - "configurations": [ - - { - "type": "node", - "request": "launch", - "name": "Mocha Tests", - "program": "${workspaceFolder}/node_modules/mocha/bin/_mocha", - "args": [ - "-u", - "tdd", - "--timeout", - "999999", - "--colors", - "${workspaceFolder}/codegens/java-native/npm" - ], - "internalConsoleOptions": "openOnSessionStart", - "skipFiles": [ - "/**" - ] - } - ] - - -} \ No newline at end of file diff --git a/codegens/java-native/.gitignore b/codegens/java-native/.gitignore new file mode 100644 index 000000000..2c7c686e6 --- /dev/null +++ b/codegens/java-native/.gitignore @@ -0,0 +1,41 @@ +.DS_Store +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Coverage directory used by tools like istanbul +.coverage + +# node-waf configuration +.lock-wscript + + +# Dependency directories +node_modules/ +jspm_packages/ + +# Typescript v1 declaration files +typings/ + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variables file +.env + +out/ diff --git a/codegens/java-native/.npmignore b/codegens/java-native/.npmignore new file mode 100644 index 000000000..79ad2ba5f --- /dev/null +++ b/codegens/java-native/.npmignore @@ -0,0 +1,76 @@ +### NPM Specific: Disregard recursive project files +### =============================================== +/.editorconfig +/.gitmodules +/test + +### Borrowed from .gitignore +### ======================== + +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Prevent IDE stuff +.idea +.vscode +*.sublime-* + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +.coverage + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# Typescript v1 declaration files +typings/ + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variables file +.env + +snippet.swift + +out/ diff --git a/codegens/java-native/README.md b/codegens/java-native/README.md new file mode 100644 index 000000000..82e238e5e --- /dev/null +++ b/codegens/java-native/README.md @@ -0,0 +1,73 @@ +# codegen-java-okhttp + +> Converts Postman-SDK Request into code snippet for Java. + +#### Prerequisites +To run Code-Gen, ensure that you have NodeJS >= v6. A copy of the NodeJS installable can be downloaded from https://nodejs.org/en/download/package-manager. + +## Using the Module +The module will expose an object which will have property `convert` which is the function for converting the Postman-SDK request to java-okhttp code snippet and `getOptions` function which returns an array of supported options. + +### convert function +Convert function will take three parameters +* `request`- Postman-SDK Request object + +* `options`- options is an object which can have following properties + * `indentType`- string representing type of indentation for code snippet. eg: 'Space', 'Tab' + * `indentCount`- positiveInteger representing count of indentation required. + * `includeBoilerplate`- boolean representing whether to include class definition in code snippet + * `requestTimeout` : Integer denoting time after which the request will bail out in milli-seconds + * `trimRequestBody` : Trim request body fields + * `followRedirect` : Boolean denoting whether to redirect a request + +* `callback`- callback function with first parameter as error and second parameter as string for code snippet + +##### Example: +```js +var request = new sdk.Request('www.google.com'), //using postman sdk to create request + options = { + indentType: 'Space', + indentCount: 2, + includeBoilerplate: false + }; +convert(request, options, function(error, snippet) { + if (error) { + // handle error + } + // handle snippet +}); +``` + +### getOptions function + +This function returns a list of options supported by this codegen. + +#### Example +```js +var options = getOptions(); + +console.log(options); +// output +// [ +// { +// name: 'Set indentation count', +// id: 'indentCount', +// type: 'positiveInteger', +// default: 2, +// description: 'Set the number of indentation characters to add per code level' +// }, +// ... +// ] +``` + +### Guideline for using generated snippet + +* Generated snippet uses `.setRequestMethod(nameOfMethod)` from `HttpURLConnection` class to form HTTP request. If the `method` doesn't require body then the value of `con.setDoOutput()` will be `false`. + +* Generated snippet creates a BiConsumer for handling Form Data `BiConsumer uploadFileFunction` when `multipart/formdata` is used otherwise it uses `DataOutputStream` in order to add body to request. + +* Since Postman-SDK Request object doesn't provide complete path of the file, it needs to be manually inserted in case of uploading a file. + +* `content-type` needs to be specified in order to add body to the request. So if no `content-type` is specified then `text/plain` will be used as default. **In case of `multipart/formdata` `content-type` is generated by snippet itself**. + +* This module doesn't support cookies. diff --git a/codegens/java-native/index.js b/codegens/java-native/index.js new file mode 100644 index 000000000..bb0a047c4 --- /dev/null +++ b/codegens/java-native/index.js @@ -0,0 +1 @@ +module.exports = require('./lib'); diff --git a/codegens/java-native/lib/index.js b/codegens/java-native/lib/index.js new file mode 100644 index 000000000..6e08e8b25 --- /dev/null +++ b/codegens/java-native/lib/index.js @@ -0,0 +1,5 @@ +module.exports = { + convert: require('./javanative').convert, + getOptions: require('./javanative').getOptions +}; + diff --git a/codegens/java-native/lib/javanative.js b/codegens/java-native/lib/javanative.js new file mode 100644 index 000000000..a04e2f521 --- /dev/null +++ b/codegens/java-native/lib/javanative.js @@ -0,0 +1,251 @@ +var _ = require('./lodash'), + + parseRequest = require('./parseRequest'), + sanitize = require('./util').sanitize, + addFormParam = require('./util').addFormParam, + sanitizeOptions = require('./util').sanitizeOptions; + +// Since Java requires to add extralines of code to handle methods with body +const METHODS_WITHOUT_BODY = ['GET', 'HEAD', 'COPY', 'UNLOCK', 'UNLINK', 'PURGE', 'LINK', 'VIEW']; + +/** + * returns content-type and boundary snippet of java for multipart request + * + * @returns {String} - java code snippet for multi-part content + */ +function multiPartSnippet () { + return 'final String boundary = "===" + System.currentTimeMillis() + "===";\n' + + 'con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);\n'; +} + +/** + * returns snippet of java by parsing data from Postman-SDK request object + * + * @param {Object} request - Postman SDK request object + * @param {String} indentString - indentation required for code snippet + * @param {Object} options - Options to tweak code snippet + * @returns {String} - java code snippet for given request object + */ +function makeSnippet (request, indentString, options) { + + var isBodyRequired = !(_.includes(METHODS_WITHOUT_BODY, request.method)), + snippet = ''; + if (request.method === 'PATCH') { + snippet += 'try {\n' + + indentString + 'Field methodsField = HttpURLConnection.class.getDeclaredField("methods");\n' + + indentString + 'methodsField.setAccessible(true);\n' + + indentString + 'Field modifiersField = Field.class.getDeclaredField("modifiers");\n' + + indentString + 'modifiersField.setAccessible(true);\n' + + indentString + 'modifiersField.setInt(methodsField, methodsField.getModifiers() & ~Modifier.FINAL);\n' + + indentString + 'String[] methods = {\n' + + indentString.repeat(2) + '"GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE", "PATCH"\n' + + indentString + '};\n' + + indentString + 'methodsField.set(null, methods);\n' + + indentString + '} catch (Exception e) {\n' + + indentString.repeat(2) + 'e.printStackTrace();\n' + + indentString + '};\n'; + } + + snippet += `URL obj = new URL("${sanitize(request.url.toString())}");\n` + + 'URLConnection connection = obj.openConnection();\n' + + 'HttpURLConnection con = null;\n' + + 'if(connection instanceof HttpsURLConnection){\n' + + indentString + 'con = (HttpsURLConnection) connection;\n' + + '}else{\n' + + indentString + 'con = (HttpURLConnection) connection;\n' + + '}\n' + + `con.setRequestMethod("${request.method}");\n`; + + if (options.requestTimeout > 0) { + snippet += `con.setConnectTimeout(${options.requestTimeout});\n`; + } + + if (!options.followRedirect) { + snippet += 'con.setInstanceFollowRedirects(false);\n'; + } + + snippet += parseRequest.parseHeader(request, indentString); + + snippet += `con.setDoOutput(${isBodyRequired ? 'true' : 'false'});\n`; + if (isBodyRequired) { + // The following code handles multiple files in the same formdata param. + // It removes the form data params where the src property is an array of filepath strings + // Splits that array into different form data params with src set as a single filepath string + if (request.body && request.body.mode === 'formdata') { + let formdata = request.body.formdata, + formdataArray = []; + formdata.members.forEach((param) => { + let key = param.key, + type = param.type, + disabled = param.disabled, + contentType = param.contentType; + if (type === 'file') { + if (typeof param.src !== 'string') { + if (Array.isArray(param.src) && param.src.length) { + param.src.forEach((filePath) => { + addFormParam(formdataArray, key, param.type, filePath, disabled, contentType); + }); + } + else { + addFormParam(formdataArray, key, param.type, '/path/to/file', disabled, contentType); + } + } + else { + addFormParam(formdataArray, key, param.type, param.src, disabled, contentType); + } + } + else { + addFormParam(formdataArray, key, param.type, param.value, disabled, contentType); + } + }); + request.body.update({ + mode: 'formdata', + formdata: formdataArray + }); + snippet += multiPartSnippet(); + } + if (request.body && request.body.mode === 'file') { + snippet += multiPartSnippet(); + } + let requestBody = (request.body ? request.body.toJSON() : {}); + // snippet for creating mediatype object in java based on content-type of request + // snippet += `con.setRequestProperty("Content-Type", "${parseRequest.parseContentType(request)}");\n` + snippet += parseRequest.parseBody(requestBody, indentString, options.trimRequestBody); + } + + if (request.body && request.body.mode === 'graphql' && !request.headers.has('Content-Type')) { + request.addHeader({ + key: 'Content-Type', + value: 'application/json' + }); + } + + snippet += 'BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));\n' + + 'String temp = null;\n' + + 'StringBuilder response = new StringBuilder();\n' + + 'while ((temp = in.readLine()) != null) {\n' + + indentString + 'response.append(temp).append(" ");\n' + + '}\n' + + 'System.out.println(response.toString());\n' + + 'in.close();'; + + return snippet; +} + + +/** + * Used in order to get options for generation of Java code snippet (i.e. Include Boilerplate code) + * + * @module getOptions + * + * @returns {Array} Options specific to generation of Java code snippet + */ +function getOptions () { + return [ + { + name: 'Include boilerplate', + id: 'includeBoilerplate', + type: 'boolean', + default: false, + description: 'Include class definition and import statements in snippet' + }, + { + name: 'Set indentation count', + id: 'indentCount', + type: 'positiveInteger', + default: 2, + description: 'Set the number of indentation characters to add per code level' + }, + { + name: 'Set indentation type', + id: 'indentType', + type: 'enum', + availableOptions: ['Tab', 'Space'], + default: 'Space', + description: 'Select the character used to indent lines of code' + }, + { + name: 'Set request timeout', + id: 'requestTimeout', + type: 'positiveInteger', + default: 0, + description: 'Set number of milliseconds the request should wait for a response ' + + 'before timing out (use 0 for infinity)' + }, + { + name: 'Follow redirects', + id: 'followRedirect', + type: 'boolean', + default: true, + description: 'Automatically follow HTTP redirects' + }, + { + name: 'Trim request body fields', + id: 'trimRequestBody', + type: 'boolean', + default: false, + description: 'Remove white space and additional lines that may affect the server\'s response' + } + ]; +} + +/** + * Converts Postman sdk request object to java code snippet + * + * @module convert + * + * @param {Object} request - postman-SDK request object + * @param {Object} options - Options to tweak code snippet generated in Java- + * @param {String} options.indentType - type for indentation eg: Space, Tab + * @param {String} options.indentCount - number of spaces or tabs for indentation. + * @param {Boolean} [options.includeBoilerplate] - indicates whether to include class definition in java + * @param {Boolean} options.followRedirect - whether to enable followredirect + * @param {Boolean} options.trimRequestBody - whether to trim fields in request body or not + * @param {Number} options.requestTimeout : time in milli-seconds after which request will bail out + * @param {Function} callback - callback function with parameters (error, snippet) + */ +function convert (request, options, callback) { + + if (_.isFunction(options)) { + callback = options; + options = {}; + } + else if (!_.isFunction(callback)) { + throw new Error('Java-Converter: callback is not valid function'); + } + options = sanitizeOptions(options, getOptions()); + // String representing value of indentation required + var indentString, + + // snippets to include java class definition according to options + headerSnippet = '', + footerSnippet = '', + + // snippet to create request in java + snippet = ''; + + indentString = options.indentType === 'Tab' ? '\t' : ' '; + indentString = indentString.repeat(options.indentCount); + + if (options.includeBoilerplate) { + headerSnippet = 'import java.io.*;\n' + + 'import javax.net.ssl.HttpsURLConnection;\n' + + 'import java.net.*;\n' + + 'import java.lang.reflect.*;\n' + + 'import java.util.function.BiConsumer;\n' + + 'public class main {\n' + + indentString + 'public static void main(String []args) throws IOException{\n'; + footerSnippet += indentString + '\n}\n}\n'; + } + + snippet = makeSnippet(request, indentString, options); + + // if boilerplate is included then two more indentString needs to be added in snippet + (options.includeBoilerplate) && + (snippet = indentString.repeat(2) + snippet.split('\n').join('\n' + indentString.repeat(2)) + '\n'); + return callback(null, headerSnippet + snippet + footerSnippet); +} +module.exports = { + convert: convert, + getOptions: getOptions +}; diff --git a/codegens/java-native/lib/lodash.js b/codegens/java-native/lib/lodash.js new file mode 100644 index 000000000..5be147afd --- /dev/null +++ b/codegens/java-native/lib/lodash.js @@ -0,0 +1,455 @@ +/* istanbul ignore next */ +module.exports = { + + /** + * Checks if `value` is an empty object, array or string. + * + * Objects are considered empty if they have no own enumerable string keyed + * properties. + * + * Values such as strings, arrays are considered empty if they have a `length` of `0`. + * + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is empty, else `false`. + * @example + * + * isEmpty(null) + * // => true + * + * isEmpty(true) + * // => true + * + * isEmpty(1) + * // => true + * + * isEmpty([1, 2, 3]) + * // => false + * + * isEmpty('abc') + * // => false + * + * isEmpty({ 'a': 1 }) + * // => false + */ + isEmpty: function (value) { + // eslint-disable-next-line lodash/prefer-is-nil + if (value === null || value === undefined) { + return true; + } + if (Array.isArray(value) || typeof value === 'string' || typeof value.splice === 'function') { + return !value.length; + } + + for (const key in value) { + if (Object.prototype.hasOwnProperty.call(value, key)) { + return false; + } + } + return true; + }, + + /** + * Checks if `value` is `undefined`. + * + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. + * @example + * + * isUndefined(void 0) + * // => true + * + * isUndefined(null) + * // => false + */ + isUndefined: function (value) { + return value === undefined; + }, + + /** + * Checks if `func` is classified as a `Function` object. + * + * @param {*} func The value to check. + * @returns {boolean} Returns `true` if `func` is a function, else `false`. + * @example + * + * isFunction(self.isEmpty) + * // => true + * + * isFunction(/abc/) + * // => false + */ + isFunction: function (func) { + return typeof func === 'function'; + }, + + /** + * Converts the first character of `string` to upper case and the remaining + * to lower case. + * + * @param {string} [string=''] The string to capitalize. + * @returns {string} Returns the capitalized string. + * @example + * + * capitalize('FRED') + * // => 'Fred' + * + * capitalize('john') + * // => 'John' + */ + + capitalize: function (string) { + return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); + }, + + /** + * Reduces `array` to a value which is the accumulated result of running + * each element in `array` thru `iteratee`, where each successive + * invocation is supplied the return value of the previous. If `accumulator` + * is not given, the first element of `array` is used as the initial + * value. The iteratee is invoked with four arguments: + * (accumulator, value, index|key, array). + * + * @param {Array} array The Array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @example + * + * reduce([1, 2], (sum, n) => sum + n, 0) + * // => 3 + * + */ + reduce: function (array, iteratee, accumulator) { + return array.reduce(iteratee, accumulator); + }, + + /** + * Iterates over elements of `array`, returning an array of all elements + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index, array). + * + * @param {Array} array The array to iterate over. + * @param {Function|object} predicate The function/object invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @example + * + * const users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false } + * ] + * + * filter(users, ({ active }) => active) + * // => object for ['barney'] + */ + filter: function (array, predicate) { + if (typeof predicate === 'function') { + return array.filter(predicate); + } + var key = Object.keys(predicate), + val = predicate[key], + res = []; + array.forEach(function (item) { + if (item[key] && item[key] === val) { + res.push(item); + } + }); + return res; + }, + + /** + * The opposite of `filter` this method returns the elements of `array` + * that `predicate` does **not** return truthy for. + * + * @param {Array} array collection to iterate over. + * @param {String} predicate The String that needs to have truthy value, invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @example + * + * const users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false } + * ] + * + * reject(users, 'active') + * // => object for ['fred'] + */ + reject: function (array, predicate) { + var res = []; + array.forEach((object) => { + if (!object[predicate]) { + res.push(object); + } + }); + return res; + }, + + /** + * Creates an array of values by running each element of `array` thru `iteratee`. + * The iteratee is invoked with three arguments: (value, index, array). + * + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + * @example + * + * function square(n) { + * return n * n + * } + * + * map([4, 8], square) + * // => [16, 64] + */ + map: function (array, iteratee) { + return array.map(iteratee); + }, + + /** + * Iterates over elements of `collection` and invokes `iteratee` for each element. + * The iteratee is invoked with three arguments: (value, index|key, collection). + * + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @example + * + * forEach([1, 2], value => console.log(value)) + * // => Logs `1` then `2`. + * + * forEach({ 'a': 1, 'b': 2 }, (value, key) => console.log(key)) + * // => Logs 'a' then 'b' + */ + + forEach: function (collection, iteratee) { + if (collection === null) { + return null; + } + + if (Array.isArray(collection)) { + return collection.forEach(iteratee); + } + const iterable = Object(collection), + props = Object.keys(collection); + var index = -1, + key, i; + + for (i = 0; i < props.length; i++) { + key = props[++index]; + iteratee(iterable[key], key, iterable); + } + return collection; + }, + + /** + * Checks if `value` is in `collection`. If `collection` is a string, it's + * checked for a substring of `value`, otherwise it checks if the `value` is present + * as a key in a `collection` object. + * + * @param {Array|Object|string} collection The collection to inspect. + * @param {*} value The value to search for. + * @returns {boolean} Returns `true` if `value` is found, else `false`. + * @example + * + * _.includes([1, 2, 3], 1); + * // => true + * + * _.includes({ 'a': 1, 'b': 2 }, 1); + * // => true + * + * _.includes('abcd', 'bc'); + * // => true + */ + includes: function (collection, value) { + if (Array.isArray(collection) || typeof collection === 'string') { + return collection.includes(value); + } + for (var key in collection) { + if (collection.hasOwnProperty(key)) { + if (collection[key] === value) { + return true; + } + } + } + return false; + }, + + /** + * Gets the size of `collection` by returning its length for array and strings. + * For objects it returns the number of enumerable string keyed + * properties. + * + * @param {Array|Object|string} collection The collection to inspect. + * @returns {number} Returns the collection size. + * @example + * + * size([1, 2, 3]) + * // => 3 + * + * size({ 'a': 1, 'b': 2 }) + * // => 2 + * + * size('pebbles') + * // => 7 + */ + size: function (collection) { + // eslint-disable-next-line lodash/prefer-is-nil + if (collection === null || collection === undefined) { + return 0; + } + if (Array.isArray(collection) || typeof collection === 'string') { + return collection.length; + } + + return Object.keys(collection).length; + }, + + /** + * Converts all elements in `array` into a string separated by `separator`. + * + * @param {Array} array The array to convert. + * @param {string} [separator=','] The element separator. + * @returns {string} Returns the joined string. + * @example + * + * _.join(['a', 'b', 'c'], '~'); + * // => 'a~b~c' + */ + join: function (array, separator) { + if (array === null) { + return ''; + } + return array.join(separator); + }, + + /** + * Removes trailing whitespace or specified characters from `string`. + * + * @param {string} [string=''] The string to trim. + * @param {string} [chars=whitespace] The characters to trim. + * @returns {string} Returns the trimmed string. + * @example + * + * trimEnd(' abc ') + * // => ' abc' + * + * trimEnd('-_-abc-_-', '_-') + * // => '-_-abc' + */ + trimEnd: function (string, chars) { + if (!string) { + return ''; + } + if (string && !chars) { + return string.replace(/\s*$/, ''); + } + chars += '$'; + return string.replace(new RegExp(chars, 'g'), ''); + }, + + /** + * Returns the index of the first + * element `predicate` returns truthy for. + * + * @param {Array} array The array to inspect. + * @param {Object} predicate The exact object to be searched for in the array. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.findIndex(users, { 'user': 'fred', 'active': false }); + * // => 1 + * + * _.findIndex(users, {'active' : false}); + * // => 0 + * + */ + findIndex: function (array, predicate) { + var length = array === null ? 0 : array.length, + index = -1, + keys = Object.keys(predicate), + found, i; + if (!length) { + return -1; + } + for (i = 0; i < array.length; i++) { + found = true; + // eslint-disable-next-line no-loop-func + keys.forEach((key) => { + if (!(array[i][key] && array[i][key] === predicate[key])) { + found = false; + } + }); + if (found) { + index = i; + break; + } + } + return index; + }, + + /** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @param {Object} object The object to query. + * @param {string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * const object = { a: {b : 'c'} } + * + * + * get(object, 'a.b.c', 'default') + * // => 'default' + * + * get(object, 'a.b', 'default') + * // => 'c' + */ + get: function (object, path, defaultValue) { + if (object === null) { + return undefined; + } + var arr = path.split('.'), + res = object, + i; + for (i = 0; i < arr.length; i++) { + res = res[arr[i]]; + if (res === undefined) { + return defaultValue; + } + } + return res; + }, + + /** + * Checks if `predicate` returns truthy for **all** elements of `array`. + * Iteration is stopped once `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @param {Array} array The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + * @example + * + * every([true, 1, null, 'yes'], Boolean) + * // => false + */ + every: function (array, predicate) { + var index = -1, + length = array === null ? 0 : array.length; + + while (++index < length) { + if (!predicate(array[index], index, array)) { + return false; + } + } + return true; + } + +}; diff --git a/codegens/java-native/lib/parseRequest.js b/codegens/java-native/lib/parseRequest.js new file mode 100644 index 000000000..4114ad734 --- /dev/null +++ b/codegens/java-native/lib/parseRequest.js @@ -0,0 +1,250 @@ + +var _ = require('./lodash'), + sanitize = require('./util').sanitize; + +/** +* parses body of request and returns urlencoded string +* +* @param {Object} requestBody - json object respresenting body of request +* @param {Boolean} trimFields - indicates whether to trim fields of body +* @returns {String} - urlencoded string for request body +*/ +function parseUrlencode (requestBody, trimFields) { +// reducing array of urlencoded form data to array of strings + return _.reduce(requestBody[requestBody.mode], function (accumalator, data) { + if (!data.disabled) { + accumalator.push(`${sanitize(data.key, trimFields)}=${sanitize(data.value, trimFields)}`.replace(/&/g, '%26')); + } + return accumalator; + }, []).join('&'); +} + +/** +* returns java code snippet for adding file to the request body +* +* @param {String} indentString - string for indentation +* @returns {String} - code snippet of java for uploading file +*/ +function generateFormFile (indentString) { + + return 'BiConsumer uploadFileFunction = (String src, String key) -> {\n' + + indentString + 'try {\n' + + indentString.repeat(2) + 'File uploadFile = new File(src);\n' + + indentString.repeat(2) + 'String fileName = uploadFile.getName();\n' + + indentString.repeat(2) + 'String name = key!=null?key:fileName;\n' + + indentString.repeat(2) + 'writer.append("--" + boundary).append(LINE_FEED)\n' + + indentString.repeat(3) + '.append("Content-Disposition: form-data; name="+name+";filename="+fileName)\n' + + indentString.repeat(3) + '.append(LINE_FEED)\n' + + indentString.repeat(3) + '.append("Content-Type: "+ URLConnection.' + + 'guessContentTypeFromName(fileName)).append(LINE_FEED)\n' + + indentString.repeat(3) + '.append("Content-Transfer-Encoding: binary")\n' + + indentString.repeat(3) + '.append(LINE_FEED)\n' + + indentString.repeat(3) + '.append(LINE_FEED);\n' + + indentString.repeat(2) + 'writer.flush();\n' + + indentString.repeat(2) + 'FileInputStream inputStream = new FileInputStream(uploadFile);\n' + + indentString.repeat(2) + 'byte[] buffer = new byte[4096];\n' + + indentString.repeat(2) + 'int bytesRead = -1;\n' + + indentString.repeat(2) + 'while ((bytesRead = inputStream.read(buffer)) != -1) {\n' + + indentString.repeat(3) + 'out.write(buffer, 0, bytesRead);\n' + + indentString.repeat(2) + '}\n' + + indentString.repeat(2) + 'out.flush();\n' + + indentString.repeat(2) + 'inputStream.close();\n' + + indentString.repeat(2) + 'writer.append(LINE_FEED).flush();\n' + + indentString.repeat(2) + '} catch (IOException e) {\n' + + indentString.repeat(3) + 'e.printStackTrace();\n' + + indentString.repeat(2) + '}\n' + + indentString + '};\n'; + +} + +/** +* returns java code snippet for adding form data to the request body +* +* @param {String} indentString - string for indentation +* @returns {String} - code snippet of java for uploading form data +*/ +function generateFormField (indentString) { + + return 'BiConsumer addFormField = (name, key) -> {\n' + + indentString + 'writer.append("--" + boundary).append(LINE_FEED)\n' + + indentString.repeat(2) + '.append("Content-Disposition: form-data; name="+name)\n' + + indentString.repeat(2) + '.append(LINE_FEED)\n' + + indentString.repeat(2) + '.append("Content-Type: text/plain; charset=UTF-8").append(LINE_FEED)\n' + + indentString.repeat(2) + '.append(LINE_FEED)\n' + + indentString.repeat(2) + '.append(key)\n' + + indentString.repeat(2) + '.append(LINE_FEED);\n' + + indentString + 'writer.flush();\n' + + indentString + '};\n'; + +} + +/** +* parses body of request and creates java code snippet for adding form data +* +* @param {Object} requestBody - JSON object representing body of request +* @param {String} indentString - string for indentation +* @param {Boolean} trimFields - indicates whether to trim fields of body +* @returns {String} - code snippet of java for multipart formdata +*/ +function parseFormData (requestBody, indentString, trimFields) { + var fileFunctionGenerated = false, + formFunctionGenerated = false; + return _.reduce(requestBody[requestBody.mode], function (body, data) { + if (data.disabled) { + return body; + } + if (data.type === 'file') { + if (!fileFunctionGenerated) { + body += generateFormFile(indentString); + fileFunctionGenerated = true; + } + body += `uploadFileFunction.accept("${data.src}","${sanitize(data.key, trimFields)}");\n`; + + } + else { + if (!formFunctionGenerated) { + body += generateFormField(indentString); + formFunctionGenerated = true; + } + !data.value && (data.value = ''); + body += `addFormField.accept("${sanitize(data.key, trimFields)}","${sanitize(data.value, trimFields)}");\n`; + + } + return body; + }, ''); +} + + +/** +* returns java code snippet for adding file to the request body +* +* @returns {String} - header java code snippet for form data +*/ +function generateBoilerPlateHeader () { + return 'PrintWriter writer = new PrintWriter(new OutputStreamWriter(out, "UTF-8"),true);\n' + + 'final String LINE_FEED = "\\r\\n";\n'; +} + +/** +* returns java code snippet for adding file to the request body +* +* @returns {String} - footer java code snippet for form data +*/ +function generateBoilerPlateFooter () { + return 'writer.append("--" + boundary + "--").append(LINE_FEED);\n' + + 'writer.close();\n' + + 'out.close();\n'; +} + + +/** +* parses request object and returns java code snippet for adding request body +* +* @param {Object} requestBody - JSON object representing body of request +* @param {String} indentString - string for indentation +* @param {Boolean} trimFields - indicates whether to trim fields of body +* @returns {String} - code snippet of java parsed from request object +*/ +function parseBody (requestBody, indentString, trimFields) { + var snippet = 'con.setDoInput(true);\n' + + 'DataOutputStream out = new DataOutputStream(con.getOutputStream());\n'; + if (!_.isEmpty(requestBody)) { + + switch (requestBody.mode) { + case 'urlencoded': + snippet += `out.writeBytes("${parseUrlencode(requestBody, trimFields)}");\n` + + 'out.flush();\n' + + 'out.close();\n'; + return snippet; + case 'raw': + snippet += `out.writeBytes(${JSON.stringify(requestBody[requestBody.mode])});\n` + + 'out.flush();\n' + + 'out.close();\n'; + return snippet; + // eslint-disable-next-line no-case-declarations + case 'graphql': + let query = requestBody[requestBody.mode].query, + graphqlVariables; + try { + graphqlVariables = JSON.parse(requestBody[requestBody.mode].variables); + } + catch (e) { + graphqlVariables = {}; + } + snippet += `out.writeBytes("${sanitize(JSON.stringify({ + query: query, + variables: graphqlVariables + }), trimFields)}");\n`; + snippet += 'out.flush();\n' + + 'out.close();\n'; + return snippet; + case 'formdata': + snippet += generateBoilerPlateHeader(); + snippet += requestBody.formdata.length ? + `${parseFormData(requestBody, indentString, trimFields)}` : + 'writer.append("--" + boundary).append(LINE_FEED)\n' + + indentString + '.append("Content-Disposition: form-data;")\n' + + indentString + '.append(LINE_FEED)\n' + + indentString + '.append("Content-Type: text/plain; charset=UTF-8")\n' + + indentString + '.append(LINE_FEED);\n' + + 'writer.flush();\n'; + snippet += generateBoilerPlateFooter(); + return snippet; + + case 'file': + snippet += generateBoilerPlateHeader(); + snippet += generateFormFile(indentString); + snippet += `uploadFileFunction.accept("${requestBody.file.src}",null);\n`; + snippet += generateBoilerPlateFooter(); + return snippet; + default: + snippet += 'out.writeBytes("");\n' + + 'out.close();\n'; + return snippet; + } + } + snippet += 'out.writeBytes("");\n' + + 'out.close();\n'; + + return snippet; +} + +/** +* Parses header in Postman-SDK request and returns code snippet of java for adding headers +* +* @param {Object} request - Postman SDK request object +* @returns {String} - code snippet for adding headers in java +*/ +function parseHeader (request) { + var headerArray = request.toJSON().header, + headerSnippet = ''; + + if (!_.isEmpty(headerArray)) { + headerArray = _.reject(headerArray, 'disabled'); + headerSnippet += _.reduce(headerArray, function (accumalator, header) { + accumalator += `con.setRequestProperty("${sanitize(header.key, true)}", ` + + `"${sanitize(header.value)}");\n`; + return accumalator; + }, ''); + } + return headerSnippet; +} + +/** +* returns content-type of request body if available else returns text/plain as default +* +* @param {Object} request - Postman SDK request object +* @returns {String}- content-type of request body +*/ +function parseContentType (request) { + if (request.body && request.body.mode === 'graphql') { + return 'application/json'; + } + return request.getHeaders({enabled: true, ignoreCase: true})['content-type'] || 'text/plain'; +} + +module.exports = { + parseBody: parseBody, + parseHeader: parseHeader, + parseContentType: parseContentType +}; diff --git a/codegens/java-native/lib/util.js b/codegens/java-native/lib/util.js new file mode 100644 index 000000000..4ed8cd8c7 --- /dev/null +++ b/codegens/java-native/lib/util.js @@ -0,0 +1,118 @@ +module.exports = { + /** + * sanitizes input string by handling escape characters eg: converts '''' to '\'\'' + * and trim input if required + * + * @param {String} inputString - Input string being sanitized + * @param {Boolean} [trim] - indicates whether to trim string or not + * @returns {String} + */ + sanitize: function (inputString, trim) { + if (typeof inputString !== 'string') { + return ''; + } + inputString = inputString.replace(/\\/g, '\\\\').replace(/"/g, '\\"'); + return trim ? inputString.trim() : inputString; + + }, + + /** + * sanitizes input options + * + * @param {Object} options - Options provided by the user + * @param {Array} optionsArray - options array received from getOptions function + * + * @returns {Object} - Sanitized options object + */ + sanitizeOptions: function (options, optionsArray) { + var result = {}, + defaultOptions = {}, + id; + optionsArray.forEach((option) => { + defaultOptions[option.id] = { + default: option.default, + type: option.type + }; + if (option.type === 'enum') { + defaultOptions[option.id].availableOptions = option.availableOptions; + } + }); + + for (id in options) { + if (options.hasOwnProperty(id)) { + if (defaultOptions[id] === undefined) { + continue; + } + switch (defaultOptions[id].type) { + case 'boolean': + if (typeof options[id] !== 'boolean') { + result[id] = defaultOptions[id].default; + } + else { + result[id] = options[id]; + } + break; + case 'positiveInteger': + if (typeof options[id] !== 'number' || options[id] < 0) { + result[id] = defaultOptions[id].default; + } + else { + result[id] = options[id]; + } + break; + case 'enum': + if (!defaultOptions[id].availableOptions.includes(options[id])) { + result[id] = defaultOptions[id].default; + } + else { + result[id] = options[id]; + } + break; + default: + result[id] = options[id]; + } + } + } + + for (id in defaultOptions) { + if (defaultOptions.hasOwnProperty(id)) { + if (result[id] === undefined) { + result[id] = defaultOptions[id].default; + } + } + } + return result; + }, + + /** + * + * @param {Array} array - form data array + * @param {String} key - key of form data param + * @param {String} type - type of form data param(file/text) + * @param {String} val - value/src property of form data param + * @param {String} disabled - Boolean denoting whether the param is disabled or not + * @param {String} contentType - content type header of the param + * + * Appends a single param to form data array + */ + addFormParam: function (array, key, type, val, disabled, contentType) { + if (type === 'file') { + array.push({ + key: key, + type: type, + src: val, + disabled: disabled, + contentType: contentType + }); + } + else { + array.push({ + key: key, + type: type, + value: val, + disabled: disabled, + contentType: contentType + }); + } + } +}; diff --git a/codegens/java-native/npm-shrinkwrap.json b/codegens/java-native/npm-shrinkwrap.json new file mode 100644 index 000000000..419f6cd68 --- /dev/null +++ b/codegens/java-native/npm-shrinkwrap.json @@ -0,0 +1,5 @@ +{ + "name": "@postman/codegen-java-native", + "version": "0.0.1", + "lockfileVersion": 1 +} diff --git a/codegens/java-native/npm/test-lint.js b/codegens/java-native/npm/test-lint.js new file mode 100644 index 000000000..b113b8bfd --- /dev/null +++ b/codegens/java-native/npm/test-lint.js @@ -0,0 +1,58 @@ +#!/usr/bin/env node +var shell = require('shelljs'), + chalk = require('chalk'), + async = require('async'), + ESLintCLIEngine = require('eslint').CLIEngine, + + /** + * The list of source code files / directories to be linted. + * + * @type {Array} + */ + LINT_SOURCE_DIRS = [ + './lib', + './bin', + './test', + './examples/*.js', + './npm/*.js', + './index.js' + ]; + +module.exports = function (exit) { + // banner line + console.info(chalk.yellow.bold('\nLinting files using eslint...')); + + async.waterfall([ + + /** + * Instantiates an ESLint CLI engine and runs it in the scope defined within LINT_SOURCE_DIRS. + * + * @param {Function} next - The callback function whose invocation marks the end of the lint test run. + * @returns {*} + */ + function (next) { + next(null, (new ESLintCLIEngine()).executeOnFiles(LINT_SOURCE_DIRS)); + }, + + /** + * Processes a test report from the Lint test runner, and displays meaningful results. + * + * @param {Object} report - The overall test report for the current lint test. + * @param {Object} report.results - The set of test results for the current lint run. + * @param {Function} next - The callback whose invocation marks the completion of the post run tasks. + * @returns {*} + */ + function (report, next) { + var errorReport = ESLintCLIEngine.getErrorResults(report.results); + // log the result to CLI + console.info(ESLintCLIEngine.getFormatter()(report.results)); + // log the success of the parser if it has no errors + (errorReport && !errorReport.length) && console.info(chalk.green('eslint ok!')); + // ensure that the exit code is non zero in case there was an error + next(Number(errorReport && errorReport.length) || 0); + } + ], exit); +}; + +// ensure we run this script exports if this is a direct stdin.tty run +!module.parent && module.exports(shell.exit); diff --git a/codegens/java-native/npm/test-newman.js b/codegens/java-native/npm/test-newman.js new file mode 100644 index 000000000..0c8559a8e --- /dev/null +++ b/codegens/java-native/npm/test-newman.js @@ -0,0 +1,59 @@ +#!/usr/bin/env node +/* eslint-env node, es6 */ +// --------------------------------------------------------------------------------------------------------------------- +// This script is intended to execute all unit tests. +// --------------------------------------------------------------------------------------------------------------------- + +var shell = require('shelljs'), + + // set directories and files for test and coverage report + path = require('path'), + + NYC = require('nyc'), + chalk = require('chalk'), + recursive = require('recursive-readdir'), + + COV_REPORT_PATH = '.coverage', + SPEC_SOURCE_DIR = path.join(__dirname, '..', 'test', 'newman'); + +module.exports = function (exit) { + // banner line + console.info(chalk.yellow.bold('Running newman tests using mocha on node...')); + + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); + + var Mocha = require('mocha'), + nyc = new NYC({ + reportDir: COV_REPORT_PATH, + tempDirectory: COV_REPORT_PATH, + reporter: ['text', 'lcov', 'text-summary'], + exclude: ['config', 'test'], + hookRunInContext: true, + hookRunInThisContext: true + }); + + nyc.wrap(); + // add all spec files to mocha + recursive(SPEC_SOURCE_DIR, function (err, files) { + if (err) { console.error(err); return exit(1); } + + var mocha = new Mocha({ timeout: 1000 * 60 }); + + files.filter(function (file) { // extract all test files + return (file.substr(-8) === '.test.js'); + }).forEach(mocha.addFile.bind(mocha)); + + mocha.run(function (runError) { + runError && console.error(runError.stack || runError); + + nyc.reset(); + nyc.writeCoverageFile(); + nyc.report(); + exit(runError ? 1 : 0); + }); + }); +}; + +// ensure we run this script exports if this is a direct stdin.tty run +!module.parent && module.exports(shell.exit); diff --git a/codegens/java-native/npm/test-unit.js b/codegens/java-native/npm/test-unit.js new file mode 100644 index 000000000..0de7fd529 --- /dev/null +++ b/codegens/java-native/npm/test-unit.js @@ -0,0 +1,59 @@ +#!/usr/bin/env node +/* eslint-env node, es6 */ +// --------------------------------------------------------------------------------------------------------------------- +// This script is intended to execute all unit tests. +// --------------------------------------------------------------------------------------------------------------------- + +var shell = require('shelljs'), + + // set directories and files for test and coverage report + path = require('path'), + + NYC = require('nyc'), + chalk = require('chalk'), + recursive = require('recursive-readdir'), + + COV_REPORT_PATH = '.coverage', + SPEC_SOURCE_DIR = path.join(__dirname, '..', 'test', 'unit'); + +module.exports = function (exit) { + // banner line + console.info(chalk.yellow.bold('Running unit tests using mocha on node...')); + + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); + + var Mocha = require('mocha'), + nyc = new NYC({ + reportDir: COV_REPORT_PATH, + tempDirectory: COV_REPORT_PATH, + reporter: ['text', 'lcov', 'text-summary'], + exclude: ['config', 'test'], + hookRunInContext: true, + hookRunInThisContext: true + }); + + nyc.wrap(); + // add all spec files to mocha + recursive(SPEC_SOURCE_DIR, function (err, files) { + if (err) { console.error(err); return exit(1); } + + var mocha = new Mocha({ timeout: 1000 * 60 }); + + files.filter(function (file) { // extract all test files + return (file.substr(-8) === '.test.js'); + }).forEach(mocha.addFile.bind(mocha)); + + mocha.run(function (runError) { + runError && console.error(runError.stack || runError); + + nyc.reset(); + nyc.writeCoverageFile(); + nyc.report(); + exit(runError ? 1 : 0); + }); + }); +}; + +// ensure we run this script exports if this is a direct stdin.tty run +!module.parent && module.exports(shell.exit); diff --git a/codegens/java-native/npm/test.js b/codegens/java-native/npm/test.js new file mode 100644 index 000000000..471858159 --- /dev/null +++ b/codegens/java-native/npm/test.js @@ -0,0 +1,20 @@ +#!/usr/bin/env node +var chalk = require('chalk'), + exit = require('shelljs').exit, + prettyms = require('pretty-ms'), + startedAt = Date.now(), + name = require('../package.json').name; + +require('async').series([ + require('./test-lint'), + require('./test-unit'), + require('./test-newman') + // Add a separate folder for every new suite of tests + // require('./test-unit') + // require('./test-browser') + // require('./test-integration') +], function (code) { + // eslint-disable-next-line max-len + console.info(chalk[code ? 'red' : 'green'](`\n${name}: duration ${prettyms(Date.now() - startedAt)}\n${name}: ${code ? 'not ok' : 'ok'}!`)); + exit(code && (typeof code === 'number' ? code : 1) || 0); +}); diff --git a/codegens/java-native/package.json b/codegens/java-native/package.json new file mode 100644 index 000000000..cde1f544a --- /dev/null +++ b/codegens/java-native/package.json @@ -0,0 +1,34 @@ +{ + "name": "@postman/codegen-java-native", + "version": "0.0.1", + "description": "Converts Postman SDK Requests to java native code snippet", + "main": "index.js", + "com_postman_plugin": { + "type": "code_generator", + "lang": "java", + "variant": "Native", + "syntax_mode": "java" + }, + "directories": { + "lib": "lib", + "test": "test" + }, + "scripts": { + "test": "node npm/test.js", + "test-lint": "node npm/test-lint.js", + "test-unit": "node npm/test-unit.js", + "test-newman": "node npm/test-newman.js" + }, + "repository": { + "type": "git", + "url": "" + }, + "author": "Postman Labs ", + "license": "Apache-2.0", + "homepage": "https://github.com/postmanlabs/code-generators/tree/master/codegens/java-native", + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=8" + } +} diff --git a/codegens/java-native/test/.eslintrc b/codegens/java-native/test/.eslintrc new file mode 100644 index 000000000..9d477e31e --- /dev/null +++ b/codegens/java-native/test/.eslintrc @@ -0,0 +1,30 @@ +{ + "plugins": [ + "mocha" + ], + "env": { + "mocha": true, + "node": true, + "es6": true + }, + "rules": { + // Mocha + "mocha/handle-done-callback": "error", + "mocha/max-top-level-suites": "error", + "mocha/no-exclusive-tests": "error", + "mocha/no-global-tests": "error", + "mocha/no-hooks-for-single-case": "off", + "mocha/no-hooks": "off", + "mocha/no-identical-title": "error", + "mocha/no-mocha-arrows": "error", + "mocha/no-nested-tests": "error", + "mocha/no-pending-tests": "error", + "mocha/no-return-and-callback": "error", + "mocha/no-sibling-hooks": "error", + "mocha/no-skipped-tests": "warn", + "mocha/no-synchronous-tests": "off", + "mocha/no-top-level-hooks": "warn", + "mocha/valid-test-description": "off", + "mocha/valid-suite-description": "off" + } +} diff --git a/codegens/java-native/test/newman/newman.test.js b/codegens/java-native/test/newman/newman.test.js new file mode 100644 index 000000000..6b6b472bd --- /dev/null +++ b/codegens/java-native/test/newman/newman.test.js @@ -0,0 +1,12 @@ +var runNewmanTest = require('../../../../test/codegen/newman/newmanTestUtil').runNewmanTest, + convert = require('../../lib/index').convert; + +describe('convert for different request types', function () { + var options = {indentCount: 3, indentType: 'Space', includeBoilerplate: true}, + testConfig = { + compileScript: 'javac -cp *: main.java', + runScript: 'java -cp *: main', + fileName: 'main.java' + }; + runNewmanTest(convert, options, testConfig); +}); diff --git a/codegens/java-native/test/unit/.gitkeep b/codegens/java-native/test/unit/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/codegens/java-native/test/unit/convert.test.js b/codegens/java-native/test/unit/convert.test.js new file mode 100644 index 000000000..506202edf --- /dev/null +++ b/codegens/java-native/test/unit/convert.test.js @@ -0,0 +1,331 @@ +var expect = require('chai').expect, + sdk = require('postman-collection'), + sanitize = require('../../lib/util').sanitize, + convert = require('../../lib/index').convert, + getOptions = require('../../lib/index').getOptions, + mainCollection = require('../../../../test/codegen/newman/fixtures/basicCollection.json'); + +describe('java convert function', function () { + describe('convert function', function () { + var request = new sdk.Request(mainCollection.item[0].request), + snippetArray, + options = { + includeBoilerplate: true, + indentType: 'Tab', + indentCount: 2 + }; + const SINGLE_SPACE = ' '; + + it('should generate snippet with default options given no options', function () { + convert(request, function (error, snippet) { + if (error) { + expect.fail(null, null, error); + return; + } + snippetArray = snippet.split('\n'); + for (var i = 0; i < snippetArray.length; i++) { + if (snippetArray[i].startsWith('public class main {')) { + expect(snippetArray[i + 1].substr(0, 4)).to.equal(SINGLE_SPACE.repeat(4)); + expect(snippetArray[i + 1].charAt(4)).to.not.equal(SINGLE_SPACE); + } + } + }); + }); + + it('should return snippet with boilerplate code given option', function () { + convert(request, { includeBoilerplate: true }, function (error, snippet) { + if (error) { + expect.fail(null, null, error); + return; + } + expect(snippet).to.include('import java.io.*;\nimport javax.net.ssl.HttpsURLConnection;\n' + + 'import java.net.*;\nimport java.lang.reflect.*;\nimport java.util.function.BiConsumer;\n' + + 'public class main {\n'); + }); + }); + + it('should return snippet with requestTimeout given option', function () { + convert(request, { requestTimeout: 1000 }, function (error, snippet) { + if (error) { + expect.fail(null, null, error); + return; + } + expect(snippet).to.include('.setConnectTimeout(1000)'); + }); + }); + + it('should return snippet without followRedirect given option', function () { + convert(request, { followRedirect: true }, function (error, snippet) { + if (error) { + expect.fail(null, null, error); + return; + } + expect(snippet).to.not.include('.setInstanceFollowRedirects(false)'); + }); + }); + + it('should generate snippet with Tab as an indent type with exact indent count', function () { + convert(request, options, function (error, snippet) { + if (error) { + expect.fail(null, null, error); + return; + } + snippetArray = snippet.split('\n'); + for (var i = 0; i < snippetArray.length; i++) { + if (snippetArray[i].startsWith('public class main {')) { + expect(snippetArray[i + 1].charAt(0)).to.equal('\t'); + expect(snippetArray[i + 1].charAt(1)).to.equal('\t'); + expect(snippetArray[i + 1].charAt(2)).to.not.equal('\t'); + } + } + }); + }); + + it('should trim header keys and not trim header values', function () { + var request = new sdk.Request({ + 'method': 'GET', + 'header': [ + { + 'key': ' key_containing_whitespaces ', + 'value': ' value_containing_whitespaces ' + } + ], + 'url': { + 'raw': 'https://google.com', + 'protocol': 'https', + 'host': [ + 'google', + 'com' + ] + } + }); + convert(request, {}, function (error, snippet) { + if (error) { + expect.fail(null, null, error); + } + expect(snippet).to.be.a('string'); + expect(snippet).to.include('.setRequestProperty("key_containing_whitespaces", ' + + '" value_containing_whitespaces ")'); + }); + }); + + it('should generate snippets for no files in form data', function () { + var request = new sdk.Request({ + 'method': 'POST', + 'header': [], + 'body': { + 'mode': 'formdata', + 'formdata': [ + { + 'key': 'no file', + 'value': '', + 'type': 'file', + 'src': [] + }, + { + 'key': 'no src', + 'value': '', + 'type': 'file' + }, + { + 'key': 'invalid src', + 'value': '', + 'type': 'file', + 'src': {} + } + ] + }, + 'url': { + 'raw': 'https://postman-echo.com/post', + 'protocol': 'https', + 'host': [ + 'postman-echo', + 'com' + ], + 'path': [ + 'post' + ] + } + }); + convert(request, {}, function (error, snippet) { + if (error) { + expect.fail(null, null, error); + } + expect(snippet).to.be.a('string'); + expect(snippet).to.include('"/path/to/file","no file"'); + expect(snippet).to.include('"/path/to/file","no src"'); + expect(snippet).to.include('"/path/to/file","invalid src"'); + expect(snippet).to.include('BiConsumer uploadFileFunction'); + }); + }); + + it('should generate snippets for mixed form data of text and files', function () { + var request = new sdk.Request({ + 'method': 'POST', + 'header': [ + { + 'key': 'Content-Type', + 'value': 'application/x-www-form-urlencoded', + 'disabled': true + }, + { + 'key': 'content-type', + 'value': 'application/json', + 'disabled': true + } + ], + 'body': { + 'mode': 'formdata', + 'formdata': [ + { + 'key': 'fdjks', + 'value': '', + 'type': 'text' + }, + { + 'key': 'sdf', + 'src': 'package.json', + 'type': 'file' + }, + { + 'key': '12', + 'value': '"23"', + 'description': '', + 'type': 'text' + }, + { + 'key': '\'123\'', + 'value': '\'1"23"4\'', + 'description': '', + 'type': 'text' + }, + { + 'key': '\'"23\\"4\\""\'', + 'value': '', + 'description': '', + 'type': 'text', + 'disabled': true + } + ] + }, + 'url': { + 'raw': 'https://postman-echo.com/post', + 'protocol': 'https', + 'host': [ + 'postman-echo', + 'com' + ], + 'path': [ + 'post' + ] + } + }); + convert(request, {}, function (error, snippet) { + if (error) { + expect.fail(null, null, error); + } + expect(snippet).to.be.a('string'); + expect(snippet).to.include('uploadFileFunction.accept("package.json","sdf")'); + expect(snippet).to.include('addFormField.accept("12","\\"23\\"")'); + expect(snippet).to.include('addFormField.accept("\'123\'","\'1\\"23\\"4\'")'); + expect(snippet).to.include('addFormField.accept("fdjks","")'); + expect(snippet).to.include('BiConsumer uploadFileFunction'); + expect(snippet).to.include('BiConsumer addFormField'); + }); + }); + }); + + + it('should generate snippets for Patch request', function () { + var request = new sdk.Request({ + 'method': 'PATCH', + 'header': [ + { + 'key': 'Content-Type', + 'value': 'text/plain' + } + ], + 'body': { + 'mode': 'raw', + 'raw': 'Curabitur auctor, elit nec pulvinar porttitor,' + }, + 'url': { + 'raw': 'https://postman-echo.com/patch', + 'protocol': 'https', + 'host': [ + 'postman-echo', + 'com' + ], + 'path': [ + 'patch' + ] + } + }); + convert(request, {}, function (error, snippet) { + if (error) { + expect.fail(null, null, error); + } + expect(snippet).to.be.a('string'); + expect(snippet).to.include('Field methodsField'); + expect(snippet).to.include('methodsField.set(null, methods)'); + expect(snippet).to.include('"Curabitur auctor, elit nec pulvinar porttitor,'); + }); + }); + + + it('should generate snippets for uploading file', function () { + var request = new sdk.Request({ + 'method': 'POST', + 'header': [], + 'body': { + 'mode': 'file', + 'file': { + 'src': 'dummy.png' + } + }, + 'url': { + 'raw': 'https://postman-echo.com/post', + 'protocol': 'https', + 'host': [ + 'postman-echo', + 'com' + ], + 'path': [ + 'post' + ] + } + }); + convert(request, {}, function (error, snippet) { + if (error) { + expect.fail(null, null, error); + } + expect(snippet).to.be.a('string'); + expect(snippet).to.include('uploadFileFunction.accept("dummy.png",null)'); + expect(snippet).to.include('BiConsumer uploadFileFunction'); + }); + }); + + + describe('getOptions function', function () { + it('should return array of options for csharp-restsharp converter', function () { + expect(getOptions()).to.be.an('array'); + }); + + it('should return all the valid options', function () { + expect(getOptions()[0]).to.have.property('id', 'includeBoilerplate'); + expect(getOptions()[1]).to.have.property('id', 'indentCount'); + expect(getOptions()[2]).to.have.property('id', 'indentType'); + expect(getOptions()[3]).to.have.property('id', 'requestTimeout'); + expect(getOptions()[4]).to.have.property('id', 'followRedirect'); + expect(getOptions()[5]).to.have.property('id', 'trimRequestBody'); + }); + }); + + describe('sanitize function', function () { + it('should handle invalid parameters', function () { + expect(sanitize(123, false)).to.equal(''); + expect(sanitize(' inputString', true)).to.equal('inputString'); + }); + }); + +}); diff --git a/codegens/java-native/test/unit/dummy.js b/codegens/java-native/test/unit/dummy.js deleted file mode 100644 index 3cf8db931..000000000 --- a/codegens/java-native/test/unit/dummy.js +++ /dev/null @@ -1,36 +0,0 @@ - -var expect = require('chai').expect, -sdk = require('postman-collection'), -sanitize = require('../../lib/util').sanitize, -convert = require('../../lib/index').convert, -getOptions = require('../../lib/index').getOptions, -mainCollection = require('../../../../test/codegen/newman/fixtures/basicCollection.json'); - - - -var request = new sdk.Request({ - "method": "POST", - "header": [], - "body": { - "mode": "file", - "file": { - "src": "dummy.png" - } - }, - "url": { - "raw": "https://postman-echo.com/post", - "protocol": "https", - "host": [ - "postman-echo", - "com" - ], - "path": [ - "post" - ] - } -}); - convert(request, {}, function (error, snippet) { - console.log("snippet executed"); - console.log(snippet); - -}); \ No newline at end of file diff --git a/codegens/java-native/test/unit/fixtures/testcollection/collection.json b/codegens/java-native/test/unit/fixtures/testcollection/collection.json new file mode 100644 index 000000000..5862ab49b --- /dev/null +++ b/codegens/java-native/test/unit/fixtures/testcollection/collection.json @@ -0,0 +1,983 @@ +{ + "info": { + "name": "Code-Gen Test Cases", + "_postman_id": "41182fad-912e-6bc9-d6b9-dfb6f5bf5ffb", + "description": "This collection contains requests that will be used to test validity of plugin created to convert postman request into code snippet of particular language.", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + }, + "item": [ + { + "name": "Request Headers with disabled headers", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "var responseJSON;", + "try {", + " tests[\"Body contains headers\"] = responseBody.has(\"headers\");", + " responseJSON = JSON.parse(responseBody);", + " tests[\"Header contains host\"] = \"host\" in responseJSON.headers;", + " tests[\"Header contains test parameter sent as part of request header\"] = \"my-sample-header\" in responseJSON.headers;", + "}", + "catch (e) { }", + "", + "", + "", + "" + ] + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "my-sample-header", + "value": "Lorem ipsum dolor sit amet" + }, + { + "key": "not-disabled-header", + "value": "ENABLED" + }, + { + "key": "disabled header", + "value": "DISABLED", + "disabled": true + } + ], + "body": {}, + "url": { + "raw": "https://postman-echo.com/headers", + "protocol": "https", + "host": [ + "postman-echo", + "com" + ], + "path": [ + "headers" + ] + }, + "description": "A `GET` request to this endpoint returns the list of all request headers as part of the response JSON.\nIn Postman, sending your own set of headers through the [Headers tab](https://www.getpostman.com/docs/requests#headers?source=echo-collection-app-onboarding) will reveal the headers as part of the response." + }, + "response": [] + }, + { + "name": "GET Request with disabled query", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "var responseJSON;", + "", + "try { ", + " responseJSON = JSON.parse(responseBody); ", + " tests['response is valid JSON'] = true;", + "}", + "catch (e) { ", + " responseJSON = {}; ", + " tests['response is valid JSON'] = false;", + "}", + "", + "tests['response json contains headers'] = _.has(responseJSON, 'headers');", + "tests['response json contains args'] = _.has(responseJSON, 'args');", + "tests['response json contains url'] = _.has(responseJSON, 'url');", + "", + "tests['args key contains argument passed as url parameter'] = ('test' in responseJSON.args);", + "tests['args passed via request url params has value \"123\"'] = (_.get(responseJSON, 'args.test') === \"123\");" + ] + } + } + ], + "request": { + "method": "GET", + "header": [], + "body": {}, + "url": { + "raw": "https://postman-echo.com/get?test=123&anotherone=232", + "protocol": "https", + "host": [ + "postman-echo", + "com" + ], + "path": [ + "get" + ], + "query": [ + { + "key": "test", + "value": "123", + "equals": true + }, + { + "key": "anotherone", + "value": "232", + "equals": true + }, + { + "key": "anotheroneone", + "value": "sdfsdf", + "equals": true, + "disabled": true + } + ] + }, + "description": "The HTTP `GET` request method is meant to retrieve data from a server. The data\nis identified by a unique URI (Uniform Resource Identifier). \n\nA `GET` request can pass parameters to the server using \"Query String \nParameters\". For example, in the following request,\n\n> http://example.com/hi/there?hand=wave\n\nThe parameter \"hand\" has the value \"wave\".\n\nThis endpoint echoes the HTTP headers, request parameters and the complete\nURI requested." + }, + "response": [] + }, + { + "name": "POST Raw Text", + "event": [ + { + "listen": "test", + "script": { + "id": "753f8a33-adb6-402f-8d19-386c1981ecb6", + "type": "text/javascript", + "exec": [ + "var responseJSON;", + "", + "try { ", + " responseJSON = JSON.parse(responseBody); ", + " tests['response is valid JSON'] = true;", + "}", + "catch (e) { ", + " responseJSON = {}; ", + " tests['response is valid JSON'] = false;", + "}", + "", + "", + "tests['response has post data'] = _.has(responseJSON, 'data');", + "tests['response matches the data posted'] = (responseJSON.data && responseJSON.data.length === 256);", + "", + "tests[\"content-type equals text/plain\"] = responseJSON && responseJSON.headers && (responseJSON.headers[\"content-type\"] === 'text/plain');" + ] + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "text/plain" + } + ], + "body": { + "mode": "raw", + "raw": "\"'Duis posuere augue vel cursus pharetra. In luctus a ex nec pretium. Praesent neque quam, tincidunt nec leo eget, rutrum vehicula magna.\nMaecenas consequat elementum elit, \"id\" \"se\\\"mper\" sem tristique et. Integer pulvinar enim quis consectetur interdum volutpat.'\"" + }, + "url": { + "raw": "https://postman-echo.com/post", + "protocol": "https", + "host": [ + "postman-echo", + "com" + ], + "path": [ + "post" + ] + }, + "description": "The HTTP `POST` request method is meant to transfer data to a server \n(and elicit a response). What data is returned depends on the implementation\nof the server.\n\nA `POST` request can pass parameters to the server using \"Query String \nParameters\", as well as the Request Body. For example, in the following request,\n\n> POST /hi/there?hand=wave\n>\n> \n\nThe parameter \"hand\" has the value \"wave\". The request body can be in multiple\nformats. These formats are defined by the MIME type of the request. The MIME \nType can be set using the ``Content-Type`` HTTP header. The most commonly used \nMIME types are:\n\n* `multipart/form-data`\n* `application/x-www-form-urlencoded`\n* `application/json`\n\nThis endpoint echoes the HTTP headers, request parameters, the contents of\nthe request body and the complete URI requested." + }, + "response": [] + }, + { + "name": "POST form data with file", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "var responseJSON;", + "", + "try { ", + " responseJSON = JSON.parse(responseBody); ", + " tests['response is valid JSON'] = true;", + "}", + "catch (e) { ", + " responseJSON = {}; ", + " tests['response is valid JSON'] = false;", + "}", + "", + "", + "tests['response has post data'] = _.has(responseJSON, 'data');", + "tests['response matches the data posted'] = (responseJSON.data && responseJSON.data.length === 256);", + "", + "tests[\"content-type equals text/plain\"] = responseJSON && responseJSON.headers && (responseJSON.headers[\"content-type\"] === 'text/plain');" + ] + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/x-www-form-urlencoded", + "disabled": true + }, + { + "key": "content-type", + "value": "application/json", + "disabled": true + } + ], + "body": { + "mode": "formdata", + "formdata": [ + { + "key": "fdjks", + "value": "dsf", + "type": "text" + }, + { + "key": "sdf", + "value": "", + "type": "text" + }, + { + "key": "12", + "value": "\"23\"", + "description": "", + "type": "text" + }, + { + "key": "'123'", + "value": "'\"23\\\"4\\\"\"'", + "description": "", + "type": "text" + }, + { + "key": "", + "value": "", + "description": "", + "type": "text", + "disabled": true + } + ] + }, + "url": { + "raw": "https://postman-echo.com/post", + "protocol": "https", + "host": [ + "postman-echo", + "com" + ], + "path": [ + "post" + ] + }, + "description": "The HTTP `POST` request method is meant to transfer data to a server \n(and elicit a response). What data is returned depends on the implementation\nof the server.\n\nA `POST` request can pass parameters to the server using \"Query String \nParameters\", as well as the Request Body. For example, in the following request,\n\n> POST /hi/there?hand=wave\n>\n> \n\nThe parameter \"hand\" has the value \"wave\". The request body can be in multiple\nformats. These formats are defined by the MIME type of the request. The MIME \nType can be set using the ``Content-Type`` HTTP header. The most commonly used \nMIME types are:\n\n* `multipart/form-data`\n* `application/x-www-form-urlencoded`\n* `application/json`\n\nThis endpoint echoes the HTTP headers, request parameters, the contents of\nthe request body and the complete URI requested." + }, + "response": [] + }, + { + "name": "POST urlencoded data with disabled entries", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "var responseJSON;", + "", + "try { ", + " responseJSON = JSON.parse(responseBody); ", + " tests['response is valid JSON'] = true;", + "}", + "catch (e) { ", + " responseJSON = {}; ", + " tests['response is valid JSON'] = false;", + "}", + "", + "", + "tests['response has post data'] = _.has(responseJSON, 'data');", + "tests['response matches the data posted'] = (responseJSON.data && responseJSON.data.length === 256);", + "", + "tests[\"content-type equals text/plain\"] = responseJSON && responseJSON.headers && (responseJSON.headers[\"content-type\"] === 'text/plain');" + ] + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/x-www-form-urlencoded" + } + ], + "body": { + "mode": "urlencoded", + "urlencoded": [ + { + "key": "1", + "value": "a", + "description": "", + "type": "text" + }, + { + "key": "2", + "value": "b", + "description": "", + "type": "text", + "disabled": true + }, + { + "key": "\"\"12\"\"", + "value": "\"23\"", + "description": "", + "type": "text" + }, + { + "key": "'1\"2\\\"\"3'", + "value": "'1\"23\"4'", + "description": "", + "type": "text" + } + ] + }, + "url": { + "raw": "https://postman-echo.com/post/?hardik=\"me\"", + "protocol": "https", + "host": [ + "postman-echo", + "com" + ], + "path": [ + "post", + "" + ], + "query": [ + { + "key": "hardik", + "value": "\"me\"", + "equals": true + } + ] + }, + "description": "The HTTP `POST` request method is meant to transfer data to a server \n(and elicit a response). What data is returned depends on the implementation\nof the server.\n\nA `POST` request can pass parameters to the server using \"Query String \nParameters\", as well as the Request Body. For example, in the following request,\n\n> POST /hi/there?hand=wave\n>\n> \n\nThe parameter \"hand\" has the value \"wave\". The request body can be in multiple\nformats. These formats are defined by the MIME type of the request. The MIME \nType can be set using the ``Content-Type`` HTTP header. The most commonly used \nMIME types are:\n\n* `multipart/form-data`\n* `application/x-www-form-urlencoded`\n* `application/json`\n\nThis endpoint echoes the HTTP headers, request parameters, the contents of\nthe request body and the complete URI requested." + }, + "response": [] + }, + { + "name": "POST json with raw", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "var responseJSON;", + "", + "try { ", + " responseJSON = JSON.parse(responseBody); ", + " tests['response is valid JSON'] = true;", + "}", + "catch (e) { ", + " responseJSON = {}; ", + " tests['response is valid JSON'] = false;", + "}", + "", + "", + "tests['response has post data'] = _.has(responseJSON, 'data');", + "tests['response matches the data posted'] = (responseJSON.data && responseJSON.data.length === 256);", + "", + "tests[\"content-type equals text/plain\"] = responseJSON && responseJSON.headers && (responseJSON.headers[\"content-type\"] === 'text/plain');" + ] + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"json\": \"Test-Test\"\n}" + }, + "url": { + "raw": "https://postman-echo.com/post", + "protocol": "https", + "host": [ + "postman-echo", + "com" + ], + "path": [ + "post" + ] + }, + "description": "The HTTP `POST` request method is meant to transfer data to a server \n(and elicit a response). What data is returned depends on the implementation\nof the server.\n\nA `POST` request can pass parameters to the server using \"Query String \nParameters\", as well as the Request Body. For example, in the following request,\n\n> POST /hi/there?hand=wave\n>\n> \n\nThe parameter \"hand\" has the value \"wave\". The request body can be in multiple\nformats. These formats are defined by the MIME type of the request. The MIME \nType can be set using the ``Content-Type`` HTTP header. The most commonly used \nMIME types are:\n\n* `multipart/form-data`\n* `application/x-www-form-urlencoded`\n* `application/json`\n\nThis endpoint echoes the HTTP headers, request parameters, the contents of\nthe request body and the complete URI requested." + }, + "response": [ + { + "id": "db02f994-5ac4-41e1-835a-f49a14acbb6e", + "name": "POST json with raw", + "originalRequest": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"json\": \"Test-Test\"\n}" + }, + "url": { + "raw": "https://postman-echo.com/post", + "protocol": "https", + "host": [ + "postman-echo", + "com" + ], + "path": [ + "post" + ] + } + }, + "status": "OK", + "code": 200, + "_postman_previewlanguage": "json", + "header": [ + { + "key": "Access-Control-Allow-Credentials", + "value": "", + "name": "Access-Control-Allow-Credentials", + "description": "Indicates whether or not the response to the request can be exposed when the credentials flag is true. When used as part of a response to a preflight request, this indicates whether or not the actual request can be made using credentials." + }, + { + "key": "Access-Control-Allow-Headers", + "value": "", + "name": "Access-Control-Allow-Headers", + "description": "Used in response to a preflight request to indicate which HTTP headers can be used when making the actual request." + }, + { + "key": "Access-Control-Allow-Methods", + "value": "", + "name": "Access-Control-Allow-Methods", + "description": "Specifies the method or methods allowed when accessing the resource. This is used in response to a preflight request." + }, + { + "key": "Access-Control-Allow-Origin", + "value": "", + "name": "Access-Control-Allow-Origin", + "description": "Specifies a URI that may access the resource. For requests without credentials, the server may specify '*' as a wildcard, thereby allowing any origin to access the resource." + }, + { + "key": "Access-Control-Expose-Headers", + "value": "", + "name": "Access-Control-Expose-Headers", + "description": "Lets a server whitelist headers that browsers are allowed to access." + }, + { + "key": "Connection", + "value": "keep-alive", + "name": "Connection", + "description": "Options that are desired for the connection" + }, + { + "key": "Content-Encoding", + "value": "gzip", + "name": "Content-Encoding", + "description": "The type of encoding used on the data." + }, + { + "key": "Content-Length", + "value": "385", + "name": "Content-Length", + "description": "The length of the response body in octets (8-bit bytes)" + }, + { + "key": "Content-Type", + "value": "application/json; charset=utf-8", + "name": "Content-Type", + "description": "The mime type of this content" + }, + { + "key": "Date", + "value": "Wed, 07 Feb 2018 10:06:15 GMT", + "name": "Date", + "description": "The date and time that the message was sent" + }, + { + "key": "ETag", + "value": "W/\"215-u7EU1nFtauIn0/aVifjuXA\"", + "name": "ETag", + "description": "An identifier for a specific version of a resource, often a message digest" + }, + { + "key": "Server", + "value": "nginx", + "name": "Server", + "description": "A name for the server" + }, + { + "key": "Vary", + "value": "X-HTTP-Method-Override, Accept-Encoding", + "name": "Vary", + "description": "Tells downstream proxies how to match future request headers to decide whether the cached response can be used rather than requesting a fresh one from the origin server." + }, + { + "key": "set-cookie", + "value": "sails.sid=s%3AxRBxgrc9M-jKK_l1mX3y3rM_ry8wYLz4.Of4qpOzd9hi6uO0sAQIj%2Bxs2VeppWxYjJa4OpIW3PKg; Path=/; HttpOnly", + "name": "set-cookie", + "description": "an HTTP cookie" + } + ], + "cookie": [ + { + "expires": "Tue Jan 19 2038 08:44:07 GMT+0530 (IST)", + "httpOnly": true, + "domain": "postman-echo.com", + "path": "/", + "secure": false, + "value": "s%3AxRBxgrc9M-jKK_l1mX3y3rM_ry8wYLz4.Of4qpOzd9hi6uO0sAQIj%2Bxs2VeppWxYjJa4OpIW3PKg", + "key": "sails.sid" + } + ], + "body": "{\"args\":{},\"data\":\"{\\n \\\"json\\\": \\\"Test-Test\\\"\\n}\",\"files\":{},\"form\":{},\"headers\":{\"host\":\"postman-echo.com\",\"content-length\":\"25\",\"accept\":\"*/*\",\"accept-encoding\":\"gzip, deflate\",\"cache-control\":\"no-cache\",\"content-type\":\"text/plain\",\"cookie\":\"sails.sid=s%3AkOgtF1XmXtVFx-Eg3S7-37BKKaMqMDPe.hnwldNwyvsaASUiRR0Y0vcowadkMXO4HMegTeVIPgqo\",\"postman-token\":\"2ced782f-a141-428e-8af6-04ce954a77d5\",\"user-agent\":\"PostmanRuntime/7.1.1\",\"x-forwarded-port\":\"443\",\"x-forwarded-proto\":\"https\"},\"json\":null,\"url\":\"https://postman-echo.com/post\"}" + } + ] + }, + { + "name": "POST javascript with raw", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "var responseJSON;", + "", + "try { ", + " responseJSON = JSON.parse(responseBody); ", + " tests['response is valid JSON'] = true;", + "}", + "catch (e) { ", + " responseJSON = {}; ", + " tests['response is valid JSON'] = false;", + "}", + "", + "", + "tests['response has post data'] = _.has(responseJSON, 'data');", + "tests['response matches the data posted'] = (responseJSON.data && responseJSON.data.length === 256);", + "", + "tests[\"content-type equals text/plain\"] = responseJSON && responseJSON.headers && (responseJSON.headers[\"content-type\"] === 'text/plain');" + ] + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/javascript" + } + ], + "body": { + "mode": "raw", + "raw": "var val = 6;\nconsole.log(val);" + }, + "url": { + "raw": "https://postman-echo.com/post", + "protocol": "https", + "host": [ + "postman-echo", + "com" + ], + "path": [ + "post" + ] + }, + "description": "The HTTP `POST` request method is meant to transfer data to a server \n(and elicit a response). What data is returned depends on the implementation\nof the server.\n\nA `POST` request can pass parameters to the server using \"Query String \nParameters\", as well as the Request Body. For example, in the following request,\n\n> POST /hi/there?hand=wave\n>\n> \n\nThe parameter \"hand\" has the value \"wave\". The request body can be in multiple\nformats. These formats are defined by the MIME type of the request. The MIME \nType can be set using the ``Content-Type`` HTTP header. The most commonly used \nMIME types are:\n\n* `multipart/form-data`\n* `application/x-www-form-urlencoded`\n* `application/json`\n\nThis endpoint echoes the HTTP headers, request parameters, the contents of\nthe request body and the complete URI requested." + }, + "response": [] + }, + { + "name": "POST text/xml with raw", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "var responseJSON;", + "", + "try { ", + " responseJSON = JSON.parse(responseBody); ", + " tests['response is valid JSON'] = true;", + "}", + "catch (e) { ", + " responseJSON = {}; ", + " tests['response is valid JSON'] = false;", + "}", + "", + "", + "tests['response has post data'] = _.has(responseJSON, 'data');", + "tests['response matches the data posted'] = (responseJSON.data && responseJSON.data.length === 256);", + "", + "tests[\"content-type equals text/plain\"] = responseJSON && responseJSON.headers && (responseJSON.headers[\"content-type\"] === 'text/plain');" + ] + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "text/xml" + } + ], + "body": { + "mode": "raw", + "raw": "\n Test Test\n" + }, + "url": { + "raw": "https://postman-echo.com/post", + "protocol": "https", + "host": [ + "postman-echo", + "com" + ], + "path": [ + "post" + ] + }, + "description": "The HTTP `POST` request method is meant to transfer data to a server \n(and elicit a response). What data is returned depends on the implementation\nof the server.\n\nA `POST` request can pass parameters to the server using \"Query String \nParameters\", as well as the Request Body. For example, in the following request,\n\n> POST /hi/there?hand=wave\n>\n> \n\nThe parameter \"hand\" has the value \"wave\". The request body can be in multiple\nformats. These formats are defined by the MIME type of the request. The MIME \nType can be set using the ``Content-Type`` HTTP header. The most commonly used \nMIME types are:\n\n* `multipart/form-data`\n* `application/x-www-form-urlencoded`\n* `application/json`\n\nThis endpoint echoes the HTTP headers, request parameters, the contents of\nthe request body and the complete URI requested." + }, + "response": [] + }, + { + "name": "POST text/html with raw", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "var responseJSON;", + "", + "try { ", + " responseJSON = JSON.parse(responseBody); ", + " tests['response is valid JSON'] = true;", + "}", + "catch (e) { ", + " responseJSON = {}; ", + " tests['response is valid JSON'] = false;", + "}", + "", + "", + "tests['response has post data'] = _.has(responseJSON, 'data');", + "tests['response matches the data posted'] = (responseJSON.data && responseJSON.data.length === 256);", + "", + "tests[\"content-type equals text/plain\"] = responseJSON && responseJSON.headers && (responseJSON.headers[\"content-type\"] === 'text/plain');" + ] + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "text/html" + } + ], + "body": { + "mode": "raw", + "raw": "\n Test Test\n" + }, + "url": { + "raw": "https://postman-echo.com/post", + "protocol": "https", + "host": [ + "postman-echo", + "com" + ], + "path": [ + "post" + ] + }, + "description": "The HTTP `POST` request method is meant to transfer data to a server \n(and elicit a response). What data is returned depends on the implementation\nof the server.\n\nA `POST` request can pass parameters to the server using \"Query String \nParameters\", as well as the Request Body. For example, in the following request,\n\n> POST /hi/there?hand=wave\n>\n> \n\nThe parameter \"hand\" has the value \"wave\". The request body can be in multiple\nformats. These formats are defined by the MIME type of the request. The MIME \nType can be set using the ``Content-Type`` HTTP header. The most commonly used \nMIME types are:\n\n* `multipart/form-data`\n* `application/x-www-form-urlencoded`\n* `application/json`\n\nThis endpoint echoes the HTTP headers, request parameters, the contents of\nthe request body and the complete URI requested." + }, + "response": [] + }, + { + "name": "Resolve URL", + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/x-www-form-urlencoded" + } + ], + "body": { + "mode": "raw", + "raw": "Duis posuere augue vel cursus pharetra. In luctus a ex nec pretium. Praesent neque quam, tincidunt nec leo eget, rutrum vehicula magna.\nMaecenas consequat elementum elit, id semper sem tristique et. Integer pulvinar enim quis consectetur interdum volutpat." + }, + "url": { + "raw": "https://postman-echo.com/:action", + "protocol": "https", + "host": [ + "postman-echo", + "com" + ], + "path": [ + ":action" + ], + "variable": [ + { + "key": "action", + "value": "post" + } + ] + }, + "description": null + }, + "response": [] + }, + { + "name": "PUT Request", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "var responseJSON;", + "", + "try { ", + " responseJSON = JSON.parse(responseBody); ", + " tests['response is valid JSON'] = true;", + "}", + "catch (e) { ", + " responseJSON = {}; ", + " tests['response is valid JSON'] = false;", + "}", + "", + "", + "tests['response has PUT data'] = _.has(responseJSON, 'data');", + "tests['response matches the data sent in request'] = (responseJSON.data && responseJSON.data.length === 256);" + ] + } + } + ], + "request": { + "method": "PUT", + "header": [ + { + "key": "Content-Type", + "value": "text/plain" + } + ], + "body": { + "mode": "raw", + "raw": "Etiam mi lacus, cursus vitae felis et, blandit pellentesque neque. Vestibulum eget nisi a tortor commodo dignissim.\nQuisque ipsum ligula, faucibus a felis a, commodo elementum nisl. Mauris vulputate sapien et tincidunt viverra. Donec vitae velit nec metus." + }, + "url": { + "raw": "https://postman-echo.com/put", + "protocol": "https", + "host": [ + "postman-echo", + "com" + ], + "path": [ + "put" + ] + }, + "description": "The HTTP `PUT` request method is similar to HTTP `POST`. It too is meant to \ntransfer data to a server (and elicit a response). What data is returned depends on the implementation\nof the server.\n\nA `PUT` request can pass parameters to the server using \"Query String \nParameters\", as well as the Request Body. For example, in the following \nraw HTTP request,\n\n> PUT /hi/there?hand=wave\n>\n> \n\n\n" + }, + "response": [] + }, + { + "name": "PATCH Request", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "var responseJSON;", + "", + "try { ", + " responseJSON = JSON.parse(responseBody); ", + " tests['response is valid JSON'] = true;", + "}", + "catch (e) { ", + " responseJSON = {}; ", + " tests['response is valid JSON'] = false;", + "}", + "", + "", + "tests['response has PUT data'] = _.has(responseJSON, 'data');", + "tests['response matches the data sent in request'] = (responseJSON.data && responseJSON.data.length === 256);" + ] + } + } + ], + "request": { + "method": "PATCH", + "header": [ + { + "key": "Content-Type", + "value": "text/plain" + } + ], + "body": { + "mode": "raw", + "raw": "Curabitur auctor, elit nec pulvinar porttitor, ex augue condimentum enim, eget suscipit urna felis quis neque.\nSuspendisse sit amet luctus massa, nec venenatis mi. Suspendisse tincidunt massa at nibh efficitur fringilla. Nam quis congue mi. Etiam volutpat." + }, + "url": { + "raw": "https://postman-echo.com/patch", + "protocol": "https", + "host": [ + "postman-echo", + "com" + ], + "path": [ + "patch" + ] + }, + "description": "The HTTP `PATCH` method is used to update resources on a server. The exact\nuse of `PATCH` requests depends on the server in question. There are a number\nof server implementations which handle `PATCH` differently. Technically, \n`PATCH` supports both Query String parameters and a Request Body.\n\nThis endpoint accepts an HTTP `PATCH` request and provides debug information\nsuch as the HTTP headers, Query String arguments, and the Request Body." + }, + "response": [] + }, + { + "name": "DELETE Request", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "var responseJSON;", + "", + "try { ", + " responseJSON = JSON.parse(responseBody); ", + " tests['response is valid JSON'] = true;", + "}", + "catch (e) { ", + " responseJSON = {}; ", + " tests['response is valid JSON'] = false;", + "}", + "", + "", + "tests['response has PUT data'] = _.has(responseJSON, 'data');", + "tests['response matches the data sent in request'] = (responseJSON.data && responseJSON.data.length === 256);" + ] + } + } + ], + "request": { + "method": "DELETE", + "header": [ + { + "key": "Content-Type", + "value": "application/x-www-form-urlencoded" + }, + { + "key": "Content-Length", + "value": "1000", + "disabled": true + } + ], + "body": { + "mode": "urlencoded", + "urlencoded": [ + { + "key": "dsfs", + "value": "sfdds", + "description": "", + "type": "text" + }, + { + "key": "sfdsdf", + "value": "sdf", + "description": "", + "type": "text" + } + ] + }, + "url": { + "raw": "https://postman-echo.com/delete", + "protocol": "https", + "host": [ + "postman-echo", + "com" + ], + "path": [ + "delete" + ] + }, + "description": "The HTTP `DELETE` method is used to delete resources on a server. The exact\nuse of `DELETE` requests depends on the server implementation. In general, \n`DELETE` requests support both, Query String parameters as well as a Request \nBody.\n\nThis endpoint accepts an HTTP `DELETE` request and provides debug information\nsuch as the HTTP headers, Query String arguments, and the Request Body." + }, + "response": [] + }, + { + "name": "OPTIONS to postman echo", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "var responseJSON;", + "", + "try { ", + " responseJSON = JSON.parse(responseBody); ", + " tests['response is valid JSON'] = true;", + "}", + "catch (e) { ", + " responseJSON = {}; ", + " tests['response is valid JSON'] = false;", + "}", + "", + "", + "tests['response has post data'] = _.has(responseJSON, 'data');", + "tests['response matches the data posted'] = (responseJSON.data && responseJSON.data.length === 256);", + "", + "tests[\"content-type equals text/plain\"] = responseJSON && responseJSON.headers && (responseJSON.headers[\"content-type\"] === 'text/plain');" + ] + } + } + ], + "request": { + "method": "OPTIONS", + "header": [ + { + "key": "Content-Type", + "value": "application/x-www-form-urlencoded" + } + ], + "body": {}, + "url": { + "raw": "https://postman-echo.com/post", + "protocol": "https", + "host": [ + "postman-echo", + "com" + ], + "path": [ + "post" + ] + }, + "description": "The HTTP `POST` request method is meant to transfer data to a server \n(and elicit a response). What data is returned depends on the implementation\nof the server.\n\nA `POST` request can pass parameters to the server using \"Query String \nParameters\", as well as the Request Body. For example, in the following request,\n\n> POST /hi/there?hand=wave\n>\n> \n\nThe parameter \"hand\" has the value \"wave\". The request body can be in multiple\nformats. These formats are defined by the MIME type of the request. The MIME \nType can be set using the ``Content-Type`` HTTP header. The most commonly used \nMIME types are:\n\n* `multipart/form-data`\n* `application/x-www-form-urlencoded`\n* `application/json`\n\nThis endpoint echoes the HTTP headers, request parameters, the contents of\nthe request body and the complete URI requested." + }, + "response": [] + } + ] +} \ No newline at end of file diff --git a/codegens/java-native/test/unit/validation.test.js b/codegens/java-native/test/unit/validation.test.js new file mode 100644 index 000000000..3291640c3 --- /dev/null +++ b/codegens/java-native/test/unit/validation.test.js @@ -0,0 +1,30 @@ +var expect = require('chai').expect, + path = require('path'), + + package = require(path.resolve('.', 'package.json')); + + +describe('package.json', function () { + it('should have com_postman_plugin object with valid properties', function () { + expect(package).to.have.property('com_postman_plugin'); + + expect(package.com_postman_plugin.type).to.equal('code_generator'); + expect(package.com_postman_plugin.lang).to.be.a('string'); + expect(package.com_postman_plugin.variant).to.be.a('string'); + expect(package.com_postman_plugin.syntax_mode).to.be.equal('java'); + }); + it('should have main property with relative path to object with convert property', function () { + var languageModule; + + expect(package.main).to.be.a('string'); + + try { + languageModule = require(path.resolve('.', package.main)); + } + catch (error) { + console.error(error); + } + expect(languageModule).to.be.a('object'); + expect(languageModule.convert).to.be.a('function'); + }); +});