diff options
Diffstat (limited to 'ncomp-sirius-manager-generator/src')
10 files changed, 1277 insertions, 0 deletions
diff --git a/ncomp-sirius-manager-generator/src/main/groovy/org/openecomp/ncomp/sirius/manager/generator/ControllerGenerator.groovy b/ncomp-sirius-manager-generator/src/main/groovy/org/openecomp/ncomp/sirius/manager/generator/ControllerGenerator.groovy new file mode 100644 index 0000000..cf2fd59 --- /dev/null +++ b/ncomp-sirius-manager-generator/src/main/groovy/org/openecomp/ncomp/sirius/manager/generator/ControllerGenerator.groovy @@ -0,0 +1,303 @@ + +/*- + * ============LICENSE_START========================================== + * OPENECOMP - DCAE + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + */ + +package org.openecomp.ncomp.sirius.manager.generator +
+
+import org.openecomp.ncomp.sirius.manager.console.Utils; +import org.openecomp.ncomp.sirius.manager.controllermodel.ControllerModel + +import groovy.text.SimpleTemplateEngine
+ +import org.eclipse.emf.ecore.EClass
+import org.eclipse.emf.ecore.EFactory; +import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.EOperation
+import org.eclipse.emf.ecore.EPackage;
+import org.json.JSONObject; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.Yaml; +
+
+class ControllerGenerator {
+ EObject o + EObject providerObject + String providerPackage + String providerPrefix
+ ControllerModel m
+ EPackage p
+ String subName
+ String clientName
+ String prefix
+ String type = "R"
+ ControllerGenerator root; + boolean enableDrools = false; + boolean enableIRequestHandler = true; + boolean enableISwaggerHandler = false; + boolean enableISiriusPlugin = true;
+ public ControllerGenerator(EObject o, ControllerModel m) {
+ this.o = o
+ this.m = m
+ root = this
+ }
+ public String packageName() {
+ if (this != root && clientName == null) {
+ return root.packageName() + (root.o.eClass().EPackage != o.eClass().EPackage? "." + subName : "")
+ }
+ EPackage p = o.eClass().getEPackage()
+ return p.nsURI.replaceAll('.'+p.nsPrefix+'$',"") + ".servers.${p.nsPrefix}"
+ }
+ public String factoryName() {
+ EPackage p = o.eClass().getEPackage()
+ return "${p.nsPrefix.capitalize()}Factory"
+ }
+ public String packageName2() {
+ EPackage p = o.eClass().getEPackage()
+ return "${p.nsPrefix.capitalize()}Package"
+ }
+ public def operations() {
+ def l = []
+ l += o.eClass().getEOperations();
+ o.eClass().getEAllSuperTypes().each { EClass c ->
+ l += c.getEOperations()
+ }
+ return l
+ }
+ public def operationsProvider() { + def l = [] + l += o.eClass().getEOperations(); + o.eClass().getEAllSuperTypes().each { EClass c -> + if (providerObject != null && ( + providerObject.eClass().getEAllSuperTypes().contains(c) + || c == providerObject.eClass())) return + l += c.getEOperations() + } + return l + } + public void generateAnt(String fname, boolean xtext, boolean tar) {
+ def xml = new XmlSlurper().parseText(new File(".classpath").text)
+ SimpleTemplateEngine engine = new SimpleTemplateEngine()
+ def env = [g:this,m:m,sourceDirectories:[],projects:[],xtext:xtext,tar:tar]
+ xml.classpathentry.each { e ->
+ switch (e.@kind) {
+ case "src":
+ def path = e.@path.toString()
+ if (path.startsWith("/")) {
+ println "path=$path"
+ switch (path) {
+ case "/org.openecomp.ncomp.webservice": env.projects += "org.openecomp.ncomp.utils.jar"; break
+ default: env.projects += path.replace("/","") + ".jar"
+ }
+ }
+ else {
+ env.sourceDirectories += path
+ }
+ break
+// <classpathentry kind="lib" path="/sirius-store/artifacts/org.openecomp.ncomp.gwt.api.jar"/>
+ case "lib":
+ def path = e.@path.toString()
+ switch (path) {
+ case ~/\/sirius-store.*/:
+ def a = path.split("/")
+ def jar = a[3]
+ println "jar=$jar"
+ env.projects += a[3]
+ }
+ }
+ }
+ println "Creating $fname"
+ def x = engine.createTemplate(new File("$m.templateDirectory/ant_xml").text).make(env)
+ File f = new File(fname)
+ f.delete()
+ f.parentFile.mkdirs()
+ f << x
+ }
+ public void generateScripts(String dir,String n) {
+ SimpleTemplateEngine engine = new SimpleTemplateEngine()
+ EPackage p = o.eClass().getEPackage() + def env = [g:this,m:m, n:n, nsPrefix: p.getNsPrefix()]
+ env.sClass = "${root.m.prefix}${root.o.eClass().name}Server"
+ env.sPackage = root.packageName()
+ String fname = "$dir/${n}-controller"
+ println "Creating $fname" + println "Using $m.templateDirectory/controller"
+ def x = engine.createTemplate(new File("$m.templateDirectory/controller").text).make(env)
+ File f = new File(fname)
+ f.delete()
+ f.parentFile.mkdirs()
+ f << x
+ }
+ public void generate(String dir) { + if (enableDrools && ! enableISiriusPlugin) { + System.err.println "Drools requires ISiriusPlugin, thus enabling ISiriusPlugin" + enableISiriusPlugin = true + }
+ SimpleTemplateEngine engine = new SimpleTemplateEngine()
+
+ File dir1 = new File(dir)
+ if (root == this && dir1.exists()) dir1.deleteDir()
+ dir1.mkdir()
+
+ EPackage p = o.eClass().getEPackage()
+
+ ["Server":[:],"Client":[:],"Console":[:],"Controller":[:],"Factory":[:],"Provider":[:]].each {n, c ->
+ if (root != this) {
+ switch (n) {
+ case "Server": return
+ case "Factory": if (type == "A" || type == "C" || type == "P") return; + case "Client": case "Console": if (type == "P") return;
+ }
+ }
+ def env = [
+ g: this,
+ o: o,
+ p: p,
+ prefix: m.prefix,
+ name : o.eClass().getName(),
+ nsPrefix : p.getNsPrefix(),
+ nsURI : p.getNsURI(),
+ packageName : packageName(),
+ cName : "${m.prefix}${o.eClass().name}$n",
+ fName : factoryName(),
+ path : root == this ? "resources" : subName,
+ ]
+ switch (n) {
+ case "Provider": env.cName = "${m.prefix}${o.eClass().name}ProviderTemplate"; break
+ case "Controller": env.cName = "${m.prefix}${o.eClass().name}"; break + case "Factory": env.cName = "${m.prefix}${env.fName}"; break
+ }
+ env.sClass = "${root.m.prefix}${root.o.eClass().name}Server"
+ env.sPackage = root == this ? "" : root.packageName()
+ def fname = "$dir/${env.cName}.java"
+ println "Creating $fname" + println "Using $m.templateDirectory/${n}.java"
+ def x = engine.createTemplate(new File("$m.templateDirectory/${n}.java").text).make(env)
+ def f = new File(fname)
+ f.parentFile.mkdirs()
+ f << x
+ switch (n) { + case "Provider": + def fname2 = "${dir.replace('src/main/sirius-gen','src/main/java')}/${env.cName}.java".replace("ProviderTemplate", "Provider") + def f2 = new File(fname2) + if (!f2.exists()) { + println "Creating $fname2" + f2.parentFile.mkdirs() + f2 << x.toString().replace("${o.eClass().name}ProviderTemplate", "${o.eClass().name}Provider") + } + break + } + // println "x=$x"
+ } + generateYaml(dir)
+ subApis.each { ControllerGenerator g ->
+ g.generate(dir + (g.o.eClass().EPackage != o.eClass().EPackage ? "/$g.subName" : ""))
+ }
+ } + def generateYaml(dir) { + def y = [operations:[:], messages:[dummy:[:]]] + EClass c = o.eClass() + c.getEAllOperations().each { EOperation op -> + y.operations[op.name] = [:] + y.messages[op.name] = [ + errorCode: "$op.name-FAILED-5001W", + messageFormat: "{0}", + description: "Operation Failed with Exception" + ] + } + c.getEAllOperations().each { EOperation op -> + y.operations["REMOTE_$op.name"] = [decription:"Remote call $op.name"] + y.messages["REMOTE_$op.name"] = [ + errorCode: "REMOTE-$op.name-FAILED-5001W", + messageFormat: "{0}", + description: "Remote Operation Failed with Exception" + ] + } + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + Yaml yaml = new Yaml(options); + JSONObject j = Utils.object2json(y) + File f = new File("src/main/sirius-gen/${c.name}.yaml") + if (f.exists()) f.delete() + f << yaml.dump(yaml.load(j.toString())) + }
+ def subApis = []
+ public void addObject(String subpackage, EObject o, ControllerModel m, boolean enableIRequestHandler = false, boolean enableISiriusPlugin = false) {
+ def g = new ControllerGenerator(o,m)
+ g.root = this
+ g.subName = subpackage
+ g.type = "O" + g.enableIRequestHandler = enableIRequestHandler + g.enableISiriusPlugin = enableISiriusPlugin
+ subApis += g
+ }
+ public void addApi(String name, EObject o, ControllerModel m, boolean enableIRequestHandler = false, boolean enableISiriusPlugin = false) {
+ def g = new ControllerGenerator(o,m)
+ g.root = this
+ g.subName = name
+ g.type = "A" + g.enableIRequestHandler = enableIRequestHandler + g.enableISiriusPlugin = enableISiriusPlugin
+ subApis += g
+ }
+ public void addProvider(String name, EObject o, ControllerModel m) { + def g = new ControllerGenerator(o,m) + g.root = this + g.subName = name + g.type = "P" + g.enableIRequestHandler = false + g.enableISiriusPlugin = false + subApis += g + } + def subClients = []
+ public void addClient(String name, EObject o, ControllerModel m, boolean enableIRequestHandler = false, boolean enableISiriusPlugin = false) {
+ def g = new ControllerGenerator(o,m)
+ g.root = this
+ g.clientName = name
+ g.type = "C" + g.enableIRequestHandler = enableIRequestHandler + g.enableISiriusPlugin = enableISiriusPlugin
+ subClients += g
+ }
+ List<String> aliases = new ArrayList<String>();
+ public void addAlias(String alias) {
+ aliases.add(alias);
+ }
+ List<String> factories = new ArrayList<String>(); + def useNew = [:]
+ public void addFactory(String factory, boolean useNew = true) {
+ factories.add(factory); + this.useNew[factory] = useNew
+ } + public void enableDrools() { + enableDrools = true; + } + public void addFactory(EFactory f) { + def p = f.ePackage + String f1 = "${p.nsURI}.${p.name.capitalize()}Factory" + addFactory(f1,false) + } + public void setProvider(EObject o2, String prefix) { + providerObject = o2 + EPackage p = o2.eClass().getEPackage() + providerPackage = p.nsURI.replaceAll('.'+p.nsPrefix+'$',"") + ".servers.${p.nsPrefix}" + providerPrefix = prefix + }
+}
diff --git a/ncomp-sirius-manager-generator/src/main/templates/Client.java b/ncomp-sirius-manager-generator/src/main/templates/Client.java new file mode 100644 index 0000000..4b38e94 --- /dev/null +++ b/ncomp-sirius-manager-generator/src/main/templates/Client.java @@ -0,0 +1,125 @@ + +/*- + * ============LICENSE_START========================================== + * OPENECOMP - DCAE + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + */ + +<% +import org.openecomp.ncomp.utils.StringUtil +%>// Autogenerated +// Do not edit. No need to extend this class. +package $packageName; + +import org.openecomp.ncomp.sirius.manager.AbstractClient; +import org.openecomp.ncomp.sirius.manager.HighAvailabilityClient; +import org.openecomp.ncomp.sirius.manager.GenericHttpClient; + +import org.apache.log4j.Logger; + +import org.openecomp.logger.EcompLogger; + +import org.eclipse.emf.common.util.EList; +import org.eclipse.emf.ecore.EClass; + +import ${p.nsURI}.impl.${name}Impl; +import ${p.nsURI}.${g.packageName2()}; +import ${packageName}.logging.${name}OperationEnum; +import ${packageName}.logging.${name}MessageEnum; + +<% if (sPackage != "") { %> +import ${sPackage}.${prefix}${g.root.o.eClass().name}; <% } %> + + + + +@SuppressWarnings("unchecked") +public class ${cName} extends ${name}Impl { + public static final Logger logger = Logger.getLogger(${cName}.class); + static final EcompLogger ecomplogger = EcompLogger.getEcompLogger(); + public AbstractClient client; + + public ${cName}(String file, String name) { + ${prefix}${g.root.o.eClass().name}.ecoreSetup(); + client = new GenericHttpClient(file,name); + client.add("/$path", this); + } + + public ${cName}(String file, String name1, String name2) { + HighAvailabilityClient client1 = new HighAvailabilityClient(file,name1,name2); + client = client1.all; // requests should be forwarded to all. + client.add("/$path", this); + } + + public ${cName}(AbstractClient c) { + client = c; + client.add("/resources", this); + } + + +<% g.operations().each { op -> + def decl = [] + def vars = [] + def timeout = "null" + if (op.getEParameters().find { it.name == "cx" }) { + decl += "org.json.JSONObject cx" + vars += "cx" + timeout = 'cx != null && cx.has("timeout") ? cx.getLong("timeout") : null' + } + def override = "@Override" + def path1 = g.subName == null ? "\"/$path\"" : "\"/$g.subName\"" + if (g.root != g && g.root.o.eClass().EPackage == o.eClass().EPackage) { + decl += "String path" + override = "" + path1 = "path" + } + op.getEParameters().each { p -> + if (p.name == "cx") return + vars += p.name + if (p.isMany()) + decl += "EList<${p.getEType().getInstanceClassName()}> $p.name" + else { + if (p.getEType()==null) System.err.println "$op.name $p.name $p" + decl += "${p.getEType().getInstanceClassName()} $p.name" + } + } + + + def rType = op.getEType() == null ? "void" : op.getEType().getInstanceClassName() + if (op.isMany()) rType = "EList<$rType>" + def ret = rType == "void" ? "" : "return res;" + def decl1 = rType == "void" ? "" : "${rType} res;" + def decl2 = rType == "void" ? "" : "res = ($rType) " +%> + $override + public ${rType} ${op.name}(${StringUtil.join(decl, ", ")}) { + EClass c = ${g.packageName2()}.eINSTANCE.get${g.o.eClass().name}(); //foo + ecomplogger.recordMetricEventStart(); + ecomplogger.setOperation(${name}OperationEnum.REMOTE_${op.name}); + $decl1 + try { + ${decl2}client.operationPath($path1, c, "${op.name}", $timeout<% if (vars.size()>0) {%>, <%}%>${StringUtil.join(vars,",")}); + } + catch (Exception e) { + ecomplogger.warn(${name}MessageEnum.REMOTE_${op.name}, e.toString()); + throw new RuntimeException("remote call failed: " + client.getRemote() + "@$op.name: " + e); + } + ecomplogger.recordMetricEventEnd(); + ${ret} + } +<% } %> +} diff --git a/ncomp-sirius-manager-generator/src/main/templates/Console.java b/ncomp-sirius-manager-generator/src/main/templates/Console.java new file mode 100644 index 0000000..dfe1648 --- /dev/null +++ b/ncomp-sirius-manager-generator/src/main/templates/Console.java @@ -0,0 +1,97 @@ + +/*- + * ============LICENSE_START========================================== + * OPENECOMP - DCAE + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + */ + +<% +import org.openecomp.ncomp.utils.StringUtil +%>// Autogenerated +// Do not edit but extend this class as needed +package $packageName; + + +import org.apache.log4j.Logger; +import org.eclipse.emf.common.util.EList; + +import org.openecomp.ncomp.sirius.manager.console.Console; +import org.openecomp.ncomp.sirius.manager.AbstractClient; +import org.openecomp.ncomp.sirius.manager.ManagementServerError; + +<% g.subApis.each { api -> + if (api.o.eClass().getEPackage() == o.eClass().getEPackage()) return +%> + +import ${api.packageName()}.${prefix}${api.o.eClass().name}Console; <% } %> + + +public class ${cName} extends Console { + public static final Logger logger = Logger.getLogger(${cName}.class); + protected ${prefix}${name}Client controller; + +<% g.subApis.each { api -> if (api.type == "P") return; %> + ${prefix}${api.o.eClass().name}Console ${api.subName}; <% } %> + + + public ${cName}(String filename, String name) { + super(filename, name); + controller = new ${prefix}${name}Client(filename,name); + client = controller.client; +<% g.subApis.each { api -> if (api.type == "P") return; %> + ${api.subName} = new ${prefix}${api.o.eClass().name}Console(filename,name); <% } %> + } + + public ${cName}(AbstractClient c) { + controller = new ${prefix}${name}Client(c); + client = controller.client; + } + +<% g.operations().each { op -> + def decl = [] + def vars = [] + if (g.root != g && g.root.o.eClass().EPackage == o.eClass().EPackage) { + decl += "String path" + vars += "path" + } + op.getEParameters().each { p -> + if (p.name == "cx") return + vars += p.name + if (p.isMany()) + decl += "EList<${p.getEType().getInstanceClassName()}> $p.name" + else + decl += "${p.getEType().getInstanceClassName()} $p.name" + } + def rType = op.getEType() == null ? "void" : op.getEType().getInstanceClassName() + if (op.isMany()) rType = "EList<$rType>" + def ret = rType == "void" ? "" : "return res;" + def decl1 = rType == "void" ? "" : "$rType res = null;" + def assign = rType == "void" ? "" : "res = " + if (op.getEParameters().find { it.name == "cx" }) vars = ["null"] + vars +%> + public $rType ${op.name}(${StringUtil.join(decl, ", ")}) { + $decl1 + try { + $assign controller.${op.name}(${StringUtil.join(vars,",")}); + } + catch (ManagementServerError e) { + System.err.println("ERROR: " + e.getJson().toString(2)); + } + $ret + } +<% } %> +} diff --git a/ncomp-sirius-manager-generator/src/main/templates/Controller.java b/ncomp-sirius-manager-generator/src/main/templates/Controller.java new file mode 100644 index 0000000..903dde0 --- /dev/null +++ b/ncomp-sirius-manager-generator/src/main/templates/Controller.java @@ -0,0 +1,191 @@ + +/*- + * ============LICENSE_START========================================== + * OPENECOMP - DCAE + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + */ + +<% + + +import org.openecomp.ncomp.component.ApiRequestStatus; +import org.openecomp.ncomp.sirius.manager.ManagementServerError; +import org.openecomp.ncomp.utils.StringUtil +import org.openecomp.ncomp.sirius.manager.server.AbstractManagementServer +import org.openecomp.ncomp.gwt.siriusportal.model.GuiClientApi + +%>// Autogenerated +// Do not edit. No need to extend this class. +package $packageName; + + + + + + +import java.io.InputStream; + +import org.openecomp.ncomp.sirius.manager.IRequestHandler; +import org.openecomp.ncomp.sirius.manager.ISwaggerHandler; +import org.openecomp.ncomp.sirius.manager.ISiriusPlugin; +import org.openecomp.ncomp.sirius.manager.ISiriusServer; +import org.openecomp.ncomp.sirius.manager.ManagementServer; +import org.openecomp.ncomp.sirius.manager.SwaggerUtils; +import org.openecomp.ncomp.sirius.function.FunctionUtils; +import org.openecomp.ncomp.component.ApiRequestStatus; + +import org.apache.log4j.Logger; + +import org.openecomp.logger.EcompLogger; + +import org.eclipse.emf.common.util.EList; +import org.eclipse.emf.ecore.EObject; +import org.json.JSONObject; + +import java.util.Date; + +import ${packageName}.logging.${name}OperationEnum; +import ${packageName}.logging.${name}MessageEnum; + + +<% + def others = [] + switch (o) { + case AbstractManagementServer: + others += "java.util.Date"; + others += "org.openecomp.ncomp.sirius.manager.server.LoggerInfo" + others += "org.openecomp.ncomp.sirius.manager.server.ServerFactory" + break + case GuiClientApi: + others += "org.openecomp.ncomp.sirius.gui.tools.*"; + others += "org.openecomp.ncomp.gwt.siriusportal.model.*"; + others += "org.openecomp.ncomp.sirius.manager.Subject"; + others += "org.openecomp.ncomp.sirius.manager.ManagementServer" + others += "org.openecomp.ncomp.sirius.manager.server.AbstractManagementServer" + break + } + if (g.enableDrools) { + others += "org.openecomp.ncomp.core.logs.*" + others += "org.openecomp.ncomp.sirius.manager.drools.DroolsRuntime" + } + others.each { n -> +%> + + + + +import $n; +<% } %> + +import ${p.nsURI}.impl.${name}Impl; + +<% + def l = [] + if (g.enableIRequestHandler) l += "IRequestHandler" + if (g.enableISwaggerHandler) l += "ISwaggerHandler" + if (g.enableISiriusPlugin) l += "ISiriusPlugin" + def implements1 = l.size() > 0 ? " implements ${StringUtil.join(l,', ')}" : "" +%> + +public class ${cName} extends ${name}Impl${implements1} { + public static final Logger logger = Logger.getLogger(${cName}.class); + static final EcompLogger ecomplogger = EcompLogger.getEcompLogger(); + public ${prefix}${name}Provider controller; + ISiriusServer server; + + public ${cName}(ISiriusServer server) { + this.server = server; + this.controller = new ${prefix}${name}Provider(server,this); + } +<% g.operations().each { op -> + def decl = [] + def vars = [] + op.getEParameters().each { p -> + vars += p.name + if (p.isMany()) + decl += "EList<${p.getEType().getInstanceClassName()}> $p.name" + else + decl += "${p.getEType().getInstanceClassName()} $p.name" + } + def rType = op.getEType() == null ? "void" : op.getEType().getInstanceClassName() + if (op.isMany()) rType = "EList<$rType>" + def ret = rType == "void" ? "" : "return res;" + def decl1 = rType == "void" ? "" : "$rType res = null;" + def assign = rType == "void" ? "" : "res = " + def vars1 = ["duration_"] + vars +%> + public $rType ${op.name}(${StringUtil.join(decl, ", ")}) { + $decl1 + long duration_ = 0; + if (server != null) + server.getServer().recordApi(null, this, "${op.name}", ApiRequestStatus.START, ${StringUtil.join(vars1,",")}); + Date now_ = new Date(); + ecomplogger.recordMetricEventStart(); + ecomplogger.setOperation(${name}OperationEnum.${op.name}); + ecomplogger.setInstanceId(ManagementServer.object2ref(this)); + try { + $assign controller.${op.name}(${StringUtil.join(vars,",")}); + } + catch (Exception e) { + duration_ = new Date().getTime()-now_.getTime(); + if (server != null) + server.getServer().recordApi(null, this, "${op.name}", ApiRequestStatus.ERROR, ${StringUtil.join(vars1,",")}); + System.err.println("ERROR: " + e); + ecomplogger.warn(${name}MessageEnum.${op.name}, e.toString()); + throw e; + } + ecomplogger.recordMetricEventEnd(); + duration_ = new Date().getTime()-now_.getTime(); + if (server != null) + server.getServer().recordApi(null, this, "${op.name}", ApiRequestStatus.OKAY, ${StringUtil.join(vars1,",")}); + $ret + } +<% } %> + +<% if (g.enableIRequestHandler) { %> + @Override + public Object handleJson(String userName, String action, String resourcePath, JSONObject json, JSONObject context) { + return controller.handleJson(userName,action,resourcePath,json,context); + } + + @Override + public Object handleBinary(String userName, String action, String resourcePath, InputStream in) { + return controller.handleBinary(userName,action,resourcePath,in); + } +<% } %> + +<% if (g.enableISwaggerHandler) { %> +@Override +public void updateSwagger(String path, SwaggerUtils swagger) { + controller.updateSwagger(path,swagger); +} +<% } %> + + +<% if (g.enableISiriusPlugin) { %> + @Override + public void start() { + controller.start(); + } +<% } %> + public static void ecoreSetup() { + ${prefix}${name}Provider.ecoreSetup(); + } + public ${prefix}${name}Provider getSomfProvider() { + return controller; + } +} diff --git a/ncomp-sirius-manager-generator/src/main/templates/Factory.java b/ncomp-sirius-manager-generator/src/main/templates/Factory.java new file mode 100644 index 0000000..63344ef --- /dev/null +++ b/ncomp-sirius-manager-generator/src/main/templates/Factory.java @@ -0,0 +1,64 @@ + +/*- + * ============LICENSE_START========================================== + * OPENECOMP - DCAE + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + */ + +// Autogenerated +// Do not edit. No need to extend this class. +package $packageName; + +import org.eclipse.emf.ecore.EPackage; +import org.apache.log4j.Logger; + +import org.openecomp.ncomp.sirius.manager.ISiriusServer; + +import ${p.nsURI}.${name}; +import ${p.nsURI}.${nsPrefix.capitalize()}Package; +import ${p.nsURI}.impl.${fName}Impl; + +<% if (sPackage != "") { %>import ${sPackage}.$sClass; <% } %> + +<% g.subApis.each { api -> +if (api.o.eClass().EPackage != o.eClass().EPackage) return +%> +import ${api.o.eClass().EPackage.nsURI}.${api.o.eClass().name};<% } %> + +public class ${cName} extends ${fName}Impl { + public static final Logger logger = Logger.getLogger(${cName}.class); + ISiriusServer server = null; + @Override + public EPackage getEPackage() { return ${nsPrefix.capitalize()}Package.eINSTANCE; } + public ${cName}(ISiriusServer server) { + this.server = server; + } + @Override + public ${name} create${name}() { + return new ${prefix}${name}(server); + } + +<% g.subApis.each { api -> + if (api.o.eClass().EPackage != o.eClass().EPackage) return +%> + @Override + public ${api.o.eClass().name} create${api.o.eClass().name}() { + return new ${prefix}${api.o.eClass().name}(server); + } +<% } %> + +} diff --git a/ncomp-sirius-manager-generator/src/main/templates/Provider.java b/ncomp-sirius-manager-generator/src/main/templates/Provider.java new file mode 100644 index 0000000..6113401 --- /dev/null +++ b/ncomp-sirius-manager-generator/src/main/templates/Provider.java @@ -0,0 +1,187 @@ + +/*- + * ============LICENSE_START========================================== + * OPENECOMP - DCAE + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + */ + +<% + +import org.openecomp.ncomp.sirius.manager.ManagementServerError; +import org.openecomp.ncomp.utils.StringUtil +import org.openecomp.ncomp.sirius.manager.server.AbstractManagementServer +import org.openecomp.ncomp.gwt.siriusportal.model.GuiClientApi + +%> +package $packageName; + + + + + +import java.io.InputStream; + +import org.openecomp.ncomp.sirius.manager.IRequestHandler; +import org.openecomp.ncomp.sirius.manager.ISiriusPlugin; +import org.openecomp.ncomp.sirius.manager.ISiriusServer; +import org.openecomp.ncomp.sirius.function.FunctionUtils; + +import org.apache.log4j.Logger; +import org.eclipse.emf.common.util.EList; +import org.json.JSONObject; + +<% + def others = [] + def provider = "BasicAdaptorProvider" + switch (o) { + case AbstractManagementServer: + others += "java.util.Date"; + others += "org.openecomp.ncomp.sirius.manager.server.LoggerInfo" + others += "org.openecomp.ncomp.sirius.manager.server.ServerFactory" + provider = "BasicManagementServerProvider" + break + case GuiClientApi: + others += "org.openecomp.ncomp.sirius.gui.tools.*"; + others += "org.openecomp.ncomp.gwt.siriusportal.model.*"; + others += "org.openecomp.ncomp.sirius.manager.Subject"; + others += "org.openecomp.ncomp.sirius.manager.ManagementServer" + others += "org.openecomp.ncomp.sirius.manager.server.AbstractManagementServer" + provider = "BasicGuiClientApiProvider" + break + } + if (g.providerObject != null) { + provider = "$g.providerPrefix${g.providerObject.eClass().name}Provider" + others += "${g.providerPackage}.$provider" + } else { + others += "org.openecomp.ncomp.sirius.manager.${provider}" + } + if (g.enableDrools) { + others += "org.openecomp.ncomp.core.logs.LogLevel" + others += "org.openecomp.ncomp.core.logs.LogMessage" + others += "org.openecomp.ncomp.core.logs.LogSeverity" + others += "org.openecomp.ncomp.core.logs.LogsFactory" + others += "org.openecomp.ncomp.sirius.manager.DroolsEventReporter" + others += "org.openecomp.ncomp.sirius.manager.drools.DroolsRuntime" + } + others.each { n -> +%> + +import $n; +<% } %> + +import ${p.nsURI}.impl.${name}Impl; +import ${p.nsURI}.${name}; + + +public class ${cName} extends ${provider} { + private static final Logger logger = Logger.getLogger(${cName}.class); + ${name} o; + + public ${cName}(ISiriusServer controller, ${name} o) { + super(controller, o); + this.o = o; + } +<% g.operationsProvider().each { op -> + def decl = [] + def vars = [] +// if (g.root != g && g.root.o.eClass().EPackage == o.eClass().EPackage) { +// decl += "String path" +// vars += "path" +// } + op.getEParameters().each { p -> + vars += p.name + if (p.isMany()) + decl += "EList<${p.getEType().getInstanceClassName()}> $p.name" + else + decl += "${p.getEType().getInstanceClassName()} $p.name" + } + def rType = op.getEType() == null ? "void" : op.getEType().getInstanceClassName() + if (op.isMany()) rType = "EList<$rType>" + def ret = rType == "void" ? "" : "return res;" + def decl1 = rType == "void" ? "" : "$rType res = null;" + def assign = rType == "void" ? "" : "res = " + def cx = op.getEParameters().find { it.name == "cx" } ? "null," : "" + def action = "$decl1\n // TODO IMPLEMENT\n throw new UnsupportedOperationException();" + switch (o) { + case AbstractManagementServer: + switch (op.name) { + case "logs": + case "properties": + case "metrics": + case "uploadInfo": + case "getMessages": + case "getValues": + case "getValuesAll": + case "evaluate": + case "getRequestLogger": + case "update": + return + } + break; + case GuiClientApi: + switch (op.name) { + case "getTree": + case "getTable": + case "getTimeSerie": + case "getObject": + case "getHtml": + case "getGraph": + return + } + break; + } + %> + public ${rType} ${op.name}(${StringUtil.join(decl, ", ")}) { + $action + } +<% } %> +<% if (g.enableIRequestHandler) { %> +public Object handleJson(String userName, String action, String resourcePath, JSONObject json, JSONObject context) { + // TODO Auto-generated method stub + return null; + } + + public Object handleBinary(String userName, String action, String resourcePath, InputStream in) { + // TODO Auto-generated method stub + return null; + } +<% } %> + +<% if (g.enableDrools) {%> +DroolsRuntime drools = null; +<% }%> +<% if (g.enableISiriusPlugin) { %> +<% if (g.enableDrools) {%> + public void start() { + try { + // TODO specify rules group, artifact and version + drools = new DroolsRuntime (1000L, "$packageName", "unspecified-rules-artifact", "0.1.0-SNAPSHOT", + new DroolsEventReporter(controller.getServer(), "unknown")); + drools.addObjectTree (o); + drools.startSession(); + drools.startScanner(60000L); + controller.getServer().setDroolsRuntime(drools); +// log("started Drools Session", LogLevel.INFO, LogSeverity.SEV4); + } catch (Exception e) { + e.printStackTrace(); + } + // TODO Auto-generated method stub + } +<% }%> +<% } %> + +} diff --git a/ncomp-sirius-manager-generator/src/main/templates/Server.java b/ncomp-sirius-manager-generator/src/main/templates/Server.java new file mode 100644 index 0000000..638a9ab --- /dev/null +++ b/ncomp-sirius-manager-generator/src/main/templates/Server.java @@ -0,0 +1,135 @@ + +/*- + * ============LICENSE_START========================================== + * OPENECOMP - DCAE + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + */ + +// Autogenerated +// Do not edit but extend this class as needed +package $packageName; + +import static org.openecomp.ncomp.utils.PropertyUtil.getPropertiesFromClasspath; + +import java.io.IOException; +import java.util.Properties; +import java.util.TimeZone; + +import org.apache.log4j.Logger; +import org.eclipse.emf.ecore.EFactory; + +import org.openecomp.entity.EcompComponent; +import org.openecomp.entity.EcompSubComponent; +import org.openecomp.entity.EcompSubComponentInstance; +import org.openecomp.ncomp.sirius.manager.Jetty8Server; +import org.openecomp.ncomp.sirius.manager.ManagementServer; +import org.openecomp.ncomp.sirius.manager.ISiriusServer; + +import ${p.nsURI}.${name}; + +<% g.subApis.each { api -> +if (api.type == "P") return +def n1 = api.subName +if (n1 == null) return +%> +import ${api.packageName()}.${api.m.prefix}${api.factoryName()}; +<% } %> + +<% g.subClients.each { api -> %> +import ${api.o.eClass().EPackage.nsURI}.${api.o.eClass().name}; +import ${api.packageName()}.${prefix}${api.o.eClass().name}Client; +<% } %> + + +public class $cName implements ISiriusServer { + public static final Logger logger = Logger.getLogger(${cName}.class); + String serverPath; + ManagementServer server; + ${prefix}${name} controller; + String directory = "data"; +// LocationControllerApi api ; + Jetty8Server webServer; + ${prefix}${fName} f = new ${prefix}${fName}(this); + +<% g.subApis.each { api -> + if (api.type == "P") return + def n1 = api.subName + if (n1 == null) return +%> + String ${n1}Path; + ManagementServer ${n1}Server; +<% } %> +<% g.subClients.each { api -> %> + ${api.o.eClass().name} $api.clientName; +<% } %> + public ${prefix}${name}Server(String filename) throws IOException { + logger.warn("controller restarting"); + ${prefix}${name}.ecoreSetup(); + props = getPropertiesFromClasspath(filename); + serverPath = (String) props.get("server.dir"); + server = new ManagementServer(f, "${name}", serverPath, filename); + server.addFactory(f); +<% g.factories.each { factory -> + if (g.useNew[factory]) { %> + server.addFactory(new ${factory}(this)); + <% } else { %> + server.addFactory(${factory}.eINSTANCE); + <% } %> +<% } %> + server.addRuntimeFactories(this); + server.start(); + } + public void runWebserver() throws IOException { + controller = (${prefix}${name}) server.find("/").o; + webServer = new Jetty8Server("${nsPrefix}.properties"); + webServer.add("/resources",server); +<% g.aliases.each { %> + webServer.add("$it",controller); +<%}%> + +<% g.subApis.each { api -> + if (api.type == "A" || api.type == "P") return + def n1 = api.subName +%> + EFactory ${n1}Factory = new ${api.m.prefix}${api.factoryName()}(this); + ${n1}Path = serverPath + "/${n1}"; + ${n1}Server = new ManagementServer(${n1}Factory, "${api.o.eClass().name}", ${n1}Path, "${n1}.properties"); + ${n1}Server.start(); + webServer.add("/${n1}",${n1}Server); +<% } %> + +<% g.subClients.each { api -> %> + $api.clientName = new ${prefix}${api.o.eClass().name}Client("${nsPrefix}.properties", "$api.clientName"); +<% } %> + logger.info("Joining webserver"); + webServer.join(); + } + static Properties props = null; + public static void main(String []args) throws IOException { + // ALWAYS USE GMT. + TimeZone.setDefault(TimeZone.getTimeZone("GMT")); + + ${prefix}${name}Server s = new ${prefix}${name}Server("${nsPrefix}.properties"); + s.runWebserver(); + } + public ${name} getController() { + return controller; + } + public ManagementServer getServer() { + return server; + } +} diff --git a/ncomp-sirius-manager-generator/src/main/templates/console b/ncomp-sirius-manager-generator/src/main/templates/console new file mode 100644 index 0000000..decc901 --- /dev/null +++ b/ncomp-sirius-manager-generator/src/main/templates/console @@ -0,0 +1,3 @@ +#!/bin/bash + +LD_LIBRARY_PATH= groovysh -cp config:lib:lib/\* diff --git a/ncomp-sirius-manager-generator/src/main/templates/controller b/ncomp-sirius-manager-generator/src/main/templates/controller new file mode 100644 index 0000000..344ec8f --- /dev/null +++ b/ncomp-sirius-manager-generator/src/main/templates/controller @@ -0,0 +1,140 @@ +#!/bin/bash + +# setup env if needed. java 6 required +## JAVA_HOME= + +############################## DO NOT EDIT BELOW ########################## + +SNAME="$m.prefix Controller" +PNAME=$n-controller +CLASS=${sPackage}.${sClass} + +############################## COMMON BELOW ########################## + +check_status () +{ + if [ -f "\${_PIDFILE}" ]; then + _PID=`cat "\${_PIDFILE}"` + check_status_of_pid \$_PID + else + _STATUS="\$SNAME (no pidfile) is NOT running" + _RUNNING=0 + fi +} + + +check_status_of_pid () +{ + if [ -n "\$1" ] && kill -0 \$1 2>/dev/null ; then + _STATUS="\$SNAME (pid \$1) is running" + _RUNNING=1 + else + _STATUS="\$SNAME (pid \$1) is NOT running" + _RUNNING=0 + fi +} + + +check_status_of_pid () +{ + if [ -n "\$1" ] && kill -0 \$1 2>/dev/null ; then + _STATUS="\$SNAME (pid \$1) is running" + _RUNNING=1 + else + _STATUS="\$SNAME (pid \$1) is NOT running" + _RUNNING=0 + fi +} + +remove_pid_file () +{ + if [ -f "\${_PIDFILE}" ]; then + rm "\${_PIDFILE}" + fi +} + + +_DIR=`dirname "\$0"` +_DIR=`dirname "\$_DIR"` + +_PIDFILE=\$_DIR/PID + +CMD=\$1 +shift + +check_status + +CP=\$(find \$_DIR/lib/*/* -name \\*.jar 2>/dev/null | xargs -I X printf ":%s" X) + +JVMARGS=\$(grep 'server.jvmargs' \$_DIR/config/${nsPrefix}.properties | sed -e 's/.*=//') + +case \$CMD in + status) + echo \$_STATUS + exit 0 + ;; + console) + \$GROOVY_HOME/bin/groovysh -cp \$_DIR/config:\$_DIR/lib:\$_DIR/lib/\\*:\$CP + ;; + run) + \$JAVA_HOME/bin/java -cp \$_DIR/config:\$_DIR/lib:\$_DIR/lib/\\*:\$CP "\$@" + ;; + groovy) + \$GROOVY_HOME/bin/groovy -cp \$_DIR/config:\$_DIR/lib:\$_DIR/lib/\\*:\$CP "\$@" + ;; + start) + if [ "\$_RUNNING" = "1" ]; then + echo \$_STATUS + exit 0 + fi + mkdir -p \$_DIR/logs + if [ -e \$_DIR/logs/\$PNAME.out.1 ]; then mv \$_DIR/logs/\$PNAME.out.1 \$_DIR/logs/\$PNAME.out.2; fi + if [ -e \$_DIR/logs/\$PNAME.err.1 ]; then mv \$_DIR/logs/\$PNAME.err.1 \$_DIR/logs/\$PNAME.err.2; fi + if [ -e \$_DIR/logs/\$PNAME.out ]; then mv \$_DIR/logs/\$PNAME.out \$_DIR/logs/\$PNAME.out.1; fi + if [ -e \$_DIR/logs/\$PNAME.err ]; then mv \$_DIR/logs/\$PNAME.err \$_DIR/logs/\$PNAME.err.1; fi +<% if (g.enableDrools) { %> + nohup \$JAVA_HOME/bin/java \$JVMARGS -Dkie.maven.settings.custom=\$_DIR/config/kie_settings.xml -cp \$_DIR/config:\$_DIR/lib:\$_DIR/lib/\\*:/opt/drools-distribution-6.3.0.Final/binaries/\\*:\$CP "\$@" \$CLASS >> \$_DIR/logs/\$PNAME.out 2>> \$_DIR/logs/\$PNAME.err & +<% } else { %> + nohup \$JAVA_HOME/bin/java \$JVMARGS -cp \$_DIR/config:\$_DIR/lib:\$_DIR/lib/\\*:\$CP "\$@" \$CLASS >> \$_DIR/logs/\$PNAME.out 2>> \$_DIR/logs/\$PNAME.err & +<% } %> + _PID=\$! + echo \$_PID > \$_PIDFILE + sleep 5 + check_status + echo \$_STATUS + if [ "\$_RUNNING" = "1" ]; then + exit 0 + else + echo "Failed to start - make sure the \$SNAME is fully configured properly" + exit 1 + fi + ;; + stop) + if [ "\$_RUNNING" = "0" ]; then + echo \$_STATUS + remove_pid_file + exit 0 + fi + echo "Stopping \$SNAME..." + _PID_TO_KILL=\$_PID; + echo "\$SNAME (pid=\${_PID_TO_KILL}) is stopping..." + kill -TERM \$_PID_TO_KILL + sleep 5 + check_status_of_pid \$_PID_TO_KILL + if [ "\$_RUNNING" = "1" ]; then + kill -TERM \$_PID_TO_KILL + fi + while [ "\$_RUNNING" = "1" ]; do + sleep 2 + check_status_of_pid \$_PID_TO_KILL + done + remove_pid_file + echo "\$SNAME has stopped." + exit 0 + ;; + *) + echo "\$0 start|stop" + ;; +esac + + diff --git a/ncomp-sirius-manager-generator/src/main/templates/xcore b/ncomp-sirius-manager-generator/src/main/templates/xcore new file mode 100644 index 0000000..8d6c1b2 --- /dev/null +++ b/ncomp-sirius-manager-generator/src/main/templates/xcore @@ -0,0 +1,32 @@ +<%
+import org.eclipse.emf.ecore.*;
+%>
+@GenModel(updateClasspath="false")
+package $pName
+
+import org.openecomp.ncomp.sirius.manager.model.NamedEntity
+
+<% p.EClassifiers.each { EClassifier c -> %>
+class $c.name extends NamedEntity {
+ <% c.getEReferences().each { EReference ref -> %>
+ ${ref.isContainment() ? "contains" : "refers"} ${ref.eType.name}${ref.isMany() ? "[]" : ""} $ref.name <% } %>
+ <% c.getEAttributes().each { EAttribute attr ->
+ switch (attr.name) {
+ case "name":
+ case "title":
+ case "description": return
+ }
+ def t = attr.eType.name
+ switch (t) {
+ case "EBoolean": t = "Boolean"; break
+ case "EString": t = "String"; break
+ case "EDouble": t = "Double"; break
+ case "EDate": t = "long"; break
+ }
+ %>
+ ${t}${attr.isMany() ? "[]" : ""} $attr.name <% } %>
+}
+<% } %>
+
+
+
|