Search in sources :

Example 66 with Project

use of com.twinsoft.convertigo.beans.core.Project in project convertigo by convertigo.

the class CLI method main.

public static void main(String[] args) throws Exception {
    Options opts = new Options().addOption(Option.builder("p").longOpt("project").optionalArg(false).argName("dir").hasArg().desc("<dir> set the directory to load as project (default current folder).").build()).addOption(Option.builder("gc").longOpt("gitContainer").optionalArg(true).argName("path").hasArg().desc("git dependencies can be extrated to the <gitContainer> folder instead of defaults.").build()).addOption(Option.builder("g").longOpt("generate").optionalArg(true).argName("mode").hasArg().desc("generate mobilebuilder code into _private/ionic: <mode> can be production (default) or debugplus, debug, fast. If omitted, build mode is used.").build()).addOption(Option.builder("b").longOpt("build").optionalArg(true).argName("mode").hasArg().desc("build generated mobilebuilder code with NPM into DisplayObject/mobile: <mode> can be production (default) or debug. If omitted, generate mode is used.").build()).addOption(Option.builder("c").longOpt("car").desc("export as <projectName>.car file").build()).addOption(Option.builder("icdv").longOpt("installCordova").optionalArg(true).argName("platforms").hasArg().desc("check and install the cordova needed by the project for a specific platform, a list of platform separated by comma, or empty for all.").build()).addOption(Option.builder("iosprof").longOpt("iosProfile").optionalArg(false).argName("provisioningProfile").hasArg().desc("use the specified provisioningProfile for iOS builds.").build()).addOption(Option.builder("iossignid").longOpt("iosSignIdentity").optionalArg(false).argName("signIdentity").hasArg().desc("override default sign identity for ios builds (iPhone Developer / iPhone Distribution).").build()).addOption(Option.builder("andks").longOpt("androidKeystore").optionalArg(false).argName("keystore").hasArg().desc("use the specified keystore for Android builds.").build()).addOption(Option.builder("andkspass").longOpt("androidKeystorePassword").optionalArg(false).argName("keystorePassword").hasArg().desc("use this password to unlock the Android keystore.").build()).addOption(Option.builder("andalias").longOpt("androidAlias").optionalArg(false).argName("alias").hasArg().desc("use this alias to choose the right certificate in the Android keystore.").build()).addOption(Option.builder("andpass").longOpt("androidPassword").optionalArg(false).argName("password").hasArg().desc("use this password to unlock the Android private key.").build()).addOption(Option.builder("cdv").longOpt("cordovaBuild").optionalArg(true).argName("mode").hasArg().desc("perform a cordova build need parameter: debug (default), release, emulator, device.").build()).addOption(Option.builder("mp").longOpt("movePackage").optionalArg(false).argName("dir").hasArg().desc("move native mobile package after a cordova build to the <dir> folder.").build()).addOption(Option.builder("nb").longOpt("nativeBuild").optionalArg(true).argName("platforms").hasArg().desc("perform and download a remote cordova build of the application. Launch build and download for all mobile platforms or add the optional <platforms> parameter with list of plaform separated by coma: Android,IOs.").build()).addOption(Option.builder("lrb").longOpt("launchRemoteBuild").optionalArg(true).argName("platforms").hasArg().desc("perform a remote cordova build of the application. Launch build for all mobile platforms or add the optional <platforms> parameter with list of plaform separated by coma: Android,IOs.").build()).addOption(Option.builder("drb").longOpt("downloadRemoteBuild").optionalArg(true).argName("platforms").hasArg().desc("download a remote cordova build of the application. Download from previous launch, all mobile platforms or add the optional <platforms> parameter with list of plaform separated by coma: Android,IOs.").build()).addOption(Option.builder("noTC").longOpt("excludeTestCases").desc("when export or deploy, do not include TestCases.").build()).addOption(Option.builder("noS").longOpt("excludeStubs").desc("when export or deploy, do not include Stubs.").build()).addOption(Option.builder("noMA").longOpt("excludeMobileApp").desc("when export or deploy, do not include built MobileApp.").build()).addOption(Option.builder("noMAA").longOpt("excludeMobileAppAssets").desc("when export or deploy, do not include built MobileApp assets.").build()).addOption(Option.builder("noDS").longOpt("excludeDataset").desc("when export or deploy, do not include mobile dataset.").build()).addOption(Option.builder("noPA").longOpt("excludePlatformAssets").desc("when export or deploy, do not include mobile platform assets.").build()).addOption(Option.builder("d").longOpt("deploy").optionalArg(false).argName("server").hasArg().desc("deploy the current project to <server> using user/password credentials.").build()).addOption(Option.builder("u").longOpt("user").optionalArg(false).argName("user").hasArg().desc("<user> used by the deploy action, default is 'admin'.").build()).addOption(Option.builder("w").longOpt("password").optionalArg(false).argName("password").hasArg().desc("<password> used by the deploy action, default is 'admin'.").build()).addOption(Option.builder("trust").longOpt("trustAllCertificates").desc("deploy over an https <server> without checking certificates.").build()).addOption(Option.builder("retry").longOpt("deployRetry").desc("deploy will retry <retry> times in case of failure.").build()).addOption(Option.builder("xsl").longOpt("assembleXsl").desc("assemble XSL files on deploy.").build()).addOption(Option.builder("v").longOpt("version").optionalArg(false).argName("version").hasArg().desc("change the 'version' property of the loaded <project>.").build()).addOption(Option.builder("l").longOpt("log").optionalArg(true).argName("level").hasArg().desc("optional <level> (default debug): error, info, warn, debug, trace.").build()).addOption(new Option("h", "help", false, "show this help"));
    CommandLine cmd = new DefaultParser().parse(opts, args, true);
    if (cmd.getOptions().length == 0 || cmd.hasOption("help")) {
        HelpFormatter help = new HelpFormatter();
        help.printHelp("cli", opts);
        return;
    }
    try {
        Level level = Level.OFF;
        if (cmd.hasOption("log")) {
            level = Level.toLevel(cmd.getOptionValue("log", "debug"));
        }
        Logger.getRootLogger().setLevel(level);
        Logger.getLogger("org").setLevel(Level.WARN);
        Logger.getLogger("httpclient").setLevel(Level.WARN);
        File projectDir = new File(cmd.hasOption("project") ? cmd.getOptionValue("project") : ".").getCanonicalFile();
        CLI cli = new CLI();
        String version = cmd.getOptionValue("version", null);
        String mobileApplicationEndpoint = cmd.getOptionValue("mobileApplicationEndpoint", null);
        Project project = cli.loadProject(projectDir, version, mobileApplicationEndpoint, cmd.getOptionValue("gitContainer"));
        String gMode = cmd.getOptionValue("generate", null);
        String bMode = cmd.getOptionValue("build", null);
        if (cmd.hasOption("generate") || cmd.hasOption("build")) {
            if (gMode == null && bMode != null) {
                gMode = bMode;
            }
            cli.generateMobileBuilder(project, gMode);
        }
        if (cmd.hasOption("build")) {
            if (bMode == null) {
                bMode = (gMode == null || gMode.equals("production")) ? "production" : "debug";
            }
            cli.compileMobileBuilder(project, bMode);
        }
        File file = null;
        if (cmd.hasOption("car") || cmd.hasOption("deploy")) {
            cli.export(project);
            File out = new File(projectDir, "build");
            Engine.logConvertigo.info("Building  : " + projectDir);
            file = cli.exportToCar(project, out, !cmd.hasOption("excludeTestCases"), !cmd.hasOption("excludeStubs"), !cmd.hasOption("excludeMobileApp"), !cmd.hasOption("excludeMobileAppAssets"), !cmd.hasOption("excludeDataset"), !cmd.hasOption("excludePlatformAssets"));
            Engine.logConvertigo.info("Built to: " + file);
        }
        if (cmd.hasOption("deploy")) {
            String server = cmd.getOptionValue("deploy");
            String user = cmd.getOptionValue("user", "admin");
            String password = cmd.getOptionValue("password", "admin");
            int retry = Integer.parseInt(cmd.getOptionValue("retry", "5"));
            boolean trustAllCertificates = cmd.hasOption("trust");
            boolean assembleXsl = cmd.hasOption("xsl");
            cli.deploy(file, server, user, password, trustAllCertificates, assembleXsl, retry);
        }
        if (cmd.hasOption("launchRemoteBuild") || cmd.hasOption("remoteBuild")) {
            String opt = cmd.getOptionValue("remoteBuild");
            if (opt == null) {
                opt = cmd.getOptionValue("launchRemoteBuild");
            }
            List<String> platforms = opt == null ? Collections.emptyList() : Arrays.asList(opt.split(","));
            cli.launchRemoteBuild(project, platforms);
        }
        if (cmd.hasOption("downloadRemoteBuild") || cmd.hasOption("remoteBuild")) {
            String opt = cmd.getOptionValue("remoteBuild");
            if (opt == null) {
                opt = cmd.getOptionValue("downloadRemoteBuild");
            }
            List<String> platforms = opt == null ? Collections.emptyList() : Arrays.asList(opt.split(","));
            List<File> files = cli.downloadRemoteBuild(project, platforms, new File(project.getDirFile(), "build"));
            Engine.logConvertigo.info("Downloaded application: " + files);
        }
        Map<String, BuildLocally> localBuilders = null;
        if (cmd.hasOption("icdv") || cmd.hasOption("cdv")) {
            String opt = cmd.getOptionValue("icdv");
            List<String> platforms = opt == null ? Collections.emptyList() : Arrays.asList(opt.split(","));
            localBuilders = cli.installCordova(project, platforms);
        }
        if (cmd.hasOption("iosprof") && cmd.hasOption("cdv")) {
            String provisioningProfile = cmd.getOptionValue("iosprof");
            String signId = cmd.getOptionValue("iossignid");
            cli.configureSignIOS(localBuilders, new File(provisioningProfile), signId);
        }
        if (cmd.hasOption("andks") && cmd.hasOption("cdv")) {
            String keystore = cmd.getOptionValue("andks");
            String keystorePassword = cmd.getOptionValue("andkspass");
            String alias = cmd.getOptionValue("alias");
            String password = cmd.getOptionValue("andpass");
            cli.configureSignAndroid(localBuilders, new File(keystore), keystorePassword, alias, password);
        }
        if (cmd.hasOption("cdv")) {
            String opt = cmd.getOptionValue("cdv");
            cli.cordovaBuild(localBuilders, opt);
        }
        if (cmd.hasOption("mp")) {
            File dir = new File(cmd.getOptionValue("mp"));
            cli.movePackage(localBuilders, dir);
        }
        Engine.logConvertigo.info("Operations terminated!");
    } finally {
    }
}
Also used : BuildLocally(com.twinsoft.convertigo.engine.localbuild.BuildLocally) Options(org.apache.commons.cli.Options) HelpFormatter(org.apache.commons.cli.HelpFormatter) Project(com.twinsoft.convertigo.beans.core.Project) CommandLine(org.apache.commons.cli.CommandLine) Option(org.apache.commons.cli.Option) ArchiveExportOption(com.twinsoft.convertigo.engine.enums.ArchiveExportOption) Level(org.apache.log4j.Level) File(java.io.File) DefaultParser(org.apache.commons.cli.DefaultParser)

Example 67 with Project

use of com.twinsoft.convertigo.beans.core.Project in project convertigo by convertigo.

the class CLI method generateMobileBuilder.

public void generateMobileBuilder(Project project, String mode) throws Exception {
    MobileBuilder mb = project.getMobileBuilder();
    MobileBuilderBuildMode bm = MobileBuilderBuildMode.production;
    try {
        bm = MobileBuilderBuildMode.valueOf(mode);
    } catch (Exception e) {
    }
    mb.setAppBuildMode(bm);
    List<Project> projects = new ArrayList<>();
    projects.add(project);
    int i = 0;
    do {
        for (Reference ref : projects.get(i).getReferenceList()) {
            if (ref instanceof ProjectSchemaReference) {
                ProjectSchemaReference pref = (ProjectSchemaReference) ref;
                Project p = Engine.theApp.referencedProjectManager.importProject(pref.getParser());
                if (p == null) {
                    Engine.logConvertigo.warn("Failed to import project reference: " + pref.getProjectName() + " (ignored)");
                } else if (!projects.contains(p)) {
                    projects.add(p);
                }
            }
        }
    } while (++i < projects.size());
    Collections.reverse(projects);
    for (Project p : projects) {
        MobileBuilder.initBuilder(p, true);
    }
    Collections.reverse(projects);
    for (Project p : projects) {
        MobileBuilder.releaseBuilder(p, true);
    }
}
Also used : Project(com.twinsoft.convertigo.beans.core.Project) ProjectSchemaReference(com.twinsoft.convertigo.beans.references.ProjectSchemaReference) MobileBuilder(com.twinsoft.convertigo.engine.mobile.MobileBuilder) Reference(com.twinsoft.convertigo.beans.core.Reference) ProjectSchemaReference(com.twinsoft.convertigo.beans.references.ProjectSchemaReference) ArrayList(java.util.ArrayList) MobileBuilderBuildMode(com.twinsoft.convertigo.engine.enums.MobileBuilderBuildMode) IOException(java.io.IOException)

Example 68 with Project

use of com.twinsoft.convertigo.beans.core.Project in project convertigo by convertigo.

the class ContextManager method managePoolContexts.

private void managePoolContexts() {
    if (Engine.isStudioMode()) {
        return;
    }
    if (!Engine.isStarted) {
        Engine.logContextManager.debug("Engine is stopped => do not manage pools");
        return;
    }
    Engine.logContextManager.debug("Executing vulture thread for context pooling");
    try {
        long timeout = manage_poll_timeout;
        long now = System.currentTimeMillis();
        if (timeout != -1) {
            timeout += now;
        }
        pooledContextsToCreateSet.clear();
        Map<String, Integer> counters = new HashMap<String, Integer>();
        // with the auto-start transaction
        for (String projectName : Engine.theApp.databaseObjectsManager.getAllProjectNamesList()) {
            if (!isRunning)
                return;
            Engine.logContextManager.trace("Analyzing project " + projectName);
            Project project = null;
            try {
                project = Engine.theApp.databaseObjectsManager.getOriginalProjectByName(projectName);
            } catch (Exception e) {
                Engine.logContextManager.warn("Unable to load project '" + projectName + "'; avorting pool research for this project", e);
                continue;
            }
            Collection<Connector> vConnectors = project.getConnectorsList();
            Engine.logContextManager.trace("Connectors: " + vConnectors);
            for (Connector connector : vConnectors) {
                if (!isRunning)
                    return;
                Engine.logContextManager.trace("Connector: " + connector);
                Collection<Pool> vPools = connector.getPoolsList();
                Engine.logContextManager.trace("Pools: " + vPools);
                String poolName;
                for (Pool pool : vPools) {
                    if (!isRunning)
                        return;
                    poolName = pool.getName();
                    Engine.logContextManager.trace("Pool: " + poolName);
                    int pooledContexts = pool.getNumberOfContexts();
                    Engine.logContextManager.debug("Pool size: " + pooledContexts);
                    String poolNameWithPath = pool.getNameWithPath();
                    pooledContextsInUse = 0;
                    pooledContextsLocked = 0;
                    pooledContextsZombie = 0;
                    pooledContextsToCreate = 0;
                    counters.put(poolNameWithPath, 0);
                    if (pooledContexts > 0) {
                        for (int i = 1; i <= pool.getNumberOfContexts(); i++) {
                            if (!isRunning)
                                return;
                            Project localProject = Engine.theApp.databaseObjectsManager.getOriginalProjectByName(projectName);
                            Connector localConnector = localProject.getConnectorByName(connector.getName());
                            Pool localPool = localConnector.getPoolByName(pool.getName());
                            String servCode = localPool.getServiceCode();
                            if (servCode != null && !servCode.equals("")) {
                                if (localConnector instanceof JavelinConnector) {
                                    ((JavelinConnector) localConnector).setServiceCode(servCode);
                                    Engine.logContextManager.trace("Connector service code overridden to : " + servCode);
                                }
                            // TODO add code for each specific connector to use pools serviceCode property
                            }
                            managePoolContext(localProject, localConnector, localPool, i);
                        }
                        int pooledContextsInUsePercentage = 100 * pooledContextsInUse / pooledContexts;
                        int pooledContextsLockedPercentage = 100 * pooledContextsLocked / pooledContexts;
                        String poolStatistics = "Pool '" + poolNameWithPath + "' usage: pool size: " + pooledContexts + "; in use contexts: " + pooledContextsInUse + " (" + pooledContextsInUsePercentage + "%); zombie contexts: " + pooledContextsZombie;
                        ;
                        if (pooledContextsZombie > 0) {
                            Engine.logContextManager.warn("Pool '" + poolNameWithPath + "' had zombie contexts!");
                            Engine.logContextManager.warn(poolStatistics);
                        }
                        if (pooledContextsInUsePercentage > 80) {
                            Engine.logContextManager.warn("Pool '" + poolNameWithPath + "' is overloaded!");
                            Engine.logContextManager.warn(poolStatistics);
                        }
                        Engine.theApp.usageMonitor.setUsageCounter("[Pool] '" + poolNameWithPath + "' size", pooledContexts);
                        Engine.theApp.usageMonitor.setUsageCounter("[Pool] '" + poolNameWithPath + "' in use contexts", pooledContextsInUse + " (" + pooledContextsInUsePercentage + "%)");
                        Engine.theApp.usageMonitor.setUsageCounter("[Pool] '" + poolNameWithPath + "' locked contexts", pooledContextsLocked + " (" + pooledContextsLockedPercentage + "%)");
                        Engine.theApp.usageMonitor.setUsageCounter("[Pool] '" + poolNameWithPath + "' zombie contexts", pooledContextsZombie);
                        Engine.theApp.usageMonitor.setUsageCounter("[Pool] '" + poolNameWithPath + "' to be created contexts", pooledContextsToCreate);
                    }
                }
            }
        }
        for (Pair<Pool, Integer> pooledContextToCreate : pooledContextsToCreateSet) {
            if (!isRunning)
                return;
            String key = pooledContextToCreate.getKey().getNameWithPath();
            createPoolContext(pooledContextToCreate.getKey(), pooledContextToCreate.getValue());
            counters.put(key, counters.get(key) + 1);
            if (timeout != -1 && (now = System.currentTimeMillis()) > timeout)
                break;
        }
        for (Entry<String, Integer> entry : counters.entrySet()) {
            if (!isRunning)
                return;
            Engine.theApp.usageMonitor.setUsageCounter("[Pool] '" + entry.getKey() + "' (re)created contexts", entry.getValue());
        }
    } catch (EngineException e) {
        Engine.logContextManager.error("An unexpected error has occured in the ContextManager vulture while managing the pool contexts.", e);
    }
    Engine.logContextManager.debug("Pools creation successfully finished");
}
Also used : Connector(com.twinsoft.convertigo.beans.core.Connector) JavelinConnector(com.twinsoft.convertigo.beans.connectors.JavelinConnector) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Project(com.twinsoft.convertigo.beans.core.Project) JavelinConnector(com.twinsoft.convertigo.beans.connectors.JavelinConnector) Pool(com.twinsoft.convertigo.beans.core.Pool) DevicePool(com.twinsoft.util.DevicePool)

Example 69 with Project

use of com.twinsoft.convertigo.beans.core.Project in project convertigo by convertigo.

the class ContextManager method findPoolContext.

private Context findPoolContext(String contextName, String projectName, String connectorName, String poolName) throws EngineException {
    Engine.logContextManager.debug("Trying to find a pooled context");
    Engine.logContextManager.debug("   contextName=" + contextName);
    Engine.logContextManager.debug("   projectName=" + projectName);
    Engine.logContextManager.debug("   connectorName=" + connectorName);
    Engine.logContextManager.debug("   poolName=" + poolName);
    Project project = Engine.theApp.databaseObjectsManager.getOriginalProjectByName(projectName);
    Connector connector;
    if (connectorName == null) {
        connector = project.getDefaultConnector();
        connectorName = connector.getName();
    } else
        connector = project.getConnectorByName(connectorName);
    // If we cannot find the pool, abort the process
    Pool pool = connector.getPoolByName(poolName);
    if (pool == null) {
        Engine.logContextManager.debug("No pool named '" + poolName + "'; aborting pool management");
        return null;
    }
    Engine.logContextManager.debug("Found pool=" + pool);
    pool.checkSymbols();
    String contextIDPrefix = ContextManager.getPoolContextID(projectName, connectorName, poolName, "");
    if (contextName != null && !contextName.equals("default") && !contextName.equals("default*")) {
        Engine.logContextManager.debug("Explicit pooled context '" + contextIDPrefix + contextName + "' has been required");
        Context context = get(contextIDPrefix + contextName);
        if (context == null)
            throw new EngineException("Explicit pooled context '" + contextIDPrefix + contextName + "' does not exist!");
        Engine.logContextManager.debug("context.waitingRequests=" + context.waitingRequests);
        Engine.logContextManager.debug("context.lockPooledContext=" + context.lockPooledContext);
        if (!context.lockPooledContext)
            throw new EngineException("Explicit pooled context '" + contextIDPrefix + contextName + "' has not been locked!");
        Engine.logContextManager.debug("The context has been previously locked and has been explicitely requested");
        return context;
    } else {
        Engine.logContextManager.debug("Searching for good candidate");
        for (Map.Entry<String, Context> entry : contexts.entrySet()) {
            Engine.logContextManager.debug("Analyzing context " + entry.getKey());
            if (entry.getKey().startsWith(contextIDPrefix)) {
                Context context = entry.getValue();
                Engine.logContextManager.debug("context.waitingRequests=" + context.waitingRequests);
                Engine.logContextManager.debug("context.lockPooledContext=" + context.lockPooledContext);
                if ((context.waitingRequests == 0) && (!context.lockPooledContext) && verifyPoolContext(context)) {
                    Engine.logContextManager.debug("Good candidate for election: " + context.contextID);
                    return entry.getValue();
                }
            }
        }
        throw new EngineException("No more available context on the pool " + poolName + "; please try again later.");
    }
}
Also used : Project(com.twinsoft.convertigo.beans.core.Project) Connector(com.twinsoft.convertigo.beans.core.Connector) JavelinConnector(com.twinsoft.convertigo.beans.connectors.JavelinConnector) Pool(com.twinsoft.convertigo.beans.core.Pool) DevicePool(com.twinsoft.util.DevicePool) HashMap(java.util.HashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 70 with Project

use of com.twinsoft.convertigo.beans.core.Project in project convertigo by convertigo.

the class SwaggerUtils method parse.

public static Swagger parse(String requestUrl, UrlMapper urlMapper) {
    Project project = urlMapper.getProject();
    String projectName = project.getName();
    String oasDirUrl = requestUrl.substring(0, requestUrl.indexOf("/" + servletMappingPath)) + "/projects/" + projectName + "/" + jsonSchemaDirectory + "/";
    Swagger swagger = parseCommon(requestUrl, project);
    List<Tag> tags = new ArrayList<Tag>();
    Tag tag = new Tag();
    tag.setName(urlMapper.getProject().getName());
    tag.setDescription(urlMapper.getProject().getComment());
    tags.add(tag);
    swagger.setTags(tags);
    // Security
    Map<String, SecuritySchemeDefinition> securityDefinitions = swagger.getSecurityDefinitions();
    for (UrlAuthentication authentication : urlMapper.getAuthenticationList()) {
        if (AuthenticationType.Basic.equals(authentication.getType())) {
            if (securityDefinitions == null || !securityDefinitions.containsKey("basicAuth")) {
                BasicAuthDefinition basicAuthDefinition = new BasicAuthDefinition();
                swagger.addSecurityDefinition("basicAuth", basicAuthDefinition);
                SecurityRequirement securityRequirement = new SecurityRequirement();
                securityRequirement.requirement("basicAuth", new ArrayList<String>());
                swagger.addSecurity(securityRequirement);
            }
        }
    }
    // Models and Schemas
    Map<String, Model> swagger_models = new HashMap<String, Model>();
    try {
        String models = getModels(oasDirUrl, urlMapper);
        if (!models.isEmpty()) {
            ObjectMapper mapper = Json.mapper();
            JsonNode definitionNode = mapper.readTree(models);
            for (Iterator<Entry<String, JsonNode>> it = GenericUtils.cast(definitionNode.fields()); it.hasNext(); ) {
                Entry<String, JsonNode> entry = it.next();
                swagger_models.put(entry.getKey().toString(), mapper.convertValue(entry.getValue(), Model.class));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        Engine.logEngine.warn("Unexpected exception while reading UrlMapper defined models", e);
    }
    swagger.setDefinitions(swagger_models);
    // Mappings
    Map<String, Path> swagger_paths = new HashMap<String, Path>();
    try {
        for (UrlMapping urlMapping : urlMapper.getMappingList()) {
            Path swagger_path = new Path();
            for (UrlMappingOperation umo : urlMapping.getOperationList()) {
                Operation s_operation = new Operation();
                s_operation.setOperationId(umo.getQName());
                s_operation.setDescription(umo.getComment());
                s_operation.setSummary(umo.getComment());
                // Operation produces
                if (umo instanceof AbstractRestOperation) {
                    DataContent dataOutput = ((AbstractRestOperation) umo).getOutputContent();
                    if (dataOutput.equals(DataContent.toJson)) {
                        s_operation.setProduces(Arrays.asList(MimeType.Json.value()));
                    } else if (dataOutput.equals(DataContent.toXml)) {
                        s_operation.setProduces(Arrays.asList(MimeType.Xml.value()));
                    } else {
                        s_operation.setProduces(Arrays.asList(MimeType.Json.value(), MimeType.Xml.value()));
                    }
                }
                // Operation tags
                List<String> list = Arrays.asList("" + project.getName());
                s_operation.setTags(list);
                // Operation consumes
                List<String> consumes = new ArrayList<String>();
                // Operation parameters
                List<Parameter> s_parameters = new ArrayList<Parameter>();
                // 1 - add path parameters
                for (String pathVarName : urlMapping.getPathVariableNames()) {
                    PathParameter s_parameter = new PathParameter();
                    s_parameter.setName(pathVarName);
                    s_parameter.setRequired(true);
                    s_parameter.setType("string");
                    // retrieve parameter description from bean
                    UrlMappingParameter ump = null;
                    try {
                        ump = umo.getParameterByName(pathVarName);
                    } catch (Exception e) {
                    }
                    if (ump != null && ump.getType() == Type.Path) {
                        s_parameter.setDescription(ump.getComment());
                        s_parameter.setType(ump.getInputType().toLowerCase());
                        Object value = ump.getValueOrNull();
                        if (value != null) {
                            s_parameter.setDefaultValue(String.valueOf(value));
                        }
                    }
                    s_parameters.add(s_parameter);
                }
                // 2 - add other parameters
                for (UrlMappingParameter ump : umo.getParameterList()) {
                    Parameter s_parameter = null;
                    if (ump.getType() == Type.Query) {
                        s_parameter = new QueryParameter();
                    } else if (ump.getType() == Type.Form) {
                        s_parameter = new FormParameter();
                    } else if (ump.getType() == Type.Body) {
                        s_parameter = new BodyParameter();
                        if (ump instanceof IMappingRefModel) {
                            String modelReference = ((IMappingRefModel) ump).getModelReference();
                            if (!modelReference.isEmpty()) {
                                if (modelReference.indexOf(".jsonschema") != -1) {
                                    modelReference = oasDirUrl + modelReference;
                                }
                                RefModel refModel = new RefModel(modelReference);
                                ((BodyParameter) s_parameter).setSchema(refModel);
                            }
                        }
                    } else if (ump.getType() == Type.Header) {
                        s_parameter = new HeaderParameter();
                    } else if (ump.getType() == Type.Path) {
                    // ignore : should have been treated before
                    }
                    if (s_parameter != null) {
                        s_parameter.setName(ump.getName());
                        s_parameter.setDescription(ump.getComment());
                        s_parameter.setRequired(ump.isRequired());
                        if (s_parameter instanceof SerializableParameter) {
                            boolean isArray = ump.isMultiValued() || ump.isArray();
                            String _type = isArray ? "array" : ump.getDataType().name().toLowerCase();
                            String _collectionFormat = ump.isMultiValued() ? "multi" : (isArray ? "csv" : null);
                            Property _items = isArray ? getItems(ump.getDataType()) : null;
                            ((SerializableParameter) s_parameter).setType(_type);
                            ((SerializableParameter) s_parameter).setCollectionFormat(_collectionFormat);
                            ((SerializableParameter) s_parameter).setItems(_items);
                            Object value = ump.getValueOrNull();
                            if (value != null) {
                                String collection = ((SerializableParameter) s_parameter).getCollectionFormat();
                                if (collection != null && collection.equals("multi")) {
                                    Property items = new StringProperty();
                                    // items.setDefault(String.valueOf(value));
                                    ((SerializableParameter) s_parameter).setItems(items);
                                // ((SerializableParameter) s_parameter).setEnumValue(Arrays.asList("val1","val2","val3"));
                                } else {
                                    ((AbstractSerializableParameter<?>) s_parameter).setDefaultValue(String.valueOf(value));
                                }
                            }
                        }
                        DataContent dataInput = ump.getInputContent();
                        if (dataInput.equals(DataContent.toJson)) {
                            if (!consumes.contains(MimeType.Json.value())) {
                                consumes.add(MimeType.Json.value());
                            }
                        } else if (dataInput.equals(DataContent.toXml)) {
                            if (!consumes.contains(MimeType.Xml.value())) {
                                consumes.add(MimeType.Xml.value());
                            }
                        }
                        // swagger-ui workaround for invalid request content-type for POST
                        if (ump.getType() == Type.Form) {
                            if (!DataType.File.equals(ump.getDataType())) {
                                if (!consumes.contains(MimeType.WwwForm.value())) {
                                    consumes.add(MimeType.WwwForm.value());
                                }
                            } else {
                                if (!consumes.contains("multipart/form-data")) {
                                    consumes.add("multipart/form-data");
                                }
                            }
                        }
                        // add parameter
                        if (ump.isExposed()) {
                            s_parameters.add(s_parameter);
                        }
                    }
                }
                s_operation.setParameters(s_parameters);
                if (!consumes.isEmpty()) {
                    s_operation.setConsumes(consumes);
                }
                // Set operation responses
                Map<String, Response> responses = new HashMap<String, Response>();
                for (UrlMappingResponse umr : umo.getResponseList()) {
                    String statusCode = umr.getStatusCode();
                    if (!statusCode.isEmpty()) {
                        if (!responses.containsKey(statusCode)) {
                            Response response = new Response();
                            // response.setDescription(umr.getComment());
                            response.setDescription(umr.getStatusText());
                            if (umr instanceof IMappingRefModel) {
                                String modelReference = ((IMappingRefModel) umr).getModelReference();
                                if (!modelReference.isEmpty()) {
                                    if (modelReference.indexOf(".jsonschema") != -1) {
                                        modelReference = oasDirUrl + modelReference;
                                    }
                                    RefProperty refProperty = new RefProperty(modelReference);
                                    response.setResponseSchema(new PropertyModelConverter().propertyToModel(refProperty));
                                }
                            }
                            responses.put(statusCode, response);
                        }
                    }
                }
                if (responses.isEmpty()) {
                    Response resp200 = new Response();
                    resp200.description("successful operation");
                    responses.put("200", resp200);
                }
                s_operation.setResponses(responses);
                // Add operation to path
                String s_method = umo.getMethod().toLowerCase();
                swagger_path.set(s_method, s_operation);
            }
            swagger_paths.put(urlMapping.getPathWithPrefix(), swagger_path);
        }
    } catch (Exception e) {
        e.printStackTrace();
        Engine.logEngine.error("Unexpected exception while parsing UrlMapper to generate definition", e);
    }
    swagger.setPaths(swagger_paths);
    return swagger;
}
Also used : UrlMapping(com.twinsoft.convertigo.beans.core.UrlMapping) SerializableParameter(io.swagger.models.parameters.SerializableParameter) AbstractSerializableParameter(io.swagger.models.parameters.AbstractSerializableParameter) AbstractRestOperation(com.twinsoft.convertigo.beans.rest.AbstractRestOperation) RefModel(io.swagger.models.RefModel) IMappingRefModel(com.twinsoft.convertigo.beans.core.IMappingRefModel) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) JsonNode(com.fasterxml.jackson.databind.JsonNode) AbstractSerializableParameter(io.swagger.models.parameters.AbstractSerializableParameter) PropertyModelConverter(io.swagger.models.utils.PropertyModelConverter) DataContent(com.twinsoft.convertigo.beans.core.UrlMappingParameter.DataContent) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Project(com.twinsoft.convertigo.beans.core.Project) JSONObject(org.codehaus.jettison.json.JSONObject) IMappingRefModel(com.twinsoft.convertigo.beans.core.IMappingRefModel) QueryParameter(io.swagger.models.parameters.QueryParameter) UrlMappingParameter(com.twinsoft.convertigo.beans.core.UrlMappingParameter) UrlMappingResponse(com.twinsoft.convertigo.beans.core.UrlMappingResponse) StringProperty(io.swagger.models.properties.StringProperty) Operation(io.swagger.models.Operation) AbstractRestOperation(com.twinsoft.convertigo.beans.rest.AbstractRestOperation) UrlMappingOperation(com.twinsoft.convertigo.beans.core.UrlMappingOperation) BodyParameter(io.swagger.models.parameters.BodyParameter) PathParameter(io.swagger.models.parameters.PathParameter) FormParameter(io.swagger.models.parameters.FormParameter) RefProperty(io.swagger.models.properties.RefProperty) Entry(java.util.Map.Entry) Swagger(io.swagger.models.Swagger) HeaderParameter(io.swagger.models.parameters.HeaderParameter) StringProperty(io.swagger.models.properties.StringProperty) Property(io.swagger.models.properties.Property) DoubleProperty(io.swagger.models.properties.DoubleProperty) RefProperty(io.swagger.models.properties.RefProperty) IntegerProperty(io.swagger.models.properties.IntegerProperty) BooleanProperty(io.swagger.models.properties.BooleanProperty) Path(io.swagger.models.Path) UrlMappingOperation(com.twinsoft.convertigo.beans.core.UrlMappingOperation) SecuritySchemeDefinition(io.swagger.models.auth.SecuritySchemeDefinition) BasicAuthDefinition(io.swagger.models.auth.BasicAuthDefinition) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Response(io.swagger.models.Response) UrlMappingResponse(com.twinsoft.convertigo.beans.core.UrlMappingResponse) Model(io.swagger.models.Model) RefModel(io.swagger.models.RefModel) IMappingRefModel(com.twinsoft.convertigo.beans.core.IMappingRefModel) SerializableParameter(io.swagger.models.parameters.SerializableParameter) FormParameter(io.swagger.models.parameters.FormParameter) PathParameter(io.swagger.models.parameters.PathParameter) Parameter(io.swagger.models.parameters.Parameter) QueryParameter(io.swagger.models.parameters.QueryParameter) AbstractSerializableParameter(io.swagger.models.parameters.AbstractSerializableParameter) HeaderParameter(io.swagger.models.parameters.HeaderParameter) BodyParameter(io.swagger.models.parameters.BodyParameter) UrlMappingParameter(com.twinsoft.convertigo.beans.core.UrlMappingParameter) Tag(io.swagger.models.Tag) UrlAuthentication(com.twinsoft.convertigo.beans.core.UrlAuthentication) SecurityRequirement(io.swagger.models.SecurityRequirement)

Aggregations

Project (com.twinsoft.convertigo.beans.core.Project)148 EngineException (com.twinsoft.convertigo.engine.EngineException)56 DatabaseObject (com.twinsoft.convertigo.beans.core.DatabaseObject)47 IOException (java.io.IOException)39 File (java.io.File)37 Sequence (com.twinsoft.convertigo.beans.core.Sequence)35 Connector (com.twinsoft.convertigo.beans.core.Connector)33 ArrayList (java.util.ArrayList)29 ProjectExplorerView (com.twinsoft.convertigo.eclipse.views.projectexplorer.ProjectExplorerView)26 JSONException (org.codehaus.jettison.json.JSONException)26 Transaction (com.twinsoft.convertigo.beans.core.Transaction)24 TreeObject (com.twinsoft.convertigo.eclipse.views.projectexplorer.model.TreeObject)22 SAXException (org.xml.sax.SAXException)21 CoreException (org.eclipse.core.runtime.CoreException)20 Step (com.twinsoft.convertigo.beans.core.Step)19 Element (org.w3c.dom.Element)19 Shell (org.eclipse.swt.widgets.Shell)18 JSONObject (org.codehaus.jettison.json.JSONObject)17 IProject (org.eclipse.core.resources.IProject)17 Cursor (org.eclipse.swt.graphics.Cursor)17