<commit_before>/**
 * Copyright 2005-2015 Red Hat, Inc.
 * <p/>
 * Red Hat licenses this file to you 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
 * <p/>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p/>
 * 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.
 */
package org.jboss.forge.addon.springboot;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.jboss.forge.addon.dependencies.builder.DependencyBuilder;
import org.jboss.forge.addon.projects.Project;
import org.jboss.forge.addon.projects.dependencies.DependencyInstaller;
import org.jboss.forge.addon.projects.facets.MetadataFacet;
import org.jboss.forge.addon.resource.DirectoryResource;
import org.jboss.forge.addon.springboot.dto.SpringBootDependencyDTO;
import org.jboss.forge.addon.ui.context.UIBuilder;
import org.jboss.forge.addon.ui.context.UIContext;
import org.jboss.forge.addon.ui.context.UIExecutionContext;
import org.jboss.forge.addon.ui.input.UISelectMany;
import org.jboss.forge.addon.ui.input.UISelectOne;
import org.jboss.forge.addon.ui.metadata.UICommandMetadata;
import org.jboss.forge.addon.ui.metadata.WithAttributes;
import org.jboss.forge.addon.ui.result.Result;
import org.jboss.forge.addon.ui.result.Results;
import org.jboss.forge.addon.ui.util.Categories;
import org.jboss.forge.addon.ui.util.Commands;
import org.jboss.forge.addon.ui.util.Metadata;
import org.jboss.forge.furnace.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.Yaml;

import static org.jboss.forge.addon.maven.archetype.ArchetypeHelper.recursiveDelete;
import static org.jboss.forge.addon.springboot.IOHelper.close;
import static org.jboss.forge.addon.springboot.IOHelper.copyAndCloseInput;
import static org.jboss.forge.addon.springboot.OkHttpClientHelper.createOkHttpClient;
import static org.jboss.forge.addon.springboot.UnzipHelper.unzip;

public class SpringBootNewProjectCommand extends AbstractSpringBootCommand {

    private static final transient Logger LOG = LoggerFactory.getLogger(SpringBootNewProjectCommand.class);

    // lets use a different category for this command
    private static final String CATEGORY = "Spring Boot";

    private static final String SPRING_BOOT_DEFAULT_VERSION = "1.4.3";
    private static final String[] SPRING_BOOT_VERSIONS = new String[]{"1.3.8", "1.4.3"};

    private static final String STARTER_URL = "https://start.spring.io/starter.zip";

    // fabric8 only dependencies which we should not pass on to start.spring.io
    private static final String[] fabric8Deps = new String[]{"spring-cloud-kubernetes", "kubeflix-ribbon-discovery",
            "kubeflix-turbine-discovery", "kubeflix-turbine-server", "camel-zipkin-starter"};

    @Inject
    @WithAttributes(label = "Spring Boot Version", required = true, description = "Spring Boot Version to use")
    private UISelectOne<String> springBootVersion;

    private List<SpringBootDependencyDTO> choices;

    @Inject
    @WithAttributes(label = "Dependencies", required = true, description = "Add Spring Boot Starters and dependencies to your application")
    private UISelectMany<SpringBootDependencyDTO> dependencies;

    @Inject
    private DependencyInstaller dependencyInstaller;

    @Override
    public void initializeUI(UIBuilder builder) throws Exception {
        springBootVersion.setValueChoices(Arrays.asList(SPRING_BOOT_VERSIONS));
        springBootVersion.setDefaultValue(SPRING_BOOT_DEFAULT_VERSION);

        try {
            choices = initDependencies();
        } catch (Exception e) {
            e.printStackTrace();
            throw new IllegalStateException("Error loading dependencies from spring-boot-application.yaml due: " + e.getMessage(), e);
        }

        dependencies.setValueChoices(choices);
        if (builder.getUIContext().getProvider().isGUI()) {
            dependencies.setItemLabelConverter(SpringBootDependencyDTO::getGroupAndName);
        } else {
            // if in CLI mode then use shorter names so they are tab friendly in the shell
            dependencies.setItemLabelConverter(dto -> Commands.shellifyCommandName(dto.getName()));
        }

        dependencies.setValueConverter(s -> {
            for (SpringBootDependencyDTO dto : choices) {
                if (dto.getId().equals(s)) {
                    return dto;
                }
            }
            return null;
        });

        builder.add(springBootVersion).add(dependencies);
    }

    private List<SpringBootDependencyDTO> initDependencies() {
        List<SpringBootDependencyDTO> list = new ArrayList<>();

        Yaml yaml = new Yaml();
        // load the application.yaml file from the spring-boot initializr project and parse it
        // and grab all the dependencies it has so we have those as choices
        InputStream input = SpringBootNewProjectCommand.class.getResourceAsStream("/spring-boot-application.yaml");
        Map data = (Map) yaml.load(input);

        Map initializer = (Map) data.get("initializr");
        List deps = (List) initializer.get("dependencies");
        for (Object dep : deps) {
            Map group = (Map) dep;
            String groupName = (String) group.get("name");
            List content = (List) group.get("content");
            for (Object row : content) {
                Map item = (Map) row;
                String id = (String) item.get("id");
                String name = (String) item.get("name");
                String description = (String) item.get("description");
                list.add(new SpringBootDependencyDTO(groupName, id, name, description));

                // are we at apache camel, then inject other Camel modules that are not in the spring-boot-application yet
/*                if ("camel".equals(id)) {
                    SpringBootDependencyDTO dto = new SpringBootDependencyDTO(groupName, "camel-zipkin-starter", "Apache Camel Zipkin", "Distributed tracing with an existing Zipkin installation with Apache Camel.");
                    String version = SpringBootVersionHelper.getVersion("camel.version");
                    dto.setMavenCoord("org.apache.camel", "camel-zipkin", version);
                    list.add(dto);
                }*/
            }
        }

        // and then add the fabric8 group
        String version = SpringBootVersionHelper.getVersion("fabric8.spring.cloud.kubernetes.version");
        SpringBootDependencyDTO dto = new SpringBootDependencyDTO("Fabric8", "spring-cloud-kubernetes", "Spring Cloud Kubernetes", "Kubernetes integration with Spring Cloud");
        dto.setMavenCoord("io.fabric8", "spring-cloud-starter-kubernetes-all", version);
        list.add(dto);

        return list;
    }

    @Override
    protected boolean isProjectRequired() {
        return false;
    }

    @Override
    public UICommandMetadata getMetadata(UIContext context) {
        return Metadata.from(super.getMetadata(context), getClass())
                .category(Categories.create(CATEGORY))
                .name(CATEGORY + ": New Project")
                .description("Create a new Spring Boot project");
    }

    @Override
    public Result execute(UIExecutionContext context) throws Exception {
        UIContext uiContext = context.getUIContext();<commit_msg>Comment line with Camel + Fabric8 hard coded deps<commit_after>/**
 * Copyright 2005-2015 Red Hat, Inc.
 * <p/>
 * Red Hat licenses this file to you 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
 * <p/>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p/>
 * 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.
 */
package org.jboss.forge.addon.springboot;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.jboss.forge.addon.dependencies.builder.DependencyBuilder;
import org.jboss.forge.addon.projects.Project;
import org.jboss.forge.addon.projects.dependencies.DependencyInstaller;
import org.jboss.forge.addon.projects.facets.MetadataFacet;
import org.jboss.forge.addon.resource.DirectoryResource;
import org.jboss.forge.addon.springboot.dto.SpringBootDependencyDTO;
import org.jboss.forge.addon.ui.context.UIBuilder;
import org.jboss.forge.addon.ui.context.UIContext;
import org.jboss.forge.addon.ui.context.UIExecutionContext;
import org.jboss.forge.addon.ui.input.UISelectMany;
import org.jboss.forge.addon.ui.input.UISelectOne;
import org.jboss.forge.addon.ui.metadata.UICommandMetadata;
import org.jboss.forge.addon.ui.metadata.WithAttributes;
import org.jboss.forge.addon.ui.result.Result;
import org.jboss.forge.addon.ui.result.Results;
import org.jboss.forge.addon.ui.util.Categories;
import org.jboss.forge.addon.ui.util.Commands;
import org.jboss.forge.addon.ui.util.Metadata;
import org.jboss.forge.furnace.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.Yaml;

import static org.jboss.forge.addon.maven.archetype.ArchetypeHelper.recursiveDelete;
import static org.jboss.forge.addon.springboot.IOHelper.close;
import static org.jboss.forge.addon.springboot.IOHelper.copyAndCloseInput;
import static org.jboss.forge.addon.springboot.OkHttpClientHelper.createOkHttpClient;
import static org.jboss.forge.addon.springboot.UnzipHelper.unzip;

public class SpringBootNewProjectCommand extends AbstractSpringBootCommand {

    private static final transient Logger LOG = LoggerFactory.getLogger(SpringBootNewProjectCommand.class);

    // lets use a different category for this command
    private static final String CATEGORY = "Spring Boot";

    private static final String SPRING_BOOT_DEFAULT_VERSION = "1.4.3";
    private static final String[] SPRING_BOOT_VERSIONS = new String[]{"1.3.8", "1.4.3"};

    private static final String STARTER_URL = "https://start.spring.io/starter.zip";

    // fabric8 only dependencies which we should not pass on to start.spring.io
    private static final String[] fabric8Deps = new String[]{"spring-cloud-kubernetes", "kubeflix-ribbon-discovery",
            "kubeflix-turbine-discovery", "kubeflix-turbine-server", "camel-zipkin-starter"};

    @Inject
    @WithAttributes(label = "Spring Boot Version", required = true, description = "Spring Boot Version to use")
    private UISelectOne<String> springBootVersion;

    private List<SpringBootDependencyDTO> choices;

    @Inject
    @WithAttributes(label = "Dependencies", required = true, description = "Add Spring Boot Starters and dependencies to your application")
    private UISelectMany<SpringBootDependencyDTO> dependencies;

    @Inject
    private DependencyInstaller dependencyInstaller;

    @Override
    public void initializeUI(UIBuilder builder) throws Exception {
        springBootVersion.setValueChoices(Arrays.asList(SPRING_BOOT_VERSIONS));
        springBootVersion.setDefaultValue(SPRING_BOOT_DEFAULT_VERSION);

        try {
            choices = initDependencies();
        } catch (Exception e) {
            e.printStackTrace();
            throw new IllegalStateException("Error loading dependencies from spring-boot-application.yaml due: " + e.getMessage(), e);
        }

        dependencies.setValueChoices(choices);
        if (builder.getUIContext().getProvider().isGUI()) {
            dependencies.setItemLabelConverter(SpringBootDependencyDTO::getGroupAndName);
        } else {
            // if in CLI mode then use shorter names so they are tab friendly in the shell
            dependencies.setItemLabelConverter(dto -> Commands.shellifyCommandName(dto.getName()));
        }

        dependencies.setValueConverter(s -> {
            for (SpringBootDependencyDTO dto : choices) {
                if (dto.getId().equals(s)) {
                    return dto;
                }
            }
            return null;
        });

        builder.add(springBootVersion).add(dependencies);
    }

    private List<SpringBootDependencyDTO> initDependencies() {
        List<SpringBootDependencyDTO> list = new ArrayList<>();

        Yaml yaml = new Yaml();
        // load the application.yaml file from the spring-boot initializr project and parse it
        // and grab all the dependencies it has so we have those as choices
        InputStream input = SpringBootNewProjectCommand.class.getResourceAsStream("/spring-boot-application.yaml");
        Map data = (Map) yaml.load(input);

        Map initializer = (Map) data.get("initializr");
        List deps = (List) initializer.get("dependencies");
        for (Object dep : deps) {
            Map group = (Map) dep;
            String groupName = (String) group.get("name");
            List content = (List) group.get("content");
            for (Object row : content) {
                Map item = (Map) row;
                String id = (String) item.get("id");
                String name = (String) item.get("name");
                String description = (String) item.get("description");
                list.add(new SpringBootDependencyDTO(groupName, id, name, description));

                // are we at apache camel, then inject other Camel modules that are not in the spring-boot-application yet
                // TODO - Check with F8 how we will manage that
                /*
                if ("camel".equals(id)) {
                    SpringBootDependencyDTO dto = new SpringBootDependencyDTO(groupName, "camel-zipkin-starter", "Apache Camel Zipkin", "Distributed tracing with an existing Zipkin installation with Apache Camel.");
                    String version = SpringBootVersionHelper.getVersion("camel.version");
                    dto.setMavenCoord("org.apache.camel", "camel-zipkin", version);
                    list.add(dto);
                }*/
            }
        }

        // and then add the fabric8 group
        // TODO - Check with F8 how we will manage that
        /*
        String version = SpringBootVersionHelper.getVersion("fabric8.spring.cloud.kubernetes.version");
        SpringBootDependencyDTO dto = new SpringBootDependencyDTO("Fabric8", "spring-cloud-kubernetes", "Spring Cloud Kubernetes", "Kubernetes integration with Spring Cloud");
        dto.setMavenCoord("io.fabric8", "spring-cloud-starter-kubernetes-all", version);
        list.add(dto);
        */

        return list;
    }

    @Override
    protected boolean isProjectRequired() {
        return false;
    }

    @Override
    public UICommandMetadata getMetadata(UIContext context) {
        return Metadata.from(super.getMetadata(context), getClass())
                .category(Categories.create(CATEGORY))
                .name(CATEGORY + ": New Project")
                .description("Create a new Spring Boot project");
    }

    @Override
    public Result execute(UIExecutionContext context) throws Exception {
        UIContext uiContext = context.getUIContext();
{'fraction_non_alphanumeric': 0.10016871836530651, 'fraction_numerical': 0.004186714990939199, 'mean_word_length': 3.2226912928759894, 'pattern_counts': {'":': 2, '<': 21, '<?xml version=': 0, '>': 25, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3959776', 'n_tokens_mistral': 4606, 'n_tokens_neox': 4392, 'n_words': 1118}