Search in sources :

Example 6 with Project

use of io.fabric8.openshift.api.model.Project in project fabric8 by jboss-fuse.

the class DeployToProfileMojo method uploadRequirements.

protected DeployResults uploadRequirements(J4pClient client, ProjectRequirements requirements) throws Exception {
    String json = DtoHelper.getMapper().writeValueAsString(requirements);
    ObjectName mbeanName = ProjectDeployerImpl.OBJECT_NAME;
    getLog().info("Updating " + (requirements.isAbstractProfile() ? "abstract " : "") + "profile: " + requirements.getProfileId() + " with parent profile(s): " + requirements.getParentProfiles() + (requirements.isUseResolver() ? " using OSGi resolver" : "") + (requirements.isLocked() ? " locked" : ""));
    getLog().info("About to invoke mbean " + mbeanName + " on jolokia URL: " + jolokiaUrl + " with user: " + fabricServer.getUsername());
    getLog().debug("JSON: " + json);
    try {
        // Append bundles to existing profile bundles if we're not running the plugin at project root
        Boolean appendBundles = !mavenSession.getExecutionRootDirectory().equalsIgnoreCase(project.getBasedir().toString());
        J4pExecRequest request = new J4pExecRequest(mbeanName, "deployProjectJsonMergeOption(java.lang.String,boolean)", json, appendBundles);
        J4pResponse<J4pExecRequest> response = client.execute(request, "POST");
        Object value = response.getValue();
        if (value == null) {
            return null;
        } else {
            DeployResults answer = DtoHelper.getMapper().reader(DeployResults.class).readValue(value.toString());
            if (answer != null) {
                String profileUrl = answer.getProfileUrl();
                if (profileUrl != null) {
                    getLog().info("");
                    getLog().info("Profile page: " + profileUrl);
                    getLog().info("");
                } else {
                    getLog().info("Result: " + answer);
                }
            } else {
                getLog().info("Result: " + value);
            }
            return answer;
        }
    } catch (J4pRemoteException e) {
        if (e.getMessage().contains(".InstanceNotFoundException")) {
            throw new MojoExecutionException("Could not find the mbean " + mbeanName + " in the JVM for " + jolokiaUrl + ". Are you sure this JVM is running the Fabric8 console?");
        } else {
            getLog().error("Failed to invoke mbean " + mbeanName + " on jolokia URL: " + jolokiaUrl + " with user: " + fabricServer.getUsername() + ". Error: " + e.getErrorType());
            getLog().error("Stack: " + e.getRemoteStackTrace());
            throw e;
        }
    }
}
Also used : J4pRemoteException(org.jolokia.client.exception.J4pRemoteException) DeployResults(io.fabric8.deployer.dto.DeployResults) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) J4pExecRequest(org.jolokia.client.request.J4pExecRequest) ObjectName(javax.management.ObjectName)

Example 7 with Project

use of io.fabric8.openshift.api.model.Project in project fabric8 by jboss-fuse.

the class DeployToProfileMojoTest method shouldExpandProjectVersionPlaceholder.

@Test
public void shouldExpandProjectVersionPlaceholder() throws IOException, J4pException, MalformedObjectNameException, MojoExecutionException {
    // Given
    File config = new File(root, randomUUID().toString());
    String property = "project = " + PLACEHOLDER_PROJECT_VERSION;
    writeToFile(config, property.getBytes());
    // When
    mojo.uploadProfileConfigFile(jolokiaClient, deployResults, root, config);
    String decodedConfig = decodeSentConfig();
    // Then
    assertEquals("project = " + FABRIC_VERSION, decodedConfig);
}
Also used : Matchers.anyString(org.mockito.Matchers.anyString) Files.writeToFile(io.fabric8.common.util.Files.writeToFile) File(java.io.File) Test(org.junit.Test)

Example 8 with Project

use of io.fabric8.openshift.api.model.Project in project fabric8 by jboss-fuse.

the class AbstractProfileMojo method buildFrom.

private DependencyDTO buildFrom(DependencyNode node) {
    Artifact artifact = node.getArtifact();
    if (artifact != null) {
        DependencyDTO answer = new DependencyDTO();
        answer.setGroupId(artifact.getGroupId());
        answer.setArtifactId(artifact.getArtifactId());
        if (artifact.isSnapshot() && !uniqueVersion) {
            answer.setVersion(artifact.getBaseVersion());
        } else {
            answer.setVersion(artifact.getVersion());
        }
        answer.setClassifier(artifact.getClassifier());
        String scope = artifact.getScope();
        answer.setScope(scope);
        answer.setType(artifact.getType());
        // so lets ignore this for the maven project's artifact
        if (artifact.getClassifier() == null && "jar".equals(artifact.getType())) {
            if (project.getArtifact().equals(artifact)) {
                getLog().debug("Ignoring bundle check on the maven project artifact: " + artifact + " as this causes issues with the maven-install-plugin and we can assume the project packaging is accurate");
            } else {
                try {
                    ArtifactResolutionRequest request = new ArtifactResolutionRequest();
                    request.setArtifact(artifact);
                    request.setRemoteRepositories(remoteRepositories);
                    request.setLocalRepository(localRepository);
                    resolver.resolve(request);
                    JarInputStream jis = new JarInputStream(new FileInputStream(artifact.getFile()));
                    Manifest man = jis.getManifest();
                    String bsn = man.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME);
                    if (bsn != null) {
                        answer.setType("bundle");
                    } else {
                    // Try to find a matching servicemix bundle for it
                    /*
                        Map<String, String> bundles = getAllServiceMixBundles();
                        getLog().debug("Trying to find a matching bundle for " + artifact);
                        String match = bundles.get(artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getVersion());
                        if (match != null) {
                            String[] parts = match.split(":");
                            answer.setGroupId(parts[0]);
                            answer.setArtifactId(parts[1]);
                            answer.setVersion(parts[2]);
                            getLog().info("Replacing artifact " + artifact + " with servicemix bundle " + match);
                        }
                        */
                    }
                } catch (Exception e) {
                    getLog().debug("Error checking artifact type for " + artifact, e);
                }
            }
        }
        answer.setOptional(artifact.isOptional());
        String type = answer.getType();
        if (type != null && type.equals("pom")) {
            getLog().debug("Ignoring pom.xml for " + answer);
            return null;
        }
        int state = node.getState();
        if (state != DependencyNode.INCLUDED) {
            getLog().debug("Ignoring " + node);
            return null;
        }
        if (isWarProject()) {
            if (scope != null && !scope.equals("provided")) {
                getLog().debug("WAR packaging so ignoring non-provided scope " + scope + " for " + node);
                return null;
            }
        }
        List children = node.getChildren();
        for (Object child : children) {
            if (child instanceof DependencyNode) {
                DependencyNode childNode = (DependencyNode) child;
                if (childNode.getState() == DependencyNode.INCLUDED) {
                    String childScope = childNode.getArtifact().getScope();
                    if (!"test".equals(childScope) && !"provided".equals(childScope)) {
                        DependencyDTO childDTO = buildFrom(childNode);
                        if (childDTO != null) {
                            answer.addChild(childDTO);
                        }
                    } else {
                        getLog().debug("Ignoring artifact " + childNode.getArtifact() + " with scope " + childScope);
                    }
                }
            }
        }
        return answer;
    }
    return null;
}
Also used : JarInputStream(java.util.jar.JarInputStream) ArtifactResolutionRequest(org.apache.maven.artifact.resolver.ArtifactResolutionRequest) DependencyNode(org.apache.maven.shared.dependency.tree.DependencyNode) DependencyDTO(io.fabric8.deployer.dto.DependencyDTO) List(java.util.List) ArrayList(java.util.ArrayList) Manifest(java.util.jar.Manifest) Artifact(org.apache.maven.artifact.Artifact) FileInputStream(java.io.FileInputStream) DependencyTreeBuilderException(org.apache.maven.shared.dependency.tree.DependencyTreeBuilderException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException)

Example 9 with Project

use of io.fabric8.openshift.api.model.Project 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 10 with Project

use of io.fabric8.openshift.api.model.Project in project fabric8-maven-plugin by fabric8io.

the class OpenshiftBuildServiceTest method init.

@Before
public void init() throws Exception {
    final File dockerFile = new File(baseDir, "Docker.tar");
    dockerFile.getParentFile().mkdirs();
    dockerFile.createNewFile();
    imageStreamFile.delete();
    new Expectations() {

        {
            dockerServiceHub.getArchiveService();
            result = archiveService;
            archiveService.createDockerBuildArchive(withAny(ImageConfiguration.class.cast(null)), withAny(MojoParameters.class.cast(null)));
            result = dockerFile;
            minTimes = 0;
            project.getArtifact();
            result = "myapp";
            minTimes = 0;
            dockerMojoParameters.getProject();
            result = project;
            minTimes = 0;
        }
    };
    image = new ImageConfiguration.Builder().name(projectName).buildConfig(new BuildImageConfiguration.Builder().from(projectName).build()).build();
    defaultConfig = new BuildService.BuildServiceConfig.Builder().buildDirectory(baseDir).buildRecreateMode(BuildRecreateMode.none).s2iBuildNameSuffix("-s2i-suffix2").openshiftBuildStrategy(OpenShiftBuildStrategy.s2i).dockerMojoParameters(dockerMojoParameters);
}
Also used : Expectations(mockit.Expectations) BuildService(io.fabric8.maven.core.service.BuildService) ImageStreamStatusBuilder(io.fabric8.openshift.api.model.ImageStreamStatusBuilder) BuildBuilder(io.fabric8.openshift.api.model.BuildBuilder) NamedTagEventListBuilder(io.fabric8.openshift.api.model.NamedTagEventListBuilder) KubernetesListBuilder(io.fabric8.kubernetes.api.model.KubernetesListBuilder) ImageStreamBuilder(io.fabric8.openshift.api.model.ImageStreamBuilder) BuildConfigBuilder(io.fabric8.openshift.api.model.BuildConfigBuilder) File(java.io.File) BuildImageConfiguration(io.fabric8.maven.docker.config.BuildImageConfiguration) Before(org.junit.Before)

Aggregations

Test (org.junit.Test)51 ResourceConfig (io.fabric8.maven.core.config.ResourceConfig)29 File (java.io.File)14 Expectations (mockit.Expectations)14 ArrayList (java.util.ArrayList)13 BuildImageConfiguration (io.fabric8.maven.docker.config.BuildImageConfiguration)11 ImageConfiguration (io.fabric8.maven.docker.config.ImageConfiguration)11 ProcessorConfig (io.fabric8.maven.core.config.ProcessorConfig)9 IOException (java.io.IOException)8 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)8 VolumeConfig (io.fabric8.maven.core.config.VolumeConfig)7 GeneratorContext (io.fabric8.maven.generator.api.GeneratorContext)6 OpenShiftClient (io.fabric8.openshift.client.OpenShiftClient)6 PodTemplateSpec (io.fabric8.kubernetes.api.model.PodTemplateSpec)5 BuildConfig (io.fabric8.openshift.api.model.BuildConfig)5 MojoFailureException (org.apache.maven.plugin.MojoFailureException)5 MavenProject (org.apache.maven.project.MavenProject)5 KubernetesListBuilder (io.fabric8.kubernetes.api.model.KubernetesListBuilder)4 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)4 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)3