Java Code Examples for org.jboss.forge.furnace.util.OperatingSystemUtils#createTempDir()

The following examples show how to use org.jboss.forge.furnace.util.OperatingSystemUtils#createTempDir() . 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: NewComponentInstanceTest.java    From fabric8-forge with Apache License 2.0 6 votes vote down vote up
@Test
public void testSomething() throws Exception {
    File tempDir = OperatingSystemUtils.createTempDir();
    try {
        Project project = projectFactory.createTempProject();
        Assert.assertNotNull("Should have created a project", project);

        CommandController command = testHarness.createCommandController(CamelSetupCommand.class, project.getRoot());
        command.initialize();
        command.setValueFor("kind", "camel-spring");

        Result result = command.execute();
        Assert.assertFalse("Should setup Camel in the project", result instanceof Failed);

        command = testHarness.createCommandController(CamelGetComponentsCommand.class, project.getRoot());
        command.initialize();

        result = command.execute();
        Assert.assertFalse("Should not fail", result instanceof Failed);

        String message = result.getMessage();
        System.out.println(message);
    } finally {
        tempDir.delete();
    }
}
 
Example 2
Source File: ContainerLifecycleListenerTest.java    From furnace with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testContainerStartup() throws Exception
{
   Furnace furnace = FurnaceFactory.getInstance();
   TestLifecycleListener listener = new TestLifecycleListener();
   ListenerRegistration<ContainerLifecycleListener> registration = furnace.addContainerLifecycleListener(listener);
   File temp = OperatingSystemUtils.createTempDir();
   temp.deleteOnExit();
   furnace.addRepository(AddonRepositoryMode.IMMUTABLE, temp);

   furnace.startAsync();
   waitUntilStarted(furnace);
   Assert.assertEquals(1, listener.beforeStartTimesCalled);
   Assert.assertEquals(1, listener.afterStartTimesCalled);
   registration.removeListener();
   furnace.stop();
}
 
Example 3
Source File: AddonRepositoryImplTest.java    From furnace with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testPluggableStateRepository() throws Exception
{
   Furnace furnace = new FurnaceImpl();
   File temp = OperatingSystemUtils.createTempDir();
   MutableAddonRepositoryStorageStrategy storageRepository = new AddonRepositoryStorageStrategyImpl(furnace.getLockManager(), temp);

   MutableAddonRepositoryStateStrategy stateRepository = new TestInMemoryAddonRepositoryStateStrategy();
   MutableAddonRepository repository = new AddonRepositoryImpl(storageRepository, stateRepository, temp);

   AddonId addon = TestInMemoryAddonRepositoryStateStrategy.TEST_ADDON;

   repository.enable(addon);
   Assert.assertTrue(repository.isEnabled(addon));

   // Delete storage directory to demonstrate that filesystem is not used to store the state
   Files.delete(temp, true);

   // Addon still enabled state wasn't affected
   Assert.assertTrue(repository.isEnabled(addon));
}
 
Example 4
Source File: AddonManagerRealTest.java    From furnace with Eclipse Public License 1.0 5 votes vote down vote up
@Before
public void setUp() throws IOException
{
   furnace = ServiceLoader.load(Furnace.class).iterator().next();
   resolver = new MavenAddonDependencyResolver();
   repository = OperatingSystemUtils.createTempDir();
   furnace.addRepository(AddonRepositoryMode.MUTABLE, repository);
   addonManager = new AddonManagerImpl(furnace, resolver);
}
 
Example 5
Source File: AddonManagerInstallTest.java    From furnace with Eclipse Public License 1.0 5 votes vote down vote up
@Before
public void setUp() throws IOException
{
   furnace = ServiceLoader.load(Furnace.class).iterator().next();
   resolver = new MavenAddonDependencyResolver();
   repository = OperatingSystemUtils.createTempDir();
   furnace.addRepository(AddonRepositoryMode.MUTABLE, repository);
   addonManager = new AddonManagerImpl(furnace, resolver);
}
 
Example 6
Source File: BootstrapClassLoader.java    From furnace with Eclipse Public License 1.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
private List<URL> handleZipFile(File file) throws IOException
{
   File tempDir = OperatingSystemUtils.createTempDir();
   List<URL> result = new ArrayList<>();
   try
   {
      ZipFile zip = new ZipFile(file);
      Enumeration<? extends ZipEntry> entries = zip.entries();
      while (entries.hasMoreElements())
      {
         ZipEntry entry = entries.nextElement();
         String name = entry.getName();
         if (name.matches(path + "/.*\\.jar"))
         {
            log.log(Level.FINE, String.format("ZipEntry detected: %s len %d added %TD",
                     file.getAbsolutePath() + "/" + entry.getName(), entry.getSize(),
                     new Date(entry.getTime())));

            result.add(copy(tempDir, entry.getName(),
                     JarLocator.class.getClassLoader().getResource(name).openStream()
                     ).toURL());
         }
      }
      zip.close();
   }
   catch (ZipException e)
   {
      throw new RuntimeException("Error handling file " + file, e);
   }
   return result;
}
 
Example 7
Source File: MultipleRepositoryViewTest.java    From furnace with Eclipse Public License 1.0 5 votes vote down vote up
@Before
public void init() throws IOException
{
   leftRepo = OperatingSystemUtils.createTempDir();
   leftRepo.deleteOnExit();
   rightRepo = OperatingSystemUtils.createTempDir();
   rightRepo.deleteOnExit();
}
 
Example 8
Source File: AddonRepositoryImplTest.java    From furnace with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testSharedStorageRepository() throws Exception
{
   Furnace furnace = new FurnaceImpl();

   File temp = OperatingSystemUtils.createTempDir();
   MutableAddonRepositoryStorageStrategy storageRepository = new AddonRepositoryStorageStrategyImpl(furnace.getLockManager(), temp);

   AddonRepositoryStateStrategyImpl firstStateRepository = new AddonRepositoryStateStrategyImpl(furnace, OperatingSystemUtils.createTempDir());
   MutableAddonRepository firstRepo = new AddonRepositoryImpl(storageRepository, firstStateRepository, temp);

   AddonRepositoryStateStrategyImpl secondStateRepository = new AddonRepositoryStateStrategyImpl(furnace, OperatingSystemUtils.createTempDir());
   MutableAddonRepository secondRepo = new AddonRepositoryImpl(storageRepository, secondStateRepository, temp);

   AddonId addon = TestInMemoryAddonRepositoryStateStrategy.TEST_ADDON;

   Assert.assertFalse(firstRepo.isDeployed(addon));
   Assert.assertFalse(secondRepo.isDeployed(addon));

   // Since storage is shared, addon will be deployed to both repositories
   firstRepo.deploy(addon, Collections.emptyList(), Collections.emptyList());

   Assert.assertTrue(firstRepo.isDeployed(addon));
   Assert.assertTrue(secondRepo.isDeployed(addon));

   firstRepo.enable(addon);

   Assert.assertTrue(firstRepo.isEnabled(addon));
   Assert.assertFalse(secondRepo.isEnabled(addon));
}
 
Example 9
Source File: AddonRepositoryImplTest.java    From furnace with Eclipse Public License 1.0 5 votes vote down vote up
private static AddonRepositoryImpl createTempRepository(Furnace furnace, MutableAddonRepositoryStateStrategy stateRepository)
{
   File temp = OperatingSystemUtils.createTempDir();
   MutableAddonRepositoryStorageStrategy storageRepository = new AddonRepositoryStorageStrategyImpl(furnace.getLockManager(), temp);

   return new AddonRepositoryImpl(storageRepository, stateRepository, temp);
}
 
Example 10
Source File: WindupUpdateRulesetCommandTest.java    From windup with Eclipse Public License 1.0 5 votes vote down vote up
@Test
@Ignore("Command can't be used currently as there's no way to run it from the UI."
            + " I'm leaving it here in case we needed the command again (maybe from a GUI?).")
public void testUpdateRulesetCommand() throws Exception
{
    // Extract the windup zip to a temp dir.
    File tempDir = OperatingSystemUtils.createTempDir();
    ZipUtil.unzipFromClassResource(WindupUpdateRulesetCommandTest.class, TEST_OLD_WINDUP, tempDir);

    // This may cause FileNotFound in Furnace if it's already running.
    System.setProperty("windup.home", new File(tempDir, "windup-old-ruleset").getAbsolutePath());

    try (CommandController controller = uiTestHarness.createCommandController(WindupUpdateRulesetCommand.class))
    {
        boolean rulesetNeedUpdate = updater.rulesetsNeedUpdate(true);
        Assert.assertTrue("Rulesets should need an update.", rulesetNeedUpdate);

        controller.initialize();
        Assert.assertTrue(controller.isEnabled());
        Result result = controller.execute();
        Assert.assertFalse(result instanceof Failed);
        rulesetNeedUpdate = updater.rulesetsNeedUpdate(true);
        Assert.assertFalse(rulesetNeedUpdate);
    }
    finally
    {
        FileUtils.deleteDirectory(tempDir);
        System.getProperties().remove("windup.home");
    }
}
 
Example 11
Source File: WindupUpdateRulesetTest.java    From windup with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testUpdateRuleset() throws Exception
{
    // Extract the rulesets to a temp dir and move the rules/ to target/rules/ .
    File tempDir = OperatingSystemUtils.createTempDir();

    ZipUtil.unzipFromClassResource(WindupUpdateRulesetTest.class, TEST_OLD_WINDUP, tempDir);
    final File targetDir = PathUtil.getWindupHome().resolve("target").toAbsolutePath().toFile();
    final File rulesetsDir = new File(targetDir, "rules");
    FileUtils.deleteDirectory(rulesetsDir);
    FileUtils.moveDirectoryToDirectory(new File(tempDir, "windup-old-ruleset/rules"), targetDir, false);
    System.setProperty(PathUtil.WINDUP_RULESETS_DIR_SYSPROP, rulesetsDir.getAbsolutePath());
    FileUtils.deleteDirectory(tempDir);

    try
    {
        boolean rulesetNeedUpdate = this.updater.rulesetsNeedUpdate(true);
        Assert.assertTrue("Rulesets should need an update.", rulesetNeedUpdate);
        updater.replaceRulesetsDirectoryWithLatestReleaseIfAny();
        Assert.assertFalse("Rulesets should not need an update.", this.updater.rulesetsNeedUpdate(true));
    }
    catch (Throwable ex)
    {
        if (ex.getClass().getSimpleName().equals("InvocationTargetException"))
        {
            final Throwable wrappedEx = ((InvocationTargetException) ex).getTargetException();
            throw new RuntimeException(wrappedEx.getClass().getSimpleName() + " " + wrappedEx.getMessage(), wrappedEx);
        }
        else
            throw ex;
    }
    finally
    {
        System.getProperties().remove("windup.home");
    }
}
 
Example 12
Source File: DistributionUpdater.java    From windup with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Downloads the given artifact, extracts it and replaces current Windup directory (as given by PathUtil)
 * with the content from the artifact (assuming it really is a Windup distribution zip).
 */
public void replaceWindupDirectoryWithDistribution(Coordinate distCoordinate)
        throws WindupException
{
    try
    {
        final CoordinateBuilder coord = CoordinateBuilder.create(distCoordinate);
        File tempFolder = OperatingSystemUtils.createTempDir();
        this.updater.extractArtifact(coord, tempFolder);

        File newDistWindupDir = getWindupDistributionSubdir(tempFolder);

        if (null == newDistWindupDir)
            throw new WindupException("Distribution update failed: "
                + "The distribution archive did not contain the windup-distribution-* directory: " + coord.toString());


        Path addonsDir = PathUtil.getWindupAddonsDir();
        Path binDir = PathUtil.getWindupHome().resolve(PathUtil.BINARY_DIRECTORY_NAME);
        Path libDir = PathUtil.getWindupHome().resolve(PathUtil.LIBRARY_DIRECTORY_NAME);

        FileUtils.deleteDirectory(addonsDir.toFile());
        FileUtils.deleteDirectory(libDir.toFile());
        FileUtils.deleteDirectory(binDir.toFile());

        FileUtils.moveDirectory(new File(newDistWindupDir, PathUtil.ADDONS_DIRECTORY_NAME), addonsDir.toFile());
        FileUtils.moveDirectory(new File(newDistWindupDir, PathUtil.BINARY_DIRECTORY_NAME), binDir.toFile());
        FileUtils.moveDirectory(new File(newDistWindupDir, PathUtil.LIBRARY_DIRECTORY_NAME), libDir.toFile());

        // Rulesets
        Path rulesDir = PathUtil.getWindupHome().resolve(PathUtil.RULES_DIRECTORY_NAME); //PathUtil.getWindupRulesDir();
        File coreDir = rulesDir.resolve(RulesetsUpdater.RULESET_CORE_DIRECTORY).toFile();

        // This is for testing purposes. The releases do not contain migration-core/ .
        if (coreDir.exists())
        {
            // migration-core/ exists -> Only replace that one.
            FileUtils.deleteDirectory(coreDir);
            final File coreDirNew = newDistWindupDir.toPath().resolve(PathUtil.RULES_DIRECTORY_NAME).resolve(RulesetsUpdater.RULESET_CORE_DIRECTORY).toFile();
            FileUtils.moveDirectory(coreDirNew, rulesDir.resolve(RulesetsUpdater.RULESET_CORE_DIRECTORY).toFile());
        }
        else
        {
            // Otherwise replace the whole rules directory (backing up the old one).
            final String newName = "rules-" + new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date());
            FileUtils.moveDirectory(rulesDir.toFile(), rulesDir.getParent().resolve(newName).toFile());
            FileUtils.moveDirectory(new File(newDistWindupDir, PathUtil.RULES_DIRECTORY_NAME), rulesDir.toFile());
        }

        FileUtils.deleteDirectory(tempFolder);
    }
    catch (IllegalStateException | DependencyException | IOException ex)
    {
        throw new WindupException("Distribution update failed: " + ex.getMessage(), ex);
    }
}
 
Example 13
Source File: WindupUpdateDistributionCommandTest.java    From windup with Eclipse Public License 1.0 4 votes vote down vote up
@Test
@Ignore("The current implementation doesn't work as it tampers with addons loaded at the time."
            + " Even if it replaced all Windup addons, it would still fail on Windows as they keep the .jar's locked.")
public void testUpdateDistribution() throws Exception
{
    // Download and unzip an old distribution.
    final CoordinateBuilder coords = CoordinateBuilder.create()
                .setGroupId("org.jboss.windup")
                .setArtifactId("windup-distribution")
                .setClassifier("offline")
                .setVersion("2.2.0.Final")
                .setPackaging("zip");
    System.out.println("Downloading " + coords + ", may take a while.");
    List<Coordinate> results = resolver.resolveVersions(DependencyQueryBuilder.create(coords));

    File windupDir = OperatingSystemUtils.createTempDir();
    this.updater.extractArtifact(results.get(0), windupDir);
    windupDir = DistributionUpdater.getWindupDistributionSubdir(windupDir);
    Assert.assertTrue(windupDir.exists());
    System.setProperty(PathUtil.WINDUP_HOME, windupDir.getAbsolutePath());

    // Run the upgrader.
    distUpdater.replaceWindupDirectoryWithLatestDistribution();

    // Check the new version.
    String newUiVersion = getInstalledAddonVersion(windupDir.toPath().resolve("addons").toString(), WINDUP_UI_ADDON_NAME);
    Assert.assertTrue(SingleVersion.valueOf(newUiVersion).compareTo(SingleVersion.valueOf("2.2.0.Final")) > 0);

    // Try to run Windup from there.
    // TODO: I need to set the harness addons directory to the freshly created dir.
    UITestHarness harness = furnace.getAddonRegistry().getServices(UITestHarness.class).get();
    try (CommandController controller = harness.createCommandController(WindupCommand.class))
    {
        controller.initialize();
        controller.setValueFor(InputPathOption.NAME, Collections.singletonList(new File("src/test/resources/test.jar").getAbsolutePath()));
        final File resultDir = new File("target/testRunFromUpgraded");
        resultDir.mkdirs();
        controller.setValueFor(OutputPathOption.NAME, resultDir.getAbsolutePath());

        Result result = controller.execute();
        Assert.assertTrue(result.getMessage(), !(result instanceof Failed));
    }
    catch (Throwable ex)
    {
        throw new WindupException("Failed running Windup from the upgraded directory: " + ex.getMessage(), ex);
    }
}
 
Example 14
Source File: WindupUpdateDistributionCommandTest.java    From windup with Eclipse Public License 1.0 4 votes vote down vote up
@Test
@Ignore("Completely broken now. New Furnace doesn't deal well with setting windup.home like this.")
public void testUpdateDistributionCommand() throws Exception
{

    // Unzip the rulesets from a .zip in resources.

    File tempDir = OperatingSystemUtils.createTempDir();
    tempDir.deleteOnExit();
    File extractedPath = new File(tempDir, "extracted-rulesets");
    ZipUtil.unzipFromClassResource(getClass(), WindupUpdateDistributionCommandTest.TEST_RULESET_ZIP, extractedPath);

    String windupDir = extractedPath + "/windup-old-ruleset";
    System.setProperty(PathUtil.WINDUP_RULESETS_DIR_SYSPROP, windupDir);
    File addonsDir = new File(windupDir, "addons");
    addonsDir.mkdirs();

    String currentUiVersion = getInstalledAddonVersion(addon.getRepository().getRootDirectory().getPath(), WINDUP_UI_ADDON_NAME);
    installOldAddonVersion(currentUiVersion); // changeUiAddonVersion(addon.getRepository().getRootDirectory(),
                                              // currentUiVersion);
    waitForOldWindupUIAddon(furnace);

    boolean rulesetNeedUpdate = updater.rulesetsNeedUpdate(true);
    Assert.assertTrue(rulesetNeedUpdate);
    try (CommandController controller = uiTestHarness.createCommandController("Windup Update Distribution"))
    {
        try
        {
            controller.initialize();
            Assert.assertTrue(controller.isEnabled());
            // Actually runs the command.
            Result result = controller.execute();
            Assert.assertFalse("Windup Update Distribution command should suceed, but it failed.", result instanceof Failed);
            rulesetNeedUpdate = updater.rulesetsNeedUpdate(true);
            Assert.assertFalse("Ruleset should have already been updated to the latest version and as such should not need another update.",
                        rulesetNeedUpdate);

            checkWindupDirectory(windupDir);
        }
        finally
        {
            FileUtils.deleteDirectory(tempDir);
        }
    }
}
 
Example 15
Source File: WindupCommandTest.java    From windup with Eclipse Public License 1.0 4 votes vote down vote up
@Test
public void testOutputDirCannotBeParentOfInputDir() throws Exception
{
    try (CommandController controller = uiTestHarness.createCommandController(WindupCommand.class))
    {
        File tempDir = OperatingSystemUtils.createTempDir();
        File inputFile = File.createTempFile("windupwizardtest", ".jar", tempDir);
        inputFile.deleteOnExit();
        try (InputStream iStream = getClass().getResourceAsStream("/test.jar"))
        {
            try (OutputStream oStream = new FileOutputStream(inputFile))
            {
                IOUtils.copy(iStream, oStream);
            }
        }

        try
        {
            controller.initialize();
            Assert.assertTrue(controller.isEnabled());
            controller.setValueFor(TargetOption.NAME, Collections.singletonList("eap"));
            controller.setValueFor(InputPathOption.NAME, Collections.singletonList(inputFile));
            Assert.assertTrue(controller.canExecute());
            controller.setValueFor(OutputPathOption.NAME, tempDir);
            Assert.assertFalse(controller.canExecute());
            List<UIMessage> messages = controller.validate();
            boolean validationFound = false;
            for (UIMessage message : messages)
            {
                if (message.getDescription().equals("Output path must not be a parent of input path."))
                {
                    validationFound = true;
                    break;
                }
            }
            Assert.assertTrue(validationFound);
            controller.setValueFor(OutputPathOption.NAME, null);
            Assert.assertTrue(controller.canExecute());
            controller.setValueFor(OverwriteOption.NAME, true);
        }
        finally
        {
            FileUtils.deleteDirectory(tempDir);
        }
    }
}