org.jboss.forge.addon.resource.DirectoryResource Java Examples

The following examples show how to use org.jboss.forge.addon.resource.DirectoryResource. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DetectFractionsCommand.java    From thorntail-addon with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void initializeUI(UIBuilder builder) throws Exception
{
   InputComponentFactory factory = builder.getInputComponentFactory();
   Project project = getSelectedProject(builder);
   inputDir = factory.createInput("inputDir", DirectoryResource.class).setLabel("Input Directory")
            .setDescription("Directory containing the compiled project sources").setRequired(true)
            .setDefaultValue(getTargetDirectory(project));
   build = factory.createInput("build", Boolean.class).setLabel("Build Project?")
            .setDescription("Build project before attempting to auto-detect");
   depend = factory.createInput("depend", Boolean.class)
            .setLabel("Add Missing Fractions as Project Dependencies?")
            .setDescription("Add missing fractions as project dependencies");

   builder.add(inputDir).add(build).add(depend);
}
 
Example #2
Source File: DetectFractionsCommand.java    From thorntail-addon with Eclipse Public License 1.0 6 votes vote down vote up
private DirectoryResource getTargetDirectory(Project project)
{
   MavenFacet mavenFacet = project.getFacet(MavenFacet.class);
   Build build = mavenFacet.getModel().getBuild();
   String targetFolderName;
   if (build != null && build.getOutputDirectory() != null)
   {
      targetFolderName = mavenFacet.resolveProperties(build.getOutputDirectory());
   }
   else
   {
      targetFolderName = "target" + File.separator + "classes";
   }
   DirectoryResource projectRoot = project.getRoot().reify(DirectoryResource.class);
   return projectRoot.getChildDirectory(targetFolderName);
}
 
Example #3
Source File: FunktionArchetypeSelectionWizardStep.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
@Override
public Result execute(UIExecutionContext context) throws Exception {
    UIContext uiContext = context.getUIContext();
    Project project = (Project) uiContext.getAttributeMap().get(Project.class);
    Archetype chosenArchetype = archetype.getValue();
    String coordinate = chosenArchetype.getGroupId() + ":" + chosenArchetype.getArtifactId() + ":"
            + chosenArchetype.getVersion();
    DependencyQueryBuilder depQuery = DependencyQueryBuilder.create(coordinate);
    String repository = chosenArchetype.getRepository();
    if (!Strings.isNullOrEmpty(repository)) {
        if (repository.endsWith(".xml")) {
            int lastRepositoryPath = repository.lastIndexOf('/');
            if (lastRepositoryPath > -1)
                repository = repository.substring(0, lastRepositoryPath);
        }
        if (!repository.isEmpty()) {
            depQuery.setRepositories(new DependencyRepository("archetype", repository));
        }
    }
    Dependency resolvedArtifact = dependencyResolver.resolveArtifact(depQuery);
    FileResource<?> artifact = resolvedArtifact.getArtifact();
    MetadataFacet metadataFacet = project.getFacet(MetadataFacet.class);
    File fileRoot = project.getRoot().reify(DirectoryResource.class).getUnderlyingResourceObject();
    ArchetypeHelper archetypeHelper = new ArchetypeHelper(artifact.getResourceInputStream(), fileRoot,
            metadataFacet.getProjectGroupName(), metadataFacet.getProjectName(), metadataFacet.getProjectVersion());
    JavaSourceFacet facet = project.getFacet(JavaSourceFacet.class);
    archetypeHelper.setPackageName(facet.getBasePackage());
    archetypeHelper.execute();
    return Results.success();
}
 
Example #4
Source File: SpringBootNewProjectCommand.java    From fabric8-forge with Apache License 2.0 4 votes vote down vote up
@Override
public Result execute(UIExecutionContext context) throws Exception {
    UIContext uiContext = context.getUIContext();
    Project project = (Project) uiContext.getAttributeMap().get(Project.class);
    if (project == null) {
        project = getSelectedProject(context.getUIContext());
    }
    MetadataFacet metadataFacet = project.getFacet(MetadataFacet.class);

    String projectName = metadataFacet.getProjectName();
    String groupId = metadataFacet.getProjectGroupName();
    String version = metadataFacet.getProjectVersion();
    File folder = project.getRoot().reify(DirectoryResource.class).getUnderlyingResourceObject();

    Map<String, SpringBootDependencyDTO> selectedDTOs = new HashMap<>();
    int[] selected = dependencies.getSelectedIndexes();
    CollectionStringBuffer csbSpringBoot = new CollectionStringBuffer(",");
    CollectionStringBuffer csbFabric8 = new CollectionStringBuffer(",");
    for (int val : selected) {
        SpringBootDependencyDTO dto = choices.get(val);
        if (isFabric8Dependency(dto.getId())) {
            csbFabric8.append(dto.getId());
        } else {
            csbSpringBoot.append(dto.getId());
        }
        selectedDTOs.put(dto.getId(), dto);
    }
    String springBootDeps = csbSpringBoot.toString();
    String fabric8Deps = csbFabric8.toString();
    // boot version need the RELEASE suffix
    String bootVersion = springBootVersion.getValue() + ".RELEASE";

    String url = String.format("%s?bootVersion=%s&groupId=%s&artifactId=%s&version=%s&packageName=%s&dependencies=%s",
            STARTER_URL, bootVersion, groupId, projectName, version, groupId, springBootDeps);

    LOG.info("About to query url: " + url);

    // use http client to call start.spring.io that creates the project
    OkHttpClient client = createOkHttpClient();

    Request request = new Request.Builder().url(url).build();

    Response response = client.newCall(request).execute();
    InputStream is = response.body().byteStream();

    // some archetypes might not use maven or use the maven source layout so lets remove
    // the pom.xml and src folder if its already been pre-created
    // as these will be created if necessary via the archetype jar's contents
    File pom = new File(folder, "pom.xml");
    if (pom.isFile() && pom.exists()) {
        pom.delete();
    }
    File src = new File(folder, "src");
    if (src.isDirectory() && src.exists()) {
        recursiveDelete(src);
    }

    File name = new File(folder, projectName + ".zip");
    if (name.exists()) {
        name.delete();
    }

    FileOutputStream fos = new FileOutputStream(name, false);
    copyAndCloseInput(is, fos);
    close(fos);

    // unzip the download from spring starter
    unzip(name, folder);

    LOG.info("Unzipped file to folder: {}", folder.getAbsolutePath());

    // and delete the zip file
    name.delete();

    if (!Strings.isEmpty(fabric8Deps)) {
        addFabric8DependenciesToPom(project, fabric8Deps, selectedDTOs);
    }

    // are there any fabric8 dependencies to add afterwards?
    return Results.success("Created new Spring Boot project in directory: " + folder.getName());
}
 
Example #5
Source File: DetectFractionsCommand.java    From thorntail-addon with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public Result execute(UIExecutionContext executionContext) throws Exception
{
   UIProgressMonitor progressMonitor = executionContext.getProgressMonitor();
   UIOutput output = executionContext.getUIContext().getProvider().getOutput();
   FractionUsageAnalyzer analyzer = ThorntailFacet.getFractionUsageAnalyzer();
   DirectoryResource value = inputDir.getValue();
   analyzer.source(value.getUnderlyingResourceObject());
   Project project = getSelectedProject(executionContext);
   int total = 1;
   if (build.getValue())
      total++;
   if (depend.getValue())
      total++;
   progressMonitor.beginTask("Detecting fractions", total);
   if (build.getValue())
   {
      PackagingFacet packaging = project.getFacet(PackagingFacet.class);
      progressMonitor.setTaskName("Building the project...");
      FileResource<?> finalArtifact = packaging.createBuilder().build(output.out(), output.err())
               .reify(FileResource.class);
      analyzer.source(finalArtifact.getUnderlyingResourceObject());
      progressMonitor.worked(1);
   }
   Collection<FractionDescriptor> detectedFractions = analyzer.detectNeededFractions();
   output.info(output.out(), "Detected fractions: " + detectedFractions);
   progressMonitor.worked(1);
   if (depend.getValue() && detectedFractions.size() > 0)
   {
      progressMonitor.setTaskName("Adding missing fractions as project dependencies...");
      ThorntailFacet facet = project.getFacet(ThorntailFacet.class);
      detectedFractions.removeAll(facet.getInstalledFractions());
      // detectedFractions.remove(fractionList.getFractionDescriptor(Swarm.DEFAULT_FRACTION_GROUPID, "container"));
      if (detectedFractions.isEmpty())
      {
         output.warn(output.out(), "Project already contains all the installed fractions. Doing nothing.");
      }
      else
      {
         output.info(output.out(), "Installing the following dependencies: " + detectedFractions);
         facet.installFractions(detectedFractions);
      }
      progressMonitor.worked(1);
   }
   progressMonitor.done();
   return Results.success();
}
 
Example #6
Source File: WindupCommand.java    From windup with Eclipse Public License 1.0 4 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private void initializeConfigurationOptionComponents(UIBuilder builder)
{
    for (final ConfigurationOption option : WindupConfiguration.getWindupConfigurationOptions())
    {
        InputComponent<?, ?> inputComponent = null;
        switch (option.getUIType())
        {
        case SINGLE:
        {
            UIInput<?> inputSingle = componentFactory.createInput(option.getName(), option.getType());
            inputSingle.setDefaultValue(new DefaultValueAdapter(option));
            inputComponent = inputSingle;
            break;
        }
        case MANY:
        {
            // forge can't handle "Path", so use File
            Class<?> optionType = option.getType() == Path.class ? File.class : option.getType();

            UIInputMany<?> inputMany = componentFactory.createInputMany(option.getName(), optionType);
            inputMany.setDefaultValue(new DefaultValueAdapter(option, Iterable.class));
            inputComponent = inputMany;
            break;
        }
        case SELECT_MANY:
        {
            UISelectMany<?> selectMany = componentFactory.createSelectMany(option.getName(), option.getType());
            selectMany.setValueChoices((Iterable) option.getAvailableValues());
            selectMany.setDefaultValue(new DefaultValueAdapter(option, Iterable.class));
            inputComponent = selectMany;
            break;
        }
        case SELECT_ONE:
        {
            UISelectOne<?> selectOne = componentFactory.createSelectOne(option.getName(), option.getType());
            selectOne.setValueChoices((Iterable) option.getAvailableValues());
            selectOne.setDefaultValue(new DefaultValueAdapter(option));
            inputComponent = selectOne;
            break;
        }
        case DIRECTORY:
        {
            UIInput<DirectoryResource> directoryInput = componentFactory.createInput(option.getName(),
                        DirectoryResource.class);
            directoryInput.setDefaultValue(new DefaultValueAdapter(option, DirectoryResource.class));
            inputComponent = directoryInput;
            break;
        }
        case FILE:
        {
            UIInput<?> fileInput = componentFactory.createInput(option.getName(), FileResource.class);
            fileInput.setDefaultValue(new DefaultValueAdapter(option, FileResource.class));
            inputComponent = fileInput;
            break;
        }
        case FILE_OR_DIRECTORY:
        {
            UIInput<?> fileOrDirInput = componentFactory.createInput(option.getName(), FileResource.class);
            fileOrDirInput.setDefaultValue(new DefaultValueAdapter(option, FileResource.class));
            inputComponent = fileOrDirInput;
            break;
        }
        }
        if (inputComponent == null)
        {
            throw new IllegalArgumentException("Could not build input component for: " + option);
        }
        inputComponent.setLabel(option.getLabel());
        inputComponent.setRequired(option.isRequired());
        inputComponent.setDescription(option.getDescription());
        builder.add(inputComponent);
        inputOptions.put(option, inputComponent);
    }
}
 
Example #7
Source File: WindupCommandTest.java    From windup with Eclipse Public License 1.0 4 votes vote down vote up
@Test
public void testOutputDefaultValue() throws Exception
{
    Assert.assertNotNull(uiTestHarness);
    try (CommandController controller = uiTestHarness.createCommandController(WindupCommand.class))
    {
        File inputFile = File.createTempFile("windupwizardtest", ".jar");
        inputFile.deleteOnExit();
        try (InputStream iStream = getClass().getResourceAsStream("/test.jar"))
        {
            try (OutputStream oStream = new FileOutputStream(inputFile))
            {
                IOUtils.copy(iStream, oStream);
            }
        }

        try
        {

            setupController(controller, inputFile, null);

            Result result = controller.execute();
            Object outputDir = controller.getValueFor("output");
            Assert.assertTrue("The output should be a folder",
                        DirectoryResource.class.isAssignableFrom(outputDir.getClass()));
            Assert.assertTrue("The output should be created inside the .report folder by default",
                        ((DirectoryResource) outputDir).getName().endsWith(".report"));
            ArrayList<File> inputDirs = (ArrayList<File>) controller.getValueFor("input");
            Assert.assertEquals(1, inputDirs.size());

            File inputDirParent = inputDirs.get(0).getParentFile();
            File child = new File(inputDirParent, ((DirectoryResource) outputDir).getName());
            Assert.assertTrue("The output should be created near the ${input} folder by default", child.exists());
            Assert.assertTrue("The output should be created near the ${input} folder by default", child.isDirectory());
            final String msg = "controller.execute() 'Failed': " + result.getMessage();
            Assert.assertFalse(msg, result instanceof Failed);
        }
        finally
        {
            inputFile.delete();
        }
    }
}