use of io.vertx.core.json.JsonArray in project raml-module-builder by folio-org.
the class AnnotationGrabber method generateMappings.
// ^http.*?//.*?/apis/patrons/.*?/fines/.*
// ^http.*?\/\/.*?\/apis\/patrons\/?(.+?)*
// ^http.*?\/\/.*?\/apis\/([^\/]+)\/([^\/]+)(\?.*)
public static JsonObject generateMappings() throws Exception {
/* this class is one of the drivers for the client generation
* check if the plugin set the system property in the pom and only if
* so generate */
String clientGen = System.getProperty("client.generate");
String modDescr = System.getProperty("modDescrptor.generate");
if (clientGen != null) {
generateClient = true;
}
if ("true".equals(modDescr)) {
generateModDescrptor = true;
}
JsonObject globalClassMapping = new JsonObject();
// get classes in generated package
ClassPath classPath = ClassPath.from(Thread.currentThread().getContextClassLoader());
ImmutableSet<ClassPath.ClassInfo> classes = classPath.getTopLevelClasses(RTFConsts.INTERFACE_PACKAGE);
Collection<Object> classNames = Collections2.transform(classes, new Function<ClassPath.ClassInfo, Object>() {
@Override
public Object apply(ClassPath.ClassInfo input) {
log.info("Mapping functions in " + input.getName() + " class to appropriate urls");
// not needed - dont need transform function,
return input.getName();
// remove
}
});
// loop over all the classes from the package
classNames.forEach(val -> {
try {
ClientGenerator cGen = new ClientGenerator();
// ----------------- class level annotations -----------------------//
// -----------------------------------------------------------------//
// will contain all mappings for a specific class in the package
JsonObject classSpecificMapping = new JsonObject();
// get annotations via reflection for a class
Annotation[] annotations = Class.forName(val.toString()).getAnnotations();
// create an entry for the class name = ex. "class":"com.sling.rest.jaxrs.resource.BibResource"
classSpecificMapping.put(CLASS_NAME, val.toString());
classSpecificMapping.put(INTERFACE_NAME, val.toString());
// needed info - these are class level annotation - not method level
for (int i = 0; i < annotations.length; i++) {
// get the annotation type - example in jersey would we javax.ws.rs.Path
Class<? extends Annotation> type = annotations[i].annotationType();
// function
for (Method method : type.getDeclaredMethods()) {
Object value = method.invoke(annotations[i], (Object[]) null);
if (type.isAssignableFrom(Path.class)) {
classSpecificMapping.put(CLASS_URL, "^/" + value);
if (generateClient) {
cGen.generateClassMeta(val.toString(), value);
}
if (generateModDescrptor && classSpecificMapping.getString(CLASS_URL) != null) {
String url = classSpecificMapping.getString(CLASS_URL).substring(2);
if (!url.contains("rmbtests")) {
MDGenerator.ProvidesEntry pe = MDGenerator.INSTANCE.new ProvidesEntry();
if (url.contains("_/tenant")) {
url = "_tenant";
}
pe.setId(url);
MDGenerator.INSTANCE.addProvidesEntry(pe);
}
}
}
}
}
// ----------------- method level annotations ------------ //
// ------------------------------------------------------- //
/**
* will be used only if ModuleDescriptor generation is turned on
* maps all http verbs to a single url
*/
mdUrl2Verbs = new HashMap<>();
JsonArray methodsInAPath;
// iterate over all functions in the class
Method[] methods = Class.forName(val.toString()).getMethods();
for (int i = 0; i < methods.length; i++) {
JsonObject methodObj = new JsonObject();
JsonObject params = getParameterNames(methods[i]);
// get annotations on the method and add all info per method to its
// own methodObj
Annotation[] methodAn = methods[i].getAnnotations();
// System.out.println(methods[i].getName());
// put the name of the function
methodObj.put(FUNCTION_NAME, methods[i].getName());
methodObj.put(METHOD_PARAMS, params);
for (int j = 0; j < methodAn.length; j++) {
Class<? extends Annotation> type = methodAn[j].annotationType();
// System.out.println("Values of " + type.getName());
if (RTFConsts.POSSIBLE_HTTP_METHOD.contains(type.getName())) {
// put the method - get or post, etc..
methodObj.put(HTTP_METHOD, type.getName());
}
boolean replaceAccept = false;
if (type.isAssignableFrom(Produces.class)) {
// this is the accept header, right now can not send */*
// so if accept header equals any/ - change this to */*
replaceAccept = true;
}
for (Method method : type.getDeclaredMethods()) {
Object value = method.invoke(methodAn[j], (Object[]) null);
if (value.getClass().isArray()) {
List<Object> retList = new ArrayList<>();
for (int k = 0; k < Array.getLength(value); k++) {
if (replaceAccept) {
// replace any/any with */* to allow declaring accpet */* which causes compilation issues
// when declared in raml. so declare any/any in raml instead and replaced here
retList.add(((String) Array.get(value, k)).replaceAll("any/any", ""));
} else {
retList.add(Array.get(value, k));
}
}
// put generically things like consumes, produces as arrays
// since they can have multi values
methodObj.put(type.getName(), retList);
} else {
if (type.isAssignableFrom(Path.class)) {
String path = classSpecificMapping.getString(CLASS_URL) + URL_PATH_DELIMITER + value;
String regexPath = getRegexForPath(path);
// put path to function
methodObj.put(METHOD_URL, path);
// put regex path to function
methodObj.put(REGEX_URL, regexPath);
}
// System.out.println(" " + method.getName() + ": " + value.toString());
}
}
}
if (generateClient) {
cGen.generateMethodMeta(methodObj.getString(FUNCTION_NAME), methodObj.getJsonObject(METHOD_PARAMS), methodObj.getString(METHOD_URL), methodObj.getString(HTTP_METHOD), methodObj.getJsonArray(CONSUMES), methodObj.getJsonArray(PRODUCES));
}
// class
if (methodObj.getString(METHOD_URL) == null) {
methodObj.put(METHOD_URL, classSpecificMapping.getString(CLASS_URL));
methodObj.put(REGEX_URL, getRegexForPath(classSpecificMapping.getString(CLASS_URL)));
}
if (generateModDescrptor) {
String verb = methodObj.getString(HTTP_METHOD);
verb = verb.substring(verb.lastIndexOf(".") + 1);
String rootURL4Service = classSpecificMapping.getString(CLASS_URL).substring(1);
/*if(mdUrl2Verbs.get(path.substring(1)) != null){
mdUrl2Verbs.get(path.substring(1)).add(verb);
} else {
mdUrl2Verbs.put(path.substring(1), new JsonArray());
mdUrl2Verbs.get(path.substring(1)).add(verb);
}*/
if (mdUrl2Verbs.get(rootURL4Service) != null) {
mdUrl2Verbs.get(rootURL4Service).add(verb);
} else {
mdUrl2Verbs.put(rootURL4Service, new HashSet<String>());
mdUrl2Verbs.get(rootURL4Service).add(verb);
}
}
// this is the key - the regex path is the key to the functions
// represented by this url
// an array of functions which answer to this url (with get, delete,
// post, etc... methods)
methodsInAPath = classSpecificMapping.getJsonArray(methodObj.getString(REGEX_URL));
if (methodsInAPath == null) {
methodsInAPath = new JsonArray();
classSpecificMapping.put(methodObj.getString(REGEX_URL), methodsInAPath);
}
methodsInAPath.add(methodObj);
}
// System.out.println( val.toString() );
globalClassMapping.put(classSpecificMapping.getString(CLASS_URL), classSpecificMapping);
if (generateClient) {
cGen.generateClass(classSpecificMapping);
}
if (generateModDescrptor) {
BiConsumer<String, Set<String>> biConsumer = (key, value) -> {
if (!key.contains("_/tenant") && !key.contains("rmbtests")) {
MDGenerator.RoutingEntry re = MDGenerator.INSTANCE.new RoutingEntry();
JsonArray ja = new JsonArray();
value.forEach(verb -> {
ja.add(verb);
});
re.setMethods(ja);
re.setEntryPath(key);
re.setLevel("30");
re.setType("request-response");
MDGenerator.INSTANCE.addRoutingEntry(re);
}
};
mdUrl2Verbs.forEach(biConsumer);
MDGenerator.INSTANCE.generateMD();
// this is needed when the MDGenerator is used to generate
// partial MDs in submodules. the system variable is maintained
// across the sub module builds and if not reset will generate a
// partial MD for all sub modules
System.setProperty("modDescrptor.generate", "false");
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
});
// writeMappings(globalClassMapping);
return globalClassMapping;
}
use of io.vertx.core.json.JsonArray in project raml-module-builder by folio-org.
the class TenantAPI method deleteTenant.
@Validate
@Override
public void deleteTenant(Map<String, String> headers, Handler<AsyncResult<Response>> handlers, Context context) throws Exception {
context.runOnContext(v -> {
try {
String tenantId = TenantTool.calculateTenantId(headers.get(ClientGenerator.OKAPI_HEADER_TENANT));
log.info("sending... deleteTenant for " + tenantId);
tenantExists(context, tenantId, h -> {
boolean exists = false;
if (h.succeeded()) {
exists = h.result();
if (!exists) {
handlers.handle(io.vertx.core.Future.succeededFuture(DeleteTenantResponse.withPlainInternalServerError("Tenant does not exist: " + tenantId)));
log.error("Can not delete. Tenant does not exist: " + tenantId);
return;
} else {
log.info("Deleting tenant " + tenantId);
}
} else {
handlers.handle(io.vertx.core.Future.failedFuture(h.cause().getMessage()));
log.error(h.cause().getMessage(), h.cause());
return;
}
String sqlFile = null;
try {
/* InputStream is = TenantAPI.class.getClassLoader().getResourceAsStream(DELETE_JSON);
if(is == null){
log.info("No delete json to use for deleting tenant " + tenantId);
handlers.handle(io.vertx.core.Future.succeededFuture(DeleteTenantResponse.withNoContent()));
return;
}
sqlFile = IOUtils.toString(is);*/
SchemaMaker sMaker = new SchemaMaker(tenantId, PostgresClient.getModuleName(), TenantOperation.DELETE, null, PomReader.INSTANCE.getRmbVersion());
sqlFile = sMaker.generateDDL();
} catch (Exception e1) {
handlers.handle(io.vertx.core.Future.failedFuture(e1.getMessage()));
log.error(e1.getMessage(), e1);
return;
}
log.info("Attempting to run delete script for: " + tenantId);
log.debug("GENERATED SCHEMA " + sqlFile);
/* connect as user in postgres-conf.json file (super user) - so that all commands will be available */
PostgresClient.getInstance(context.owner()).runSQLFile(sqlFile, true, reply -> {
try {
String res = "";
if (reply.succeeded()) {
res = new JsonArray(reply.result()).encodePrettily();
if (reply.result().size() > 0) {
log.error("Unable to run the following commands during tenant delete: ");
reply.result().forEach(System.out::println);
handlers.handle(io.vertx.core.Future.succeededFuture(DeleteTenantResponse.withPlainBadRequest(res)));
} else {
OutStream os = new OutStream();
os.setData(res);
handlers.handle(io.vertx.core.Future.succeededFuture(DeleteTenantResponse.withNoContent()));
}
} else {
log.error(reply.cause().getMessage(), reply.cause());
handlers.handle(io.vertx.core.Future.succeededFuture(DeleteTenantResponse.withPlainInternalServerError(reply.cause().getMessage())));
}
} catch (Exception e) {
log.error(e.getMessage(), e);
handlers.handle(io.vertx.core.Future.succeededFuture(DeleteTenantResponse.withPlainInternalServerError(e.getMessage())));
}
});
});
} catch (Exception e) {
log.error(e.getMessage(), e);
handlers.handle(io.vertx.core.Future.succeededFuture(DeleteTenantResponse.withPlainInternalServerError(e.getMessage())));
}
});
}
use of io.vertx.core.json.JsonArray in project vertx-micrometer-metrics by vert-x3.
the class MicrometerMetricsOptions method loadLabelMatches.
private List<Match> loadLabelMatches(JsonObject json) {
List<Match> list = new ArrayList<>();
JsonArray monitored = json.getJsonArray("labelMatchs", new JsonArray());
monitored.forEach(object -> {
if (object instanceof JsonObject)
list.add(new Match((JsonObject) object));
});
return list;
}
use of io.vertx.core.json.JsonArray in project hse-cws by holuhoev.
the class JsonParser method parse.
public <T> List<T> parse(String str, Class<T> clazz) {
if (str == null)
return null;
JsonArray jsonArray = new JsonArray(str);
List<T> list = new LinkedList<>();
try {
for (int i = 0; i < jsonArray.size(); i++) {
JsonObject jsonObject = jsonArray.getJsonObject(i);
T object = clazz.newInstance();
for (Field field : clazz.getDeclaredFields()) {
JsonAttribute jsonAttributeAnnotation = field.getAnnotation(JsonAttribute.class);
if (jsonAttributeAnnotation != null) {
field.setAccessible(true);
Object value = jsonObject.getMap().get(isNullOrEmpty(jsonAttributeAnnotation.name()) ? field.getName() : jsonAttributeAnnotation.name());
if (field.getAnnotation(Convert.class) != null) {
Object converterInstance = field.getAnnotation(Convert.class).converter().newInstance();
if (converterInstance instanceof AttributeConverter) {
value = ((AttributeConverter) converterInstance).convertToEntityAttribute(value);
}
}
field.set(object, value);
}
}
list.add(object);
}
return list;
} catch (InstantiationException | IllegalAccessException e) {
logger.error(e.getMessage());
}
return null;
}
use of io.vertx.core.json.JsonArray in project okapi by folio-org.
the class DockerModuleHandle method createContainer.
private void createContainer(int exposedPort, Handler<AsyncResult<Void>> future) {
logger.info("create container from image " + image);
JsonObject j = new JsonObject();
j.put("AttachStdin", Boolean.FALSE);
j.put("AttachStdout", Boolean.TRUE);
j.put("AttachStderr", Boolean.TRUE);
j.put("StopSignal", "SIGTERM");
if (env != null) {
JsonArray a = new JsonArray();
for (EnvEntry nv : env) {
a.add(nv.getName() + "=" + nv.getValue());
}
j.put("env", a);
}
j.put("Image", image);
JsonObject hp = new JsonObject().put("HostPort", Integer.toString(hostPort));
JsonArray ep = new JsonArray().add(hp);
JsonObject pb = new JsonObject();
pb.put(Integer.toString(exposedPort) + "/tcp", ep);
JsonObject hc = new JsonObject();
hc.put("PortBindings", pb);
hc.put("PublishAllPorts", Boolean.FALSE);
j.put("HostConfig", hc);
if (this.cmd != null && this.cmd.length > 0) {
JsonArray a = new JsonArray();
for (String aCmd : cmd) {
a.add(aCmd);
}
j.put("Cmd", a);
}
if (dockerArgs != null) {
for (Map.Entry<String, Object> entry : dockerArgs.properties().entrySet()) {
j.put(entry.getKey(), entry.getValue());
}
}
String doc = j.encodePrettily();
doc = doc.replace("%p", Integer.toString(hostPort));
logger.info("createContainer\n" + doc);
postUrlBody(dockerUrl + "/containers/create", doc, future);
}
Aggregations