🎩 You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP
Sign In

raml2code

Package Overview
Dependencies
Maintainers
1
Versions
44
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

raml2code - npm Package Compare versions

Comparing version
0.0.34
to
0.0.35
+7
.travis.yml
language: node_js
node_js:
- "0.11"
- "0.10"
before_script:
- npm install -g gulp
script: gulp
var Deref, resolveInnerClass, resolveType, resolveTypeByRef, util, utilText, _;
Deref = require('deref');
_ = require('lodash');
utilText = require('../util/text');
util = {};
util.mapProperties = function(expandedSchema, refMap, mapping) {
var data, key, keyRef, propParsed, property;
data = {};
data.classMembers = [];
data.innerClasses = [];
if (expandedSchema.properties && expandedSchema.properties.$ref) {
keyRef = expandedSchema.properties.$ref;
expandedSchema.properties = Deref.util.findByRef(keyRef, refMap);
}
for (key in expandedSchema.properties) {
property = expandedSchema.properties[key];
if (typeof property !== 'string') {
if (expandedSchema.required && _.contains(expandedSchema.required, key)) {
property.required = true;
}
propParsed = util.mapProperty(property, key, '', mapping, refMap);
data.classMembers.push(propParsed.property);
if (propParsed.innerClass) {
data.innerClasses.push(propParsed.innerClass);
}
}
}
return data;
};
util.mapProperty = function(property, name, annotation, mapping, refMap) {
var auxType, data, innerClass, keyRef, keyRefData, primitiveType, _ref;
data = {};
data.property = {};
data.property.name = name;
if (property.required) {
data.property.notNull = true;
}
data.property.size = [];
if (property.minLength) {
data.property.size.push({
"name": "min",
"value": property.minLength
});
}
if (property.maxLength) {
data.property.size.push({
"name": "max",
"value": property.maxLength
});
}
data.property.comment = property.description;
if (property.items && property.items["$ref"]) {
keyRef = property.items["$ref"];
keyRefData = resolveTypeByRef(keyRef, refMap, name, true);
} else if (property["$ref"]) {
keyRef = property["$ref"];
keyRefData = resolveTypeByRef(keyRef, refMap, name);
data.property.type = keyRefData.type;
if (keyRefData.innnerSchema.type) {
property.type = keyRefData.innnerSchema.type;
} else {
property.properties = keyRefData.innnerSchema;
data.innerClass = resolveInnerClass(keyRefData.type, property, refMap, mapping);
property.type = resolveType(data.innerClass, name);
}
}
data.property.comment = property.description;
switch (property.type) {
case 'array':
auxType = "List";
if (keyRefData && keyRefData.innnerSchema.items !== void 0) {
primitiveType = mapping[keyRefData.innnerSchema.items.type];
if (keyRefData.innnerSchema.items.title) {
auxType += "<" + keyRefData.type + ">";
} else if (primitiveType) {
auxType += "<" + primitiveType + ">";
}
}
data.property.type = auxType;
break;
case 'object':
if (property.properties) {
if (keyRefData && keyRefData.type) {
data.property.type = keyRefData.type;
} else {
data.property.type = resolveType(property, name);
innerClass = resolveInnerClass(data.property.type, property, refMap, mapping);
data.innerClass = innerClass;
}
} else if (keyRefData && keyRefData.innnerSchema && keyRefData.innnerSchema.properties) {
data.property.type = keyRefData.type;
property.properties = keyRefData.innnerSchema;
data.innerClass = resolveInnerClass(keyRefData.type, property, refMap, mapping);
} else {
data.property.type = 'Map';
}
break;
default:
data.property.type = (_ref = mapping[property.type]) != null ? _ref : property.type;
}
if (data.property.type === "BigDecimal") {
data.property.decimalMax = property.maximum;
data.property.decimalMin = property.minimum;
} else if (data.property.type === "Long") {
data.property.max = property.maximum;
data.property.min = property.minimum;
}
data.property.kind = annotation + ("(\"" + data.property.name + "\")");
return data;
};
resolveTypeByRef = function(keyRef, refMap, propertyName, isArray) {
var data, innerSchema;
if (isArray == null) {
isArray = false;
}
data = {};
data.type = "";
innerSchema = Deref.util.findByRef(keyRef, refMap);
if (innerSchema) {
if (isArray) {
data.innnerSchema = {};
data.innnerSchema.items = innerSchema;
} else {
data.innnerSchema = innerSchema;
}
data.type = resolveType(innerSchema, propertyName);
} else if (keyRef) {
console.error("$ref not found: " + keyRef + " RefMap.keys -> [" + (Object.keys(refMap)) + "]");
console.error(JSON.stringify(refMap));
}
return data;
};
resolveType = function(schema, propertyName) {
var type;
type = "";
if (schema) {
if (schema.title) {
type = utilText.capitalize(schema.title);
} else {
type = utilText.capitalize(propertyName);
}
}
return type;
};
resolveInnerClass = function(name, property, refMap, mapping) {
var aux, data;
data = null;
if (property && !property.properties.title) {
data = {};
data.className = name;
data.classDescription = property.description;
aux = util.mapProperties(property, refMap, mapping);
data.classMembers = aux.classMembers;
}
return data;
};
module.exports = util;
var Deref, util, utilText, _;
utilText = require('../util/text');
_ = require('lodash');
Deref = require('deref');
util = {};
util.mapRequestResponse = function(scheme, schemas, mapping) {
var dataRef, deref, normSchema, primitiveType, type;
type = "";
switch (scheme.type) {
case "array":
if (scheme.items) {
type = "List<Maps>";
if (scheme.items.$ref) {
deref = Deref();
normSchema = deref(scheme, schemas);
dataRef = deref.util.findByRef(normSchema.items.$ref, deref.refs);
if (dataRef && dataRef.title) {
type = "List<" + (utilText.capitalize(dataRef.title)) + ">";
} else {
type = "List";
}
} else if (scheme.items.title) {
type = "List<" + (util.capitalize(scheme.title)) + ">";
} else if (scheme.items.type) {
primitiveType = mapping[scheme.items.type];
if (primitiveType) {
type = "List<" + primitiveType + ">";
}
}
} else {
type = "List";
}
break;
case "object":
if (scheme.properties) {
type = utilText.capitalize(scheme.title);
} else {
type = "Map";
}
break;
default:
console.warn("-------WARNING the following scheme doesn't have type: -------");
console.warn("" + (JSON.stringify(scheme)) + " ");
}
return type;
};
module.exports = util.mapRequestResponse;
var getBestValidResponse, getQueryParams, getUriParameter, mapRequestResponse, parseForm, util, utilMapProperty, utilSchemas, utilText, _;
utilMapProperty = require('../util/mapProperty');
utilSchemas = require('../util/schemas');
mapRequestResponse = require('../util/mapRequestResponse');
utilText = require('../util/text');
_ = require('lodash');
util = {};
util.parseResource = function(resource, options, schemas, customAdapter, parentUri, parentUriArgs) {
var innerResource, m, methodDef, parsed, request, respond, responseType, type, uriArgs, _i, _j, _len, _len1, _ref, _ref1, _ref2, _ref3;
if (customAdapter == null) {
customAdapter = null;
}
if (parentUri == null) {
parentUri = "";
}
if (parentUriArgs == null) {
parentUriArgs = [];
}
parsed = [];
_ref = resource.methods;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
m = _ref[_i];
methodDef = {};
methodDef.uri = parentUri + resource.relativeUri;
methodDef.annotation = m.method.toUpperCase();
methodDef.name = m.method + resource.displayName;
methodDef.displayName = resource.displayName;
uriArgs = getUriParameter(resource, options.annotations.path, options.mapping);
methodDef.args = parentUriArgs.concat(uriArgs);
methodDef.args = methodDef.args.concat(getQueryParams(m.queryParameters, options.annotations.query, options.mapping));
methodDef.args = methodDef.args.concat(parseForm(m.body, options.annotations, options.mapping));
request = utilSchemas.parseBodyJson(m.body, "" + methodDef.uri + " body");
respond = utilSchemas.parseBodyJson(getBestValidResponse(m.responses).body, "" + methodDef.uri + " response");
if (request.title) {
methodDef.args = (_ref1 = methodDef.args) != null ? _ref1 : [];
type = mapRequestResponse(request, schemas, options.mapping);
methodDef.args.push({
'kind': options.annotations.body,
'type': type,
'name': request.title.toLowerCase()
});
}
methodDef.request = (_ref2 = request.title) != null ? _ref2 : null;
responseType = mapRequestResponse(respond, schemas, options.mapping);
methodDef.respondComment = respond.title;
if (responseType) {
methodDef.respond = responseType;
} else {
methodDef.respond = "Response";
}
methodDef.formData = _.find(methodDef.args, function(arg) {
return arg.type === "InputStream" || arg.type === "TypedFile";
});
methodDef.formEncoded = _.find(methodDef.args, function(arg) {
return arg.kind.indexOf("@Field") > -1 || arg.kind.indexOf("@FormDataParam") > -1;
});
if (customAdapter && typeof customAdapter === 'function') {
customAdapter(m, methodDef);
}
parsed.push(methodDef);
}
if (resource.resources) {
_ref3 = resource.resources;
for (_j = 0, _len1 = _ref3.length; _j < _len1; _j++) {
innerResource = _ref3[_j];
parsed = parsed.concat(util.parseResource(innerResource, options, schemas, customAdapter, methodDef.uri, uriArgs));
}
}
return parsed;
};
getUriParameter = function(resource, annotation, mapping) {
var key, p, uriParameters;
uriParameters = [];
for (key in resource.uriParameters) {
p = resource.uriParameters[key];
uriParameters.push(utilMapProperty.mapProperty(p, key, annotation, mapping).property);
}
return uriParameters;
};
getQueryParams = function(queryParams, annotation, mapping) {
var key, p, params;
params = [];
for (key in queryParams) {
p = queryParams[key];
params.push(utilMapProperty.mapProperty(p, key, annotation, mapping).property);
}
return params;
};
parseForm = function(body, annotations, mapping) {
var annotation, args, data, form, key, p, parsedProperty;
args = [];
form = body ? body["multipart/form-data"] || body["application/x-www-form-urlencoded"] : void 0;
if (form) {
if (body["multipart/form-data"] !== void 0) {
annotation = annotations.multiPart;
} else {
annotation = annotations.form;
}
data = form.formParameters || form.formParameters;
for (key in data) {
p = data[key];
parsedProperty = utilMapProperty.mapProperty(p, key, annotation, mapping).property;
args.push(parsedProperty);
if (parsedProperty.type === "InputStream") {
args.push({
name: parsedProperty.name + "Data",
type: "FormDataContentDisposition",
kind: annotation + ("(\"" + parsedProperty.name + "\")")
});
}
}
}
return args;
};
getBestValidResponse = function(responses) {
var response, _ref, _ref1, _ref2, _ref3;
return response = (_ref = responses["304"]) != null ? _ref : response = (_ref1 = responses["204"]) != null ? _ref1 : response = (_ref2 = responses["201"]) != null ? _ref2 : response = (_ref3 = responses["200"]) != null ? _ref3 : response;
};
module.exports = util.parseResource;
var util;
util = {};
util.parseBodyJson = function(body, meta) {
var schema;
if (meta == null) {
meta = '';
}
schema = {};
if (body && body['application/json']) {
schema = util.parseSchema(body['application/json'].schema, meta);
}
return schema;
};
util.parseSchema = function(raw, meta) {
var e, schema;
if (meta == null) {
meta = '';
}
schema = {};
if (raw) {
try {
schema = JSON.parse(raw);
} catch (_error) {
e = _error;
console.log("-----JSON ERROR on " + meta + "---------");
throw e;
}
}
return schema;
};
util.loadSchemas = function(data) {
var row, schema, schemaName, schemas, _i, _len, _ref;
schemas = [];
_ref = data.schemas;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
row = _ref[_i];
for (schemaName in row) {
schema = util.parseSchema(row[schemaName], "Trouble parsing schema: " + schemaName);
schemas.push(schema);
}
}
return schemas;
};
module.exports = util;
var text;
text = {};
text.capitalize = function(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
};
text.sanitize = function(str) {
var aux, res;
aux = str.split(".");
res = '';
aux.forEach(function(it) {
return res += text.capitalize(it);
});
return res;
};
module.exports = text;
{
"id": "widget",
"type": "object",
"title": "Widget",
"description": "A widget is used to generated partials",
"required": ["id", "name", "groupId", "artifactId", "revision", "description"],
"properties": {
"name": {
"description": "The friendly name of the widget ",
"type": "string"
},
"composite":{
"type": "object",
"$ref": "widget#/definitions/innerProperties"
},
"etiquetas":{
"$ref": "widget#/definitions/innerProperties/tags"
}
},
"definitions": {
"innerProperties": {
"xid": {
"description": "The unique identifier of the widget ",
"type": "string"
},
"name": {
"description": "The friendly name of the widget ",
"type": "string"
},
"tags": {
"description": "Common set of keywords to categorize widgets",
"type": "array",
"items": {
"type": "string",
"format": "[a-z]{1,20}"
},
"uniqueItems": true
},
"groupId": {
"description": "The version of the Widget ",
"type": "string"
},
"artifactId": {
"description": "The version of the Widget ",
"type": "string"
},
"revision": {
"description": "The version of the Widget ",
"type": "string"
},
"description": {
"description": "The description of the Widget ",
"type": "string"
}
},
"something": {
"xid": {
"description": "The unique identifier of the widget ",
"type": "string"
},
"colour": {
"description": "The friendly name of the widget ",
"type": "string"
},
"ipsum": {
"description": "The version of the Widget ",
"type": "string"
},
"lorem": {
"description": "The description of the Widget ",
"type": "string"
}
}
}
}
{
"id": "widgetInlineProperty",
"type": "object",
"title": "WidgetInlineProperty",
"description": "A widget is used to generated partials",
"required": ["id", "name", "groupId", "artifactId", "revision", "description"],
"properties": {
"name": {
"description": "The friendly name of the widget ",
"type": "string"
},
"composite":{
"type": "object",
"description": "Inner properties",
"$ref": "widget#/definitions/innerProperties"
},
"zid":{
"$ref": "widget#/definitions/something"
},
"otherColor":{
"$ref": "widget#/definitions/something/colour"
}
}
}
+22
-5
var gulp = require('gulp');
var del = require('del');
var runSequence = require('run-sequence');
var gutil = require('gulp-util');

@@ -6,6 +8,13 @@ var mocha = require('gulp-mocha');

gulp.task('coffee', ['copy-templates'], function() {
gulp.src('./src/**/*.coffee')
gulp.task('clean', function (cb) {
del([
'lib/**'
], cb);
});
gulp.task('coffee', function() {
return gulp.src('./src/**/*.coffee')
.pipe(coffee({bare: true}).on('error', gutil.log))
.pipe(gulp.dest('./lib/'))
.pipe(gulp.dest('./lib/'));
});

@@ -19,3 +28,3 @@

gulp.task('test', ['coffee', 'copy-templates'], function(cb){
gulp.task('test', function(cb){
gulp.src(['./test/**/*spec.js'])

@@ -31,2 +40,10 @@ .pipe(mocha(

gulp.task('default', [ 'test']);
gulp.task('build', function(callback) {
runSequence('clean',
['copy-templates', 'coffee'],
'test',
callback);
});
gulp.task('default', ['build']);
+33
-22

@@ -1,2 +0,2 @@

var commonHelpers, dirname, fs, generator, path, template, util, _;
var commonHelpers, customAdapter, dirname, fs, generator, parseResource, path, template, utilSchemas, _;

@@ -7,6 +7,8 @@ fs = require('fs');

util = require('./util.js');
utilSchemas = require('../util/schemas');
commonHelpers = require("../helpers/common.js").helpers();
parseResource = require('../util/parseResource');
commonHelpers = require("../helpers/common").helpers();
path = require('path');

@@ -24,28 +26,37 @@

customAdapter = function(method, methodParsed) {
if (methodParsed.formData) {
return methodParsed.consumes = "MediaType.MULTIPART_FORM_DATA";
}
};
generator.parser = function(data) {
var annotations, first, k, mapping, methodParse, model, parsed, resource, resourceGroup, schemas, v, _i, _len, _ref;
var first, k, methodParse, model, options, parsed, resource, resourceGroup, schemas, v, _i, _len, _ref;
parsed = [];
schemas = util.loadSchemas(data);
schemas = utilSchemas.loadSchemas(data);
options = {
annotations: {
path: "@PathParam",
query: "@QueryParam",
body: "",
multiPart: "@FormDataParam",
form: "@FormDataParam"
},
mapping: {
'string': "String",
'boolean': "Boolean",
'number': "BigDecimal",
'integer': "Long",
'array': "List",
'object': "Map",
'file': "InputStream"
}
};
methodParse = [];
annotations = {
path: "@PathParam",
query: "@QueryParam",
body: "",
multiPart: "@FormDataParam",
form: "@FormDataParam"
};
mapping = {
'string': "String",
'boolean': "Boolean",
'number': "BigDecimal",
'integer': "Long",
'array': "List",
'object': "Map",
'file': "InputStream"
};
_ref = data.resources;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
resource = _ref[_i];
util.parseResource(resource, methodParse, annotations, mapping, schemas);
methodParse.push(parseResource(resource, options, schemas, customAdapter));
}
methodParse = _.flatten(methodParse);
resourceGroup = _.groupBy(methodParse, function(method) {

@@ -52,0 +63,0 @@ return method.displayName;

@@ -1,11 +0,15 @@

var cmPartial, commonHelpers, deref, dirname, fs, generator, path, template, util;
var cmPartial, commonHelpers, deref, dirname, fs, generator, path, template, utilMapProperty, utilSchemas, utilText;
fs = require('fs');
commonHelpers = require("../helpers/common.js").helpers();
commonHelpers = require("../helpers/common").helpers();
util = require('./util.js');
path = require('path');
utilText = require('../util/text');
utilSchemas = require('../util/schemas');
utilMapProperty = require('../util/mapProperty');
generator = {};

@@ -44,3 +48,3 @@

parsed = [];
schemas = util.loadSchemas(datos);
schemas = utilSchemas.loadSchemas(datos);
if (datos.extra) {

@@ -56,5 +60,5 @@ datos.extra["package"] = "" + datos.extra["package"] + "." + datos.version;

model = {};
model.className = util.capitalize(normSchema.title);
model.className = utilText.capitalize(normSchema.title);
model.classDescription = (_ref = normSchema.description) != null ? _ref : "";
someData = util.mapProperties(normSchema, deref.refs, mapping);
someData = utilMapProperty.mapProperties(normSchema, deref.refs, mapping);
model.classMembers = someData.classMembers;

@@ -61,0 +65,0 @@ model.innerClasses = someData.innerClasses;

@@ -1,11 +0,17 @@

var commonHelpers, dirname, fs, generator, path, template, util;
var commonHelpers, customAdapter, dirname, fs, generator, parseResource, path, template, utilSchemas, _;
fs = require('fs');
commonHelpers = require("../helpers/common.js").helpers();
commonHelpers = require("../helpers/common").helpers();
util = require('./util.js');
utilSchemas = require('../util/schemas');
parseResource = require('../util/parseResource');
console.log(parseResource);
path = require('path');
_ = require('lodash');
generator = {};

@@ -21,28 +27,48 @@

customAdapter = function(method, methodParsed) {
var mediaType;
if (methodParsed.formData) {
methodParsed.additionalAnnotation = "Multipart";
}
if (methodParsed.formEncoded) {
methodParsed.additionalAnnotation = "FormUrlEncoded";
}
mediaType = "application/json";
if (method.body && Object.keys(method.body)[0]) {
mediaType = Object.keys(method.body)[0];
}
if (methodParsed.annotation === "DELETE") {
return methodParsed.additionalAnnotation = "Headers({\"Content-type: " + mediaType + "\"})";
}
};
generator.parser = function(data) {
var annotations, mapping, methodParse, model, parsed, resource, schemas, _i, _len, _ref;
var methodParse, model, options, parsed, resource, schemas, _i, _len, _ref;
parsed = [];
schemas = util.loadSchemas(data);
schemas = utilSchemas.loadSchemas(data);
options = {
annotations: {
path: "@Path",
query: "@Query",
body: "@Body",
multiPart: "@Part",
form: "@Field"
},
mapping: {
'string': "String",
'boolean': "Boolean",
'number': "BigDecimal",
'integer': "Long",
'array': "List",
'object': "Map",
'file': "TypedFile"
}
};
methodParse = [];
annotations = {
path: "@Path",
query: "@Query",
body: "@Body",
multiPart: "@Part",
form: "@Field"
};
mapping = {
'string': "String",
'boolean': "Boolean",
'number': "BigDecimal",
'integer': "Long",
'array': "List",
'object': "Map",
'file': "TypedFile"
};
_ref = data.resources;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
resource = _ref[_i];
util.parseResource(resource, methodParse, annotations, mapping, schemas);
methodParse.push(parseResource(resource, options, schemas, customAdapter));
}
methodParse = _.flatten(methodParse);
model = {};

@@ -49,0 +75,0 @@ model.methods = methodParse;

@@ -21,3 +21,3 @@ package {{extra.package}};

{{/if}}
Observable{{{respond}}} {{{name}}}({{#each args}}{{#if @index}},{{/if}}
Observable<{{{respond}}}> {{{name}}}({{#each args}}{{#if @index}},{{/if}}
{{{kind}}} {{{type}}} {{name}}{{/each}});

@@ -24,0 +24,0 @@

{
"name": "raml2code",
"version": "0.0.34",
"version": "0.0.35",
"description": "Raml spec to code",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"test": "gulp"
},

@@ -33,8 +33,10 @@ "repository": {

"chai": "^1.10.0",
"gulp": "3.8.10",
"del": "^1.1.1",
"gulp": "^3.8.10",
"gulp-coffee": "2.2.0",
"gulp-jasmine": "^1.0.1",
"gulp-mocha": "2.0.0",
"mocha": "^2.0.1"
"mocha": "^2.0.1",
"run-sequence": "^1.0.2"
}
}
+83
-21
# Raml to code generator
[![Build Status](https://img.shields.io/travis/gextech/raml2code/master.svg?style=flat)](https://travis-ci.org/gextech/raml2code)
* This module generate code from a RAML definition
* It uses Handlebars templates
## It must be defined as Gulp-plugin
```js
var gulp = require('gulp');
var raml2code = require('raml2code');
var genDTO = require("raml2code/lib/generators/groovy/raml2DTO.js");
gulp.task("test", function(){
gulp.src('./test/cats.raml')
.pipe(raml2code({generator: genDTO, extra: {package:'com.gex'}}))
.pipe(gulp.dest('build'));
});
```
## Sample gulpfile
```js
var gulp = require('gulp');
var raml2code = require("raml2code");
var genPojos = require("raml2code/lib/generators/groovy/pojo");
var genJaxRS = require("raml2code/lib/generators/groovy/jaxrsInterface");
var genRetrofitClient = require("raml2code/lib/generators/groovy/retrofitClient");
var raml = require('gulp-raml');
var packagePojo = "gex.catapi.dto";
var packageClient = "gex.catapi.client";
var packageJersey = "gex.catapi.resources";
//this should point to your raml definition
var ramlResource = '../../test/raml/cats.raml'
gulp.task('raml', function() {
gulp.src(ramlResource)
.pipe(raml())
.pipe(raml.reporter('default'))
.pipe(raml.reporter('fail'));
});
gulp.task("genPojos", ['raml'], function(){
gulp.src(ramlResource)
.pipe(raml2code({generator: genPojos, extra: {package: packagePojo}}))
.pipe(gulp.dest('./src/generated/groovy/gex/catapi/dto'));
});
gulp.task("genRetrofitClient" , ['raml'], function(){
gulp.src(ramlResource)
.pipe(raml2code({generator: genRetrofitClient, extra: {package: packageClient, importPojos: packagePojo}}))
.pipe(gulp.dest('./src/generated/java/gex/catapi/client'));
});
gulp.task("genJaxRS" , ['raml'], function(){
gulp.src(ramlResource)
.pipe(raml2code({generator: genJaxRS, extra: {package: packageJersey, importPojos: packagePojo}}))
.pipe(gulp.dest('./src/generated/groovy/gex/catapi/resources'));
});
gulp.task('build', ['raml', 'genPojos', 'genJaxRS', 'genRetrofitClient']);
gulp.task('default', ['build']);
```
## We use the Gradle with the gulp plugin to build or loved Java project
[gradle](https://www.gradle.org/)
[gradle-gulp-plugin](https://github.com/filipblondeel/gradle-gulp-plugin)
## Defining a Generator
## You don't like our generators, DIY

@@ -11,4 +84,5 @@ A generator is a simple object with the following properties:

* Required properties:
* template -> Handlebars template.
* parser(data) -> Function it receives RAML parsed data, returns parsed data.
* template -> Handlebars template (you could use your own templates).
* parser(data) -> Function it receives RAML parsed data, returns model that will be used in the
template engine, each model must have a name, this name is the file that will be generated.
[{ name: "test.test", model: {title:data.title + " finos"}}]

@@ -21,26 +95,14 @@ * Optional properties:

## Generators included and tested
* Groovy POJO
If the json schema has $ref, it would try to use the title to make references, if the title doesn't exits
it would generate a inner classes with the name of the property.
If there are $ref definitions, consider the following http://json-schema.org/latest/json-schema-core.html#anchor30
* JAX-RS Interface
* RETROFIT Client
* Groovy POJO
If the json schema has $ref, it would try to use the title to make references, if the title doesn't exits
it would generate a inner classes with the name of the property.
If there are $ref definitions, consider the following http://json-schema.org/latest/json-schema-core.html#anchor30
* JAX-RS Interface
* RETROFIT Client
## Gulp-plugin
```
var gulp = require('gulp');
var raml2code = require('raml2code');
var genDTO = require("raml2code/lib/generators/groovy/raml2DTO.js");
gulp.task("test", function(){
gulp.src('./test/cats.raml')
.pipe(raml2code({generator: genDTO, extra: {package:'com.gex'}}))
.pipe(gulp.dest('build'));
});
```
var Deref, util, _;
_ = require('lodash');
Deref = require('deref');
util = {};
util.getUriParameter = function(resource, annotation, mapping) {
var key, p, uriParameters;
uriParameters = [];
for (key in resource.uriParameters) {
p = resource.uriParameters[key];
uriParameters.push(util.mapProperty(p, key, annotation, mapping).property);
}
return uriParameters;
};
util.getQueryparams = function(queryParams, annotation, mapping) {
var key, p, params;
params = [];
for (key in queryParams) {
p = queryParams[key];
params.push(util.mapProperty(p, key, annotation, mapping).property);
}
return params;
};
util.parseForm = function(body, annotations, mapping) {
var annotation, args, data, form, key, p, parsedProperty;
args = [];
if (body && (body['multipart/form-data'] || body["application/x-www-form-urlencoded"])) {
form = body["multipart/form-data"] || body["application/x-www-form-urlencoded"];
if (body["multipart/form-data"] !== void 0) {
annotation = annotations.multiPart;
} else {
annotation = annotations.form;
}
data = form.formParameters || form.formParameters;
for (key in data) {
p = data[key];
parsedProperty = util.mapProperty(p, key, annotation, mapping).property;
args.push(parsedProperty);
if (parsedProperty.type === "InputStream") {
args.push({
name: parsedProperty.name + "Data",
type: "FormDataContentDisposition",
kind: annotation + ("(\"" + parsedProperty.name + "\")")
});
}
}
}
return args;
};
util.mapProperties = function(expandedSchema, refMap, mapping) {
var data, key, keyRef, propParsed, property;
data = {};
data.classMembers = [];
data.innerClasses = [];
if (expandedSchema.properties && expandedSchema.properties.$ref) {
keyRef = expandedSchema.properties.$ref;
expandedSchema.properties = Deref.util.findByRef(keyRef, refMap);
}
for (key in expandedSchema.properties) {
property = expandedSchema.properties[key];
if (typeof property !== 'string') {
if (expandedSchema.required && _.contains(expandedSchema.required, key)) {
property.required = true;
}
propParsed = util.mapProperty(property, key, '', mapping, refMap);
data.classMembers.push(propParsed.property);
if (propParsed.innerClass) {
data.innerClasses.push(propParsed.innerClass);
}
}
}
return data;
};
util.resolveTypeByRef = function(keyRef, refMap, propertyName, isArray) {
var data, innerSchema;
if (isArray == null) {
isArray = false;
}
data = {};
data.type = "";
innerSchema = Deref.util.findByRef(keyRef, refMap);
if (innerSchema) {
if (isArray) {
data.innnerSchema = {};
data.innnerSchema.items = innerSchema;
} else {
data.innnerSchema = innerSchema;
}
data.type = util.resolveType(innerSchema, propertyName);
} else if (keyRef) {
console.error("$ref not found: " + keyRef + " RefMap.keys -> [" + (Object.keys(refMap)) + "]");
console.error(JSON.stringify(refMap));
}
return data;
};
util.resolveType = function(schema, propertyName) {
var type;
type = "";
if (schema) {
if (schema.title) {
type = util.capitalize(schema.title);
} else {
type = util.capitalize(propertyName);
}
}
return type;
};
util.mapProperty = function(property, name, annotation, mapping, refMap) {
var auxType, data, innerClass, keyRef, keyRefData, primitiveType, _ref;
data = {};
data.property = {};
data.property.name = name;
if (property.required) {
data.property.notNull = true;
}
data.property.size = [];
if (property.minLength) {
data.property.size.push({
"name": "min",
"value": property.minLength
});
}
if (property.maxLength) {
data.property.size.push({
"name": "max",
"value": property.maxLength
});
}
data.property.comment = property.description;
if (property.items && property.items["$ref"]) {
keyRef = property.items["$ref"];
keyRefData = keyRefData = util.resolveTypeByRef(keyRef, refMap, name, true);
} else if (property["$ref"]) {
keyRef = property["$ref"];
keyRefData = util.resolveTypeByRef(keyRef, refMap, name);
data.property.type = keyRefData.type;
if (keyRefData.innnerSchema.type) {
property.type = keyRefData.innnerSchema.type;
} else {
property.properties = keyRefData.innnerSchema;
data.innerClass = util.resolveInnerClass(keyRefData.type, property, refMap, mapping);
property.type = util.resolveType(data.innerClass, name);
}
}
data.property.comment = property.description;
switch (property.type) {
case 'array':
auxType = "List";
if (keyRefData && keyRefData.innnerSchema.items !== void 0) {
primitiveType = mapping[keyRefData.innnerSchema.items.type];
if (keyRefData.innnerSchema.items.title) {
auxType += "<" + keyRefData.type + ">";
} else if (primitiveType) {
auxType += "<" + primitiveType + ">";
}
}
data.property.type = auxType;
break;
case 'object':
if (property.properties) {
if (keyRefData && keyRefData.type) {
data.property.type = keyRefData.type;
} else {
data.property.type = util.resolveType(property, name);
innerClass = util.resolveInnerClass(data.property.type, property, refMap, mapping);
data.innerClass = innerClass;
}
} else if (keyRefData && keyRefData.innnerSchema && keyRefData.innnerSchema.properties) {
data.property.type = keyRefData.type;
property.properties = keyRefData.innnerSchema;
data.innerClass = util.resolveInnerClass(keyRefData.type, property, refMap, mapping);
} else {
data.property.type = 'Map';
}
break;
default:
data.property.type = (_ref = mapping[property.type]) != null ? _ref : property.type;
}
if (data.property.type === "BigDecimal") {
data.property.decimalMax = property.maximum;
data.property.decimalMin = property.minimum;
} else if (data.property.type === "Long") {
data.property.max = property.maximum;
data.property.min = property.minimum;
}
data.property.kind = annotation + ("(\"" + data.property.name + "\")");
return data;
};
util.resolveInnerClass = function(name, property, refMap, mapping) {
var aux, data;
data = null;
if (property && !property.properties.title) {
data = {};
data.className = name;
data.classDescription = property.description;
aux = util.mapProperties(property, refMap, mapping);
data.classMembers = aux.classMembers;
}
return data;
};
util.loadSchemas = function(data) {
var row, schema, schemaName, schemas, _i, _len, _ref;
schemas = [];
_ref = data.schemas;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
row = _ref[_i];
for (schemaName in row) {
schema = util.parseSchema(row[schemaName], "Trouble parsing schema: " + schemaName);
schemas.push(schema);
}
}
return schemas;
};
util.parseResource = function(resource, parsed, annotations, mapping, schemas, parentUri, parentUriArgs) {
var formData, formEncoded, innerResource, m, mediaType, methodDef, request, respond, responseType, type, uriArgs, _i, _j, _len, _len1, _ref, _ref1, _ref2, _ref3;
if (parentUri == null) {
parentUri = "";
}
if (parentUriArgs == null) {
parentUriArgs = [];
}
_ref = resource.methods;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
m = _ref[_i];
methodDef = {};
methodDef.uri = parentUri + resource.relativeUri;
uriArgs = util.getUriParameter(resource, annotations.path, mapping);
methodDef.args = parentUriArgs.concat(uriArgs);
methodDef.args = methodDef.args.concat(util.getQueryparams(m.queryParameters, annotations.query, mapping));
methodDef.args = methodDef.args.concat(util.parseForm(m.body, annotations, mapping));
request = util.parseBodyJson(m.body, "" + methodDef.uri + " body");
respond = util.parseBodyJson(util.getBestValidResponse(m.responses).body, "" + methodDef.uri + " response");
type = null;
if (request.title) {
methodDef.args = (_ref1 = methodDef.args) != null ? _ref1 : [];
type = util.mapRequestResponse(request, schemas, mapping);
methodDef.args.push({
'kind': annotations.body,
'type': type,
'name': request.title.toLowerCase()
});
}
methodDef.request = (_ref2 = request.title) != null ? _ref2 : null;
responseType = util.mapRequestResponse(respond, schemas, mapping);
methodDef.respondComment = respond.title;
if (responseType) {
methodDef.respond = "<" + responseType + ">";
} else {
methodDef.respond = "<Response>";
}
methodDef.annotation = m.method.toUpperCase();
formData = _.find(methodDef.args, function(arg) {
return arg.type === "InputStream" || arg.type === "TypedFile";
});
formEncoded = _.find(methodDef.args, function(arg) {
return arg.kind.indexOf("@Field") > -1 || arg.kind.indexOf("@FormDataParam") > -1;
});
if (formData) {
methodDef.consumes = "MediaType.MULTIPART_FORM_DATA";
methodDef.additionalAnnotation = "Multipart";
}
if (formEncoded) {
methodDef.additionalAnnotation = "FormUrlEncoded";
}
mediaType = "application/json";
if (m.body && Object.keys(m.body)[0]) {
mediaType = Object.keys(m.body)[0];
}
if (methodDef.annotation !== "GET" && !type && !formData && !formEncoded) {
methodDef.additionalAnnotation = "Headers({\"Content-type: " + mediaType + "\"})";
}
methodDef.name = m.method + resource.displayName;
methodDef.displayName = resource.displayName;
parsed.push(methodDef);
}
if (resource.resources) {
_ref3 = resource.resources;
for (_j = 0, _len1 = _ref3.length; _j < _len1; _j++) {
innerResource = _ref3[_j];
util.parseResource(innerResource, parsed, annotations, mapping, schemas, methodDef.uri, uriArgs);
}
}
return void 0;
};
util.mapRequestResponse = function(scheme, schemas, mapping) {
var dataRef, deref, normSchema, primitiveType, type;
type = "";
switch (scheme.type) {
case "array":
if (scheme.items) {
type = "List<Maps>";
if (scheme.items.$ref) {
deref = Deref();
normSchema = deref(scheme, schemas);
dataRef = deref.util.findByRef(normSchema.items.$ref, deref.refs);
if (dataRef && dataRef.title) {
type = "List<" + (util.capitalize(dataRef.title)) + ">";
} else {
type = "List";
}
} else if (scheme.items.title) {
type = "List<" + (util.capitalize(scheme.title)) + ">";
} else if (scheme.items.type) {
primitiveType = mapping[scheme.items.type];
if (primitiveType) {
type = "List<" + primitiveType + ">";
}
}
} else {
type = "List";
}
break;
case "object":
if (scheme.properties) {
type = util.capitalize(scheme.title);
} else {
type = "Map";
}
break;
default:
console.warn("-------WARNING the following scheme doesn't have type: -------");
console.warn("" + (JSON.stringify(scheme)) + " ");
}
return type;
};
util.parseBodyJson = function(body, meta) {
var schema;
if (meta == null) {
meta = '';
}
schema = {};
if (body && body['application/json']) {
schema = util.parseSchema(body['application/json'].schema, meta);
}
return schema;
};
util.parseSchema = function(raw, meta) {
var e, schema;
if (meta == null) {
meta = '';
}
schema = {};
if (raw) {
try {
schema = JSON.parse(raw);
} catch (_error) {
e = _error;
console.log("-----JSON ERROR on " + meta + "---------");
throw e;
}
}
return schema;
};
util.getBestValidResponse = function(responses) {
var response, _ref, _ref1, _ref2, _ref3;
return response = (_ref = responses["304"]) != null ? _ref : response = (_ref1 = responses["204"]) != null ? _ref1 : response = (_ref2 = responses["201"]) != null ? _ref2 : response = (_ref3 = responses["200"]) != null ? _ref3 : response;
};
util.capitalize = function(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
};
util.sanitize = function(str) {
var aux, res;
aux = str.split(".");
res = '';
aux.forEach(function(it) {
return res += util.capitalize(it);
});
return res;
};
module.exports = util;
{
"id": "widget",
"type": "object",
"title": "Widget",
"description": "A widget is used to generated partials",
"required": ["id", "name", "groupId", "artifactId", "revision", "description"],
"properties": {
"name": {
"description": "The friendly name of the widget ",
"type": "string"
},
"composite":{
"type": "object",
"$ref": "widget#/definitions/innerProperties"
},
"etiquetas":{
"$ref": "widget#/definitions/innerProperties/tags"
}
},
"definitions": {
"innerProperties": {
"xid": {
"description": "The unique identifier of the widget ",
"type": "string"
},
"name": {
"description": "The friendly name of the widget ",
"type": "string"
},
"tags": {
"description": "Common set of keywords to categorize widgets",
"type": "array",
"items": {
"type": "string",
"format": "[a-z]{1,20}"
},
"uniqueItems": true
},
"groupId": {
"description": "The version of the Widget ",
"type": "string"
},
"artifactId": {
"description": "The version of the Widget ",
"type": "string"
},
"revision": {
"description": "The version of the Widget ",
"type": "string"
},
"description": {
"description": "The description of the Widget ",
"type": "string"
}
},
"something": {
"xid": {
"description": "The unique identifier of the widget ",
"type": "string"
},
"colour": {
"description": "The friendly name of the widget ",
"type": "string"
},
"ipsum": {
"description": "The version of the Widget ",
"type": "string"
},
"lorem": {
"description": "The description of the Widget ",
"type": "string"
}
}
}
}
{
"id": "widgetInlineProperty",
"type": "object",
"title": "WidgetInlineProperty",
"description": "A widget is used to generated partials",
"required": ["id", "name", "groupId", "artifactId", "revision", "description"],
"properties": {
"name": {
"description": "The friendly name of the widget ",
"type": "string"
},
"composite":{
"type": "object",
"description": "Inner properties",
"$ref": "widget#/definitions/innerProperties"
},
"zid":{
"$ref": "widget#/definitions/something"
},
"otherColor":{
"$ref": "widget#/definitions/something/colour"
}
}
}

Sorry, the diff of this file is not supported yet