Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import com.networknt.rpc.router.ServiceHandler;
import com.networknt.utility.NioUtils;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.HttpString;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;

Expand All @@ -21,10 +22,15 @@ public class FrameworkListHandler implements Handler {
static private final XLogger logger = XLoggerFactory.getXLogger(FrameworkListHandler.class);
static private Set<String> frameworks = FrameworkRegistry.getInstance().getFrameworks();

/**
* Returns a JSON list of all available frameworks defined in the service.yml of codegen-cli.
* If any issues occur with converting the result to JSON, an empty string is returned (not an empty json list).
*/
@Override
public ByteBuffer handle(HttpServerExchange exchange, Object input) {
logger.entry(input);
String result = "";
exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
try {
result = Config.getInstance().getMapper().writeValueAsString(frameworks);
} catch (JsonProcessingException e) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,25 @@
package com.networknt.codegen.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jsoniter.any.Any;
import com.networknt.codegen.CodegenWebConfig;
import com.networknt.codegen.FrameworkRegistry;
import com.networknt.codegen.Generator;
import com.networknt.config.Config;
import com.networknt.rpc.Handler;
import com.networknt.rpc.router.JsonHandler;
import com.networknt.rpc.router.ServiceHandler;
import com.networknt.schema.JsonSchema;
import com.networknt.schema.JsonSchemaFactory;
import com.networknt.schema.ValidationMessage;
import com.networknt.status.Status;
import com.networknt.utility.HashUtil;
import com.networknt.utility.NioUtils;
import io.undertow.server.HttpServerExchange;
import io.undertow.server.handlers.form.FormData;
import io.undertow.util.HttpString;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;

Expand All @@ -31,6 +38,7 @@
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static java.io.File.separator;

Expand Down Expand Up @@ -61,23 +69,18 @@ public ByteBuffer handle(HttpServerExchange exchange, Object input) {
String zipFile = output + ".zip";
String projectFolder = codegenWebConfig.getTmpFolder() + separator + output;

List<Map<String, Object>> generators = getGeneratorListFromFormData((FormData)input);
List<Map<String, Object>> generators = (List<Map<String, Object>>)input;

if(generators == null || generators.size() == 0) {
logger.error("Did not receive any generators in the request.");
Status status = new Status(STATUS_MISSING_GENERATOR_ITEM);
exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
return NioUtils.toByteBuffer(status.toString());
}
for(Map<String, Object> generatorMap: generators) {
String framework = (String)generatorMap.get("framework");
Object model = Any.wrap(generatorMap.get("model")); // should be a JSON of spec or IDL
Map<String, Object> config; // should be a json of config
try {
config = new ObjectMapper().readValue((String)generatorMap.get("config"), Map.class);
} catch (IOException e) {
logger.error("Failed to convert the given object to a map representation: " + e.getMessage());
return null;
}
Map<String, Object> config = (Map<String, Object>) generatorMap.get("config");
if(!FrameworkRegistry.getInstance().getFrameworks().contains(framework)) {
Status status = new Status(STATUS_INVALID_FRAMEWORK, framework);
return NioUtils.toByteBuffer(status.toString());
Expand Down Expand Up @@ -108,6 +111,10 @@ public ByteBuffer handle(HttpServerExchange exchange, Object input) {
logger.error("Exception:", e);
}

exchange.getResponseHeaders()
.add(new HttpString("Content-Type"), "application/zip")
.add(new HttpString("Content-Disposition"), "attachment");

// return the zip file
File file = new File(codegenWebConfig.getZipFolder() + separator + zipFile);
return NioUtils.toByteBuffer(file);
Expand Down Expand Up @@ -150,4 +157,20 @@ private List<Map<String, Object>> getGeneratorListFromFormData(FormData formData

return generatorsList;
}

@Override
public ByteBuffer validate(String serviceId, Object object) {
// get schema from serviceId, remember that the schema is for the data object only.
// the input object is the data attribute of the request body.
Map<String, Object> serviceMap = (Map<String, Object>) JsonHandler.schema.get(serviceId);
if(logger.isDebugEnabled()) {
try {
logger.debug("serviceId = " + serviceId + " serviceMap = " + Config.getInstance().getMapper().writeValueAsString(serviceMap));
} catch (Exception e) {
logger.error("Exception:", e);
}
}
logger.debug("Skipping validation on generator request for now.");
return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import com.networknt.rpc.router.ServiceHandler;
import com.networknt.utility.NioUtils;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.HttpString;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;

Expand All @@ -25,6 +26,7 @@ public class SchemaGetHandler implements Handler {

@Override
public ByteBuffer handle(HttpServerExchange exchange, Object input) {
exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
logger.entry(input);
Map<String, Object> map = (Map<String, Object>)input;
String framework = (String)map.get("framework");
Expand All @@ -35,7 +37,6 @@ public ByteBuffer handle(HttpServerExchange exchange, Object input) {
bf = generator.getConfigSchema();
} catch (IOException e) {
// return empty back in this case.

}
return bf;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import com.networknt.utility.NioUtils;
import io.undertow.server.HttpServerExchange;
import io.undertow.server.handlers.form.FormData;
import io.undertow.util.HttpString;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;

Expand All @@ -15,7 +16,8 @@
import java.util.stream.Stream;

/**
* Created by nicho on 2017-07-08.
* @author Nicholas Azar
* Created on July 8, 2017.
*/
@ServiceHandler(id="lightapi.net/codegen/validateUploadFile/0.0.1")
public class ValidateUploadFileHandler implements Handler {
Expand All @@ -31,6 +33,7 @@ public class ValidateUploadFileHandler implements Handler {
*/
@Override
public ByteBuffer handle(HttpServerExchange exchange, Object o) {
exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
logger.entry(o);
if (o instanceof FormData) {
File file = this.getFileFromForm((FormData)o);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.networknt.codegen.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.networknt.client.Http2Client;
import com.networknt.exception.ApiException;
import com.networknt.exception.ClientException;
Expand All @@ -17,9 +19,11 @@
import org.xnio.IoUtils;
import org.xnio.OptionMap;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
Expand Down Expand Up @@ -61,14 +65,14 @@ public void testMissingGeneratorItem() throws ClientException {
}
try {
connection.getIoThread().execute(() -> {
final ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath("/api/zip");
final ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath("/api/json");

request.getRequestHeaders().put(Headers.HOST, "localhost");
request.getRequestHeaders().put(Headers.AUTHORIZATION, auth);
request.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/x-www-form-urlencoded");
request.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/json");
request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
try {
connection.sendRequest(request, client.createClientCallback(reference, latch, Http2Client.getFormDataString(params)));
connection.sendRequest(request, client.createClientCallback(reference, latch, new ObjectMapper().writeValueAsString(params)));
} catch (Exception e) {
e.printStackTrace();
}
Expand All @@ -90,15 +94,13 @@ public void testMissingGeneratorItem() throws ClientException {
}

@Test
public void testInvalidFramework() throws ClientException {
Map<String, String> params = new HashMap<>();
public void testInvalidFramework() throws ClientException, IOException {
Map<String, Object> params = new HashMap<>();
params.put("host", "lightapi.net");
params.put("service", "codegen");
params.put("action", "generate");
params.put("version", "0.0.1");
params.put("generator.framework", "invalid");
params.put("generator.model", "{\"key\":\"value\"}");
params.put("generator.config", "{\"key\":\"value\"}");
params.put("data", new ObjectMapper().readValue("[{\"framework\": \"invalid\", \"model\": {\"key\":\"value\"}, \"config\": {\"key\":\"value\"}}]", List.class));

final AtomicReference<ClientResponse> reference = new AtomicReference<>();
final Http2Client client = Http2Client.getInstance();
Expand All @@ -111,14 +113,14 @@ public void testInvalidFramework() throws ClientException {
}
try {
connection.getIoThread().execute(() -> {
final ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath("/api/zip");
final ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath("/api/json");
request.getRequestHeaders().put(Headers.HOST, "localhost");
request.getRequestHeaders().put(Headers.AUTHORIZATION, auth);
request.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/x-www-form-urlencoded");
request.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/json");
request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
try {
connection.sendRequest(request, client.createClientCallback(reference, latch, Http2Client.getFormDataString(params)));
} catch (UnsupportedEncodingException e) {
connection.sendRequest(request, client.createClientCallback(reference, latch, new ObjectMapper().writeValueAsString(params)));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
});
Expand All @@ -140,14 +142,14 @@ public void testInvalidFramework() throws ClientException {


@Test
public void testGenerator() throws ClientException, ApiException, UnsupportedEncodingException {
Map<String, String> params = new HashMap<>();
public void testGenerator() throws ClientException, ApiException, IOException {
Map<String, Object> params = new HashMap<>();
params.put("host", "lightapi.net");
params.put("service", "codegen");
params.put("action", "generate");
params.put("version", "0.0.1");
params.put("generator.framework", "swagger");
params.put("generator.model", "{\n" +

String model = "{\n" +
" \"swagger\": \"2.0\",\n" +
" \"info\": {\n" +
" \"description\": \"This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.\",\n" +
Expand Down Expand Up @@ -1201,8 +1203,8 @@ public void testGenerator() throws ClientException, ApiException, UnsupportedEnc
" \"description\": \"Find out more about Swagger\",\n" +
" \"url\": \"http://swagger.io\"\n" +
" }\n" +
" }");
params.put("generator.config", "{\n" +
" }";
String config = "{\n" +
" \"rootPackage\": \"com.networknt.petstore\",\n" +
" \"handlerPackage\": \"com.networknt.petstore.handler\",\n" +
" \"modelPackage\": \"com.networknt.petstore.model\",\n" +
Expand All @@ -1212,7 +1214,9 @@ public void testGenerator() throws ClientException, ApiException, UnsupportedEnc
" \"version\": \"1.0.1\",\n" +
" \"overwriteHandler\": false,\n" +
" \"overwriteHandlerTest\": false\n" +
" }");
" }";

params.put("data", new ObjectMapper().readValue("[{\"framework\": \"swagger\", \"model\": " + model + ", \"config\": "+ config + "}]", List.class));

final AtomicReference<ClientResponse> reference = new AtomicReference<>();
final Http2Client client = Http2Client.getInstance();
Expand All @@ -1227,14 +1231,14 @@ public void testGenerator() throws ClientException, ApiException, UnsupportedEnc
connection.getIoThread().execute(new Runnable() {
@Override
public void run() {
final ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath("/api/zip");
final ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath("/api/json");
request.getRequestHeaders().put(Headers.HOST, "localhost");
request.getRequestHeaders().put(Headers.AUTHORIZATION, auth);
request.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/x-www-form-urlencoded");
request.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/json");
request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
try {
connection.sendRequest(request, client.createClientCallback(reference, latch, Http2Client.getFormDataString(params)));
} catch (UnsupportedEncodingException e) {
connection.sendRequest(request, client.createClientCallback(reference, latch, new ObjectMapper().writeValueAsString(params)));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
Expand Down
16 changes: 1 addition & 15 deletions codegen-web/view/src/AppActions.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ class AppActions {
static TEST_AUTH_KEY = 'Bearer eyJraWQiOiIxMDAiLCJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJ1cm46Y29tOm5ldHdvcmtudDpvYXV0aDI6djEiLCJhdWQiOiJ1cm46Y29tLm5ldHdvcmtudCIsImV4cCI6MTgwOTAxMTkyMCwianRpIjoiR2NpMGJQZXoxb0hxT1VzYUZ6WmRkdyIsImlhdCI6MTQ5MzY1MTkyMCwibmJmIjoxNDkzNjUxODAwLCJ2ZXJzaW9uIjoiMS4wIiwidXNlcl9pZCI6InN0ZXZlIiwidXNlcl90eXBlIjoiRU1QTE9ZRUUiLCJjbGllbnRfaWQiOiJmN2Q0MjM0OC1jNjQ3LTRlZmItYTUyZC00YzU3ODc0MjFlNzIiLCJzY29wZSI6WyJjb2RlZ2VuLnIiLCJjb2RlZ2VuLnciLCJzZXJ2ZXIuaW5mby5yIl19.MMIjxGlQknwtlizh80wX1oB75N8wfhqMttP7i3mpKwBa-zUKZcjgtE4rmc39qYXPti9ge3uGHWCQdMOlimf4Psoah-qtsQmZhuCOwejN_OhwvlIbLxCYYP9WaQM_zyuDv6luFO5ETsZQ0-QkxQHkBq1Y3D0VpHNuNlN3ulK5sK678XKw_2VNP6JM85hh1QW8pWYappkAledvyfJC3w5sUWdi3kP_rTGiumXYA0ZoY-hdp9erlin0ClEZ7qPmHSHW_TFjuRr_6rDwE1Xg-U6wNk1hMMFF4161nfdPIhDhCsjG3J4hM0y0ZluI3BnQaGKwtqyDNIJGiiTkK1ckX1qaIw'

static VALIDATE_JSON_UPLOAD_REQUEST = {
action: "/api/multipart",
action: "/api/form",
multiple: false,
showUploadList: true,
accept: '.json',
Expand All @@ -32,20 +32,6 @@ class AppActions {
action: "listFramework",
version: AppActions.API_VERSION
};

static GENERATE_REQUEST = (framework, model, config) => {return {
host: AppActions.API_HOST,
service: AppActions.API_SERVICE,
action: "generate",
version: AppActions.API_VERSION,
data: {
generators: [{
framework: framework,
model: model,
config: config
}]
}
}}
}

export {AppActions}
17 changes: 17 additions & 0 deletions codegen-web/view/src/AppServices.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,23 @@ class AppServices {
headers: {'Authorization': AppActions.TEST_AUTH_KEY}
});
}

static generate(framework, model, config) {
return axios.post(AppServices.JSON_API, {
host: AppActions.API_HOST,
service: AppActions.API_SERVICE,
action: "generate",
version: AppActions.API_VERSION,
data: [{
framework: framework,
model: model,
config: config
}]
}, {
responseType: 'blob',
headers: {'Authorization': AppActions.TEST_AUTH_KEY}
});
}
}

export {AppServices}
Loading