Search in sources :

Example 21 with Filter

use of io.fabric8.common.util.Filter in project fabric8 by jboss-fuse.

the class ArchetypeGenerateAction method doExecute.

@Override
protected Object doExecute() throws Exception {
    // if no directory then use workspace
    if (directory == null) {
        // must have a workspace location configured
        Preferences preferences = Preferences.userNodeForPackage(getClass());
        String location = preferences.get(ArchetypeWorkspace.PREFERENCE_WORKSPACE, null);
        if (location == null) {
            System.out.println("No workspace location has been set.");
            System.out.println("Use the archetype-workspace command to set a workspace first.");
            System.out.println("");
            return null;
        } else {
            System.out.println("Using current workspace: " + location);
            directory = location;
        }
    } else {
        System.out.println("Using directory as workspace: " + directory);
    }
    File target = new File(directory);
    // make sure the directory exists, auto-creating if missing
    if (!target.exists()) {
        target.mkdirs();
    }
    if (!target.exists() || !target.isDirectory()) {
        System.err.println("Workspace does not exists or is not a directory: " + directory);
        return null;
    }
    Archetype archetype = null;
    // try artifact first
    if (!isNullOrBlank(archetypeOrFilter)) {
        archetype = archetypeService.getArchetypeByArtifact(archetypeOrFilter);
        if (archetype == null) {
            // then by coordinate
            archetype = archetypeService.getArchetype(archetypeOrFilter);
        }
    }
    // no archetype yet so present a list where the user can select
    while (archetype == null) {
        List<Archetype> archetypes = archetypeService.listArchetypes(archetypeOrFilter, true);
        System.out.println("Choose archetype:");
        Iterator<Archetype> it = archetypes.iterator();
        int i = 0;
        while (it.hasNext()) {
            Archetype select = it.next();
            System.out.println(String.format("%4d: -> %-50s %s", ++i, select.artifactId, select.description));
        }
        boolean choosing = true;
        while (choosing) {
            // default select last
            String choose = ShellUtils.readLine(session, String.format("Choose a number or apply filter (case insensitive): %d: ", i), false);
            if (Strings.isNullOrBlank(choose)) {
                // user pressed enter so we select the last
                choose = "" + i;
            }
            try {
                int no = Integer.valueOf(choose);
                // is the number within range
                if (no >= 1 && no <= archetypes.size()) {
                    archetype = archetypes.get(no - 1);
                    break;
                } else {
                    System.out.println("Number " + no + " out of range. Please try again!");
                    continue;
                }
            } catch (NumberFormatException e) {
                // no its a filter, so we use this as filter, and show the list again
                archetypeOrFilter = choose;
                choosing = false;
                archetype = null;
            }
        }
    }
    // okay we have selected an archetype now
    File archetypeFile = fetchArchetype(archetype);
    if (archetypeFile == null || !archetypeFile.exists()) {
        System.err.println("No archetype found for \"" + archetypeOrFilter + "\" coordinates");
        return null;
    }
    System.out.println("----------------------------------------------------------------------------");
    System.out.println("Using archetype: " + archetype.artifactId);
    String defaultGroupId = "io.fabric8";
    String defaultArtifactId = archetype.artifactId + "-example";
    String defaultVersion = "1.0-SNAPSHOT";
    String defaultName = archetype.name;
    String defaultDescription = isNotBlank(archetype.description) ? archetype.description : "";
    System.out.println("----- Configure archetype -----");
    String groupId = ShellUtils.readLine(session, String.format("Define value for property 'groupId' (%s): ", defaultGroupId), false);
    String artifactId = ShellUtils.readLine(session, String.format("Define value for property 'artifactId' (%s): ", defaultArtifactId), false);
    String version = ShellUtils.readLine(session, String.format("Define value for property 'version' (%s): ", defaultVersion), false);
    groupId = isNullOrBlank(groupId) ? defaultGroupId : groupId;
    artifactId = isNullOrBlank(artifactId) ? defaultArtifactId : artifactId;
    version = isNullOrBlank(version) ? defaultVersion : version;
    String defaultPackageName = (groupId + "." + artifactId).replaceAll("-", ".");
    String packageName = ShellUtils.readLine(session, String.format("Define value for property 'package' (%s): ", defaultPackageName), false);
    // use artifact id as default directory name (maven does this also)
    String defaultDirectoryName = isNullOrBlank(artifactId) ? defaultArtifactId : artifactId;
    directory = ShellUtils.readLine(session, String.format("Define value for property 'directoryName' (%s): ", defaultDirectoryName), false);
    packageName = isNullOrBlank(packageName) ? defaultPackageName : packageName;
    directory = isNullOrBlank(directory) ? artifactId : directory;
    String name = ShellUtils.readLine(session, String.format("Define value for property 'name' (%s): ", defaultName), false);
    String description = ShellUtils.readLine(session, String.format("Define value for property 'description' (%s): ", defaultDescription), false);
    // use null to indicate we want out of the box description
    name = isNullOrBlank(name) ? null : name;
    description = isNullOrBlank(description) ? null : description;
    File childDir = new File(target, directory);
    ArchetypeHelper helper = new ArchetypeHelper(archetypeFile, childDir, groupId, artifactId, version, name, description);
    helper.setPackageName(packageName);
    Map<String, String> properties = helper.parseProperties();
    // if we have fabric8.profile as a property then lets configured it now, as its mandatory
    // and use artifactId as its default suggested value
    String profile = null;
    if (properties.containsKey("fabric8-profile")) {
        profile = properties.remove("fabric8-profile");
        String defaultProfile = isNullOrBlank(profile) ? artifactId : profile;
        String p = ShellUtils.readLine(session, String.format("Define value for property 'fabric8.profile' (%s): ", defaultProfile), false);
        profile = isNullOrBlank(p) ? defaultProfile : p;
    }
    // show additional properties and ask to use them as-is
    boolean mustChoose = false;
    if (!properties.isEmpty()) {
        // check if we must choose if there is an empty value or a value that has a ${ } token so we dont have a default value
        for (String value : properties.values()) {
            if (isNullOrBlank(value) || value.contains("$")) {
                mustChoose = true;
                break;
            }
        }
        if (!mustChoose) {
            System.out.println("----- Additional properties -----");
            for (String key : properties.keySet()) {
                System.out.println(String.format("Using property '%s' (%s): ", key, properties.get(key)));
            }
        }
        boolean choosing = true;
        while (mustChoose || choosing) {
            String confirm = null;
            if (!mustChoose) {
                confirm = ShellUtils.readLine(session, "Confirm additional properties configuration: (Y): ", false);
                confirm = isNullOrBlank(confirm) ? "Y" : confirm;
            }
            if (mustChoose || !"Y".equalsIgnoreCase(confirm)) {
                // ask for replacement properties suggesting the defaults
                if (!properties.isEmpty()) {
                    System.out.println("----- Configure additional properties -----");
                    for (String key : properties.keySet()) {
                        String value = properties.get(key);
                        // if the value is empty or a token, then do not show any default value
                        if (isNullOrBlank(value) || value.contains("$")) {
                            value = "";
                        }
                        String p = ShellUtils.readLine(session, String.format("Define value for property '%s' (%s): ", key, value), false);
                        p = isNullOrBlank(p) ? value : p;
                        properties.put(key, p);
                    }
                }
                mustChoose = false;
            } else {
                choosing = false;
            }
        }
    }
    // remover to include the profile back into properties
    if (profile != null) {
        properties.put("fabric8-profile", profile);
    }
    if (!properties.isEmpty()) {
        // set override properties
        helper.setOverrideProperties(properties);
    }
    String confirm = ShellUtils.readLine(session, "Create project: (Y): ", false);
    confirm = confirm == null || confirm.trim().equals("") ? "Y" : confirm;
    if ("Y".equalsIgnoreCase(confirm)) {
        System.out.println("----------------------------------------------------------------------------");
        System.out.println(String.format("Creating project in directory: %s", childDir.getCanonicalPath()));
        helper.execute();
        System.out.println("Project created successfully");
        System.out.println("");
    } else {
        System.out.println("----------------------------------------------------------------------------");
        System.out.println("Creating project aborted!");
        System.out.println("");
    }
    return null;
}
Also used : Archetype(io.fabric8.tooling.archetype.catalog.Archetype) ArchetypeHelper(io.fabric8.tooling.archetype.generator.ArchetypeHelper) Preferences(java.util.prefs.Preferences) File(java.io.File)

Example 22 with Filter

use of io.fabric8.common.util.Filter in project halyard by spinnaker.

the class LocalDebianServiceProvider method getInstallCommand.

@Override
public String getInstallCommand(DeploymentDetails deploymentDetails, GenerateService.ResolvedConfiguration resolvedConfiguration, Map<String, String> installCommands) {
    Map<String, Object> bindings = new HashMap<>();
    List<SpinnakerService.Type> serviceTypes = new ArrayList<>(installCommands.keySet()).stream().map(SpinnakerService.Type::fromCanonicalName).collect(Collectors.toList());
    List<String> upstartNames = getLocalServices(serviceTypes).stream().filter(i -> resolvedConfiguration.getServiceSettings(i.getService()).getEnabled()).map(i -> ((LocalDebianService) i).getUpstartServiceName()).filter(Objects::nonNull).collect(Collectors.toList());
    List<String> systemdServiceConfigs = upstartNames.stream().map(n -> n + ".service").collect(Collectors.toList());
    List<String> serviceInstalls = serviceTypes.stream().map(t -> installCommands.get(t.getCanonicalName())).collect(Collectors.toList());
    TemplatedResource resource = new StringReplaceJarResource("/debian/init.sh");
    bindings.put("services", Strings.join(upstartNames, " "));
    bindings.put("systemd-service-configs", Strings.join(systemdServiceConfigs, " "));
    String upstartInit = resource.setBindings(bindings).toString();
    BillOfMaterials.ArtifactSources artifactSources = artifactService.getArtifactSources(deploymentDetails.getDeploymentName());
    resource = new StringReplaceJarResource("/debian/install.sh");
    bindings = new HashMap<>();
    bindings.put("prepare-environment", "true");
    bindings.put("install-redis", "true");
    bindings.put("debian-repository", artifactSourcesConfig.mergeWithBomSources(artifactSources).getDebianRepository());
    bindings.put("install-commands", String.join("\n", serviceInstalls));
    bindings.put("service-action", "restart");
    bindings.put("upstart-init", upstartInit);
    return resource.setBindings(bindings).toString();
}
Also used : DeploymentDetails(com.netflix.spinnaker.halyard.deploy.deployment.v1.DeploymentDetails) java.util(java.util) ArtifactSourcesConfig(com.netflix.spinnaker.halyard.config.config.v1.ArtifactSourcesConfig) Autowired(org.springframework.beans.factory.annotation.Autowired) ArtifactService(com.netflix.spinnaker.halyard.deploy.services.v1.ArtifactService) GenerateService(com.netflix.spinnaker.halyard.deploy.services.v1.GenerateService) SpinnakerRuntimeSettings(com.netflix.spinnaker.halyard.deploy.spinnaker.v1.SpinnakerRuntimeSettings) Collectors(java.util.stream.Collectors) Component(org.springframework.stereotype.Component) LocalServiceProvider(com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.local.LocalServiceProvider) StringReplaceJarResource(com.netflix.spinnaker.halyard.core.resource.v1.StringReplaceJarResource) RemoteAction(com.netflix.spinnaker.halyard.core.RemoteAction) BillOfMaterials(com.netflix.spinnaker.halyard.core.registry.v1.BillOfMaterials) SpinnakerService(com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.SpinnakerService) Strings(io.fabric8.utils.Strings) TemplatedResource(com.netflix.spinnaker.halyard.core.resource.v1.TemplatedResource) TemplatedResource(com.netflix.spinnaker.halyard.core.resource.v1.TemplatedResource) SpinnakerService(com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.SpinnakerService) BillOfMaterials(com.netflix.spinnaker.halyard.core.registry.v1.BillOfMaterials) StringReplaceJarResource(com.netflix.spinnaker.halyard.core.resource.v1.StringReplaceJarResource)

Example 23 with Filter

use of io.fabric8.common.util.Filter in project fabric8-maven-plugin by fabric8io.

the class ResourceMojo method getResolvedImages.

private List<ImageConfiguration> getResolvedImages(List<ImageConfiguration> images, final Logger log) throws MojoExecutionException {
    List<ImageConfiguration> ret;
    ret = ConfigHelper.resolveImages(log, images, new ConfigHelper.Resolver() {

        @Override
        public List<ImageConfiguration> resolve(ImageConfiguration image) {
            return imageConfigResolver.resolve(image, project, session);
        }
    }, // no filter on image name yet (TODO: Maybe add this, too ?)
    null, new ConfigHelper.Customizer() {

        @Override
        public List<ImageConfiguration> customizeConfig(List<ImageConfiguration> configs) {
            try {
                GeneratorContext ctx = new GeneratorContext.Builder().config(extractGeneratorConfig()).project(project).session(session).goalFinder(goalFinder).goalName("fabric8:resource").logger(log).mode(mode).strategy(buildStrategy).useProjectClasspath(useProjectClasspath).build();
                return GeneratorManager.generate(configs, ctx, true);
            } catch (Exception e) {
                throw new IllegalArgumentException("Cannot extract generator: " + e, e);
            }
        }
    });
    Date now = getBuildReferenceDate();
    storeReferenceDateInPluginContext(now);
    String minimalApiVersion = ConfigHelper.initAndValidate(ret, null, /* no minimal api version */
    new ImageNameFormatter(project, now), log);
    return ret;
}
Also used : ImageConfigResolver(io.fabric8.maven.docker.config.handler.ImageConfigResolver) ImageConfiguration(io.fabric8.maven.docker.config.ImageConfiguration) ImageNameFormatter(io.fabric8.maven.docker.util.ImageNameFormatter) List(java.util.List) ArrayList(java.util.ArrayList) GeneratorContext(io.fabric8.maven.generator.api.GeneratorContext) MavenFilteringException(org.apache.maven.shared.filtering.MavenFilteringException) Fabric8ServiceException(io.fabric8.maven.core.service.Fabric8ServiceException) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) ConstraintViolationException(javax.validation.ConstraintViolationException) Date(java.util.Date)

Example 24 with Filter

use of io.fabric8.common.util.Filter in project strimzi by strimzi.

the class ControllerIT method waitForEvent.

private void waitForEvent(TestContext context, ConfigMap cm, String expectedMessage, Controller.EventType expectedType) {
    waitFor(context, () -> {
        List<Event> items = kubeClient.events().inNamespace(NAMESPACE).withLabels(cmPredicate.labels()).list().getItems();
        List<Event> filtered = items.stream().filter(evt -> !preExistingEvents.contains(evt.getMetadata().getUid()) && "ConfigMap".equals(evt.getInvolvedObject().getKind()) && cm.getMetadata().getName().equals(evt.getInvolvedObject().getName())).collect(Collectors.toList());
        LOGGER.debug("Waiting for events: {}", filtered.stream().map(evt -> evt.getMessage()).collect(Collectors.toList()));
        if (!filtered.isEmpty()) {
            assertEquals(1, filtered.size());
            Event event = filtered.get(0);
            assertEquals(expectedMessage, event.getMessage());
            assertEquals(expectedType.name, event.getType());
            assertNotNull(event.getInvolvedObject());
            assertEquals("ConfigMap", event.getInvolvedObject().getKind());
            assertEquals(cm.getMetadata().getName(), event.getInvolvedObject().getName());
            return true;
        } else {
            return false;
        }
    }, timeout, "Expected an error event");
}
Also used : TestContext(io.vertx.ext.unit.TestContext) ZookeeperServer(io.debezium.kafka.ZookeeperServer) LoggerFactory(org.slf4j.LoggerFactory) ConfigEntry(org.apache.kafka.clients.admin.ConfigEntry) BooleanSupplier(java.util.function.BooleanSupplier) Collections.singletonList(java.util.Collections.singletonList) AdminClient(org.apache.kafka.clients.admin.AdminClient) Locale(java.util.Locale) After(org.junit.After) Map(java.util.Map) DeleteTopicsResult(org.apache.kafka.clients.admin.DeleteTopicsResult) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient) ClassRule(org.junit.ClassRule) KafkaCluster(io.debezium.kafka.KafkaCluster) AfterClass(org.junit.AfterClass) Event(io.fabric8.kubernetes.api.model.Event) Namespace(io.strimzi.test.Namespace) Set(java.util.Set) Future(io.vertx.core.Future) Collectors(java.util.stream.Collectors) List(java.util.List) AlterConfigsResult(org.apache.kafka.clients.admin.AlterConfigsResult) UnknownTopicOrPartitionException(org.apache.kafka.common.errors.UnknownTopicOrPartitionException) Async(io.vertx.ext.unit.Async) BeforeClass(org.junit.BeforeClass) NewPartitions(org.apache.kafka.clients.admin.NewPartitions) RunWith(org.junit.runner.RunWith) HashMap(java.util.HashMap) ConfigResource(org.apache.kafka.common.config.ConfigResource) KubeClusterResource(io.strimzi.test.k8s.KubeClusterResource) CreateTopicsResult(org.apache.kafka.clients.admin.CreateTopicsResult) Collections.singletonMap(java.util.Collections.singletonMap) Before(org.junit.Before) Collections.emptyMap(java.util.Collections.emptyMap) Logger(org.slf4j.Logger) Files(java.nio.file.Files) Assert.assertNotNull(org.junit.Assert.assertNotNull) Vertx(io.vertx.core.Vertx) NewTopic(org.apache.kafka.clients.admin.NewTopic) Test(org.junit.Test) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) CreatePartitionsResult(org.apache.kafka.clients.admin.CreatePartitionsResult) Field(java.lang.reflect.Field) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) ConfigMapBuilder(io.fabric8.kubernetes.api.model.ConfigMapBuilder) ExecutionException(java.util.concurrent.ExecutionException) Ignore(org.junit.Ignore) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) Assert.assertEquals(org.junit.Assert.assertEquals) Event(io.fabric8.kubernetes.api.model.Event)

Example 25 with Filter

use of io.fabric8.common.util.Filter in project vertx-openshift-it by cescoffier.

the class Deployment method deployIfNeeded.

public static String deployIfNeeded(KubernetesClient client, String name, String path) {
    if (oc(client).deploymentConfigs().withName(name).get() != null) {
        System.out.println("Skipping the creation of dc/" + name);
        return name;
    }
    ImageStream stream = findImageStream(client, name);
    ensureThat("the image stream " + name + " exists in the namespace " + client.getNamespace(), () -> assertThat(stream).isNotNull());
    File file = filter(Objects.requireNonNull(path), ImmutableMap.of("image", stream.getStatus().getDockerImageRepository()));
    String name2 = deployIfNeeded(client, file);
    assertThat(name).isEqualTo(name2);
    return name;
}
Also used : ImageStream(io.fabric8.openshift.api.model.ImageStream) File(java.io.File)

Aggregations

List (java.util.List)18 Map (java.util.Map)18 Collectors (java.util.stream.Collectors)18 IOException (java.io.IOException)16 Pod (io.fabric8.kubernetes.api.model.Pod)12 ArrayList (java.util.ArrayList)12 File (java.io.File)11 HashMap (java.util.HashMap)11 Optional (java.util.Optional)11 TimeUnit (java.util.concurrent.TimeUnit)10 Logger (org.slf4j.Logger)10 LoggerFactory (org.slf4j.LoggerFactory)10 InputStream (java.io.InputStream)8 DeploymentConfig (io.fabric8.openshift.api.model.DeploymentConfig)7 Test (org.junit.Test)7 Volume (io.fabric8.kubernetes.api.model.Volume)6 Arrays (java.util.Arrays)6 PodList (io.fabric8.kubernetes.api.model.PodList)5 VolumeMount (io.fabric8.kubernetes.api.model.VolumeMount)5 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)5