org.apache.maven.shared.utils.io.FileUtils Java Examples

The following examples show how to use org.apache.maven.shared.utils.io.FileUtils. 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: DockerAssemblyManager.java    From docker-maven-plugin with Apache License 2.0 6 votes vote down vote up
public File createChangedFilesArchive(List<AssemblyFiles.Entry> entries, File assemblyDirectory,
                                      String imageName, MojoParameters mojoParameters)
        throws MojoExecutionException {
    BuildDirs dirs = createBuildDirs(imageName, mojoParameters);
    try {
        File archive = new File(dirs.getTemporaryRootDirectory(), "changed-files.tar");
        File archiveDir = createArchiveDir(dirs);
        for (AssemblyFiles.Entry entry : entries) {
            File dest = prepareChangedFilesArchivePath(archiveDir,entry.getDestFile(),assemblyDirectory);
            FileUtils.copyFile(entry.getSrcFile(), dest);
        }
        return createChangedFilesTarBall(archive, archiveDir);
    } catch (IOException exp) {
        throw new MojoExecutionException("Error while creating " + dirs.getTemporaryRootDirectory() +
                                         "/changed-files.tar: " + exp);
    }
}
 
Example #2
Source File: EnvUtil.java    From docker-maven-plugin with Apache License 2.0 6 votes vote down vote up
public static void storeTimestamp(File tsFile, Date buildDate) throws MojoExecutionException {
    try {
        if (tsFile.exists()) {
            tsFile.delete();
        }
        File dir = tsFile.getParentFile();
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                throw new MojoExecutionException("Cannot create directory " + dir);
            }
        }
        FileUtils.fileWrite(tsFile, StandardCharsets.US_ASCII.name(), Long.toString(buildDate.getTime()));
    } catch (IOException e) {
        throw new MojoExecutionException("Cannot create " + tsFile + " for storing time " + buildDate.getTime(),e);
    }
}
 
Example #3
Source File: BaseDevTest.java    From ci.maven with Apache License 2.0 5 votes vote down vote up
protected static void cleanUpAfterClass(boolean isDevMode) throws Exception {
   stopProcess(isDevMode);

   if (tempProj != null && tempProj.exists()) {
      FileUtils.deleteDirectory(tempProj);
   }

   if (logFile != null && logFile.exists()) {
      assertTrue(logFile.delete());
   }
}
 
Example #4
Source File: XtendCompilerMojoIT.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
public void assertFileContainsUTF16(Verifier verifier, String file, String contained) {
	verifier.assertFilePresent(file);
	try {
		String content = FileUtils.fileRead(new File(file), "UTF-16");
		if (!content.contains(contained)) {
			Assert.fail("Content of " + file + " does not contain " + contained + " but: " + content);
		}
	} catch (IOException e) {
		Assert.fail(e.getMessage());
	}
}
 
Example #5
Source File: DefaultLogCallbackTest.java    From docker-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldLogInParallel() throws IOException, DoneException, InterruptedException {
    DefaultLogCallback callback2 = new DefaultLogCallback(spec);
    callback2.open();

    ExecutorService executorService = Executors.newFixedThreadPool(2);
    LoggerTask task1 = new LoggerTask(callback, 1);
    LoggerTask task2 = new LoggerTask(callback2, 1 + NR_LOOPS);
    executorService.submit(task1);
    executorService.submit(task2);
    executorService.awaitTermination(1, TimeUnit.SECONDS);

    List<String> lines = Arrays.asList(FileUtils.fileReadArray(file));
    //System.out.println(lines);
    assertThat(lines.size(), is(NR_LOOPS * 2));

    // fill set with expected line numbers
    Set<Integer> indexes = new HashSet<>();
    for (int i = 1; i <= 2 * NR_LOOPS; i++) {
        indexes.add(i);
    }

    // remove found line numbers from set
    for (String line : lines) {
        String prefix = "callback-test> line ";
        assertThat(line, startsWith(prefix));
        String suffix = line.substring(prefix.length());
        indexes.remove(Integer.parseInt(suffix));
    }

    // expect empty set
    assertThat(indexes, is(empty()));
}
 
Example #6
Source File: DefaultLogCallbackTest.java    From docker-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldKeepStreamOpen() throws IOException, DoneException {
    DefaultLogCallback callback2 = new DefaultLogCallback(spec);
    callback2.open();
    callback.log(1, ts, "line 1");
    callback2.log(1, ts, "line 2");
    callback.log(1, ts, "line 3");
    callback.close();
    callback2.log(1, ts, "line 4");
    callback2.close();

    List<String> lines = Arrays.asList(FileUtils.fileReadArray(file));
    assertThat(lines,
            contains("callback-test> line 1", "callback-test> line 2", "callback-test> line 3", "callback-test> line 4"));
}
 
Example #7
Source File: DefaultLogCallbackTest.java    From docker-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldLogToStdout() throws IOException, DoneException {
    // we don't need the default stream for this test
    callback.close();

    file = File.createTempFile("logcallback-stdout", ".log");
    file.deleteOnExit();
    FileOutputStream os = new FileOutputStream(file);
    PrintStream ps = new PrintStream(os);
    PrintStream stdout = System.out;
    try {
        System.setOut(ps);
        spec = new LogOutputSpec.Builder().prefix("stdout> ")
                .build();
        callback = new DefaultLogCallback(spec);
        callback.open();
        DefaultLogCallback callback2 = new DefaultLogCallback(spec);
        callback2.open();

        callback.log(1, ts, "line 1");
        callback2.log(1, ts, "line 2");
        callback.log(1, ts, "line 3");
        callback.close();
        callback2.log(1, ts, "line 4");
        callback2.close();

        List<String> lines = Arrays.asList(FileUtils.fileReadArray(file));
        assertThat(lines, contains("stdout> line 1", "stdout> line 2", "stdout> line 3", "stdout> line 4"));
    } finally {
        System.setOut(stdout);
    }
}
 
Example #8
Source File: DefaultLogCallbackTest.java    From docker-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldLogError() throws IOException, DoneException {
    callback.error("error 1");
    callback.log(1, ts, "line 2");
    callback.error("error 3");
    callback.close();

    List<String> lines = Arrays.asList(FileUtils.fileReadArray(file));
    assertThat(lines, contains("error 1", "callback-test> line 2", "error 3"));
}
 
Example #9
Source File: DefaultLogCallbackTest.java    From docker-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldLogSequentially() throws IOException, DoneException {
    callback.log(1, ts, "line 1");
    callback.log(1, ts, "line 2");
    callback.close();

    List<String> lines = Arrays.asList(FileUtils.fileReadArray(file));
    assertThat(lines, contains("callback-test> line 1", "callback-test> line 2"));
}
 
Example #10
Source File: EnvUtil.java    From docker-maven-plugin with Apache License 2.0 5 votes vote down vote up
public static Date loadTimestamp(File tsFile) throws IOException {
    try {
        if (tsFile.exists()) {
            String ts = FileUtils.fileRead(tsFile);
            return new Date(Long.parseLong(ts));
        } else {
            return null;
        }
    } catch (IOException e) {
        throw new IOException("Cannot read timestamp " + tsFile,e);
    }
}
 
Example #11
Source File: DockerAssemblyManager.java    From docker-maven-plugin with Apache License 2.0 5 votes vote down vote up
private File createArchiveDir(BuildDirs dirs) throws IOException, MojoExecutionException {
    File archiveDir = new File(dirs.getTemporaryRootDirectory(), "changed-files");
    if (archiveDir.exists()) {
        // Remove old stuff to
        FileUtils.cleanDirectory(archiveDir);
    } else {
        if (!archiveDir.mkdir()) {
            throw new MojoExecutionException("Cannot create " + archiveDir);
        }
    }
    return archiveDir;
}
 
Example #12
Source File: DockerAssemblyManager.java    From docker-maven-plugin with Apache License 2.0 5 votes vote down vote up
private void addDockerIncludes(DefaultFileSet fileSet) throws IOException {
    File directory = fileSet.getDirectory();
    File dockerInclude = new File(directory, DOCKER_INCLUDE);
    if (dockerInclude.exists()) {
        ArrayList<String> includes = new ArrayList<>(Arrays.asList(FileUtils.fileReadArray(dockerInclude)));
        fileSet.setIncludes(includes.toArray(new String[0]));
    }
}
 
Example #13
Source File: DockerAssemblyManager.java    From docker-maven-plugin with Apache License 2.0 5 votes vote down vote up
private void addDockerExcludes(DefaultFileSet fileSet, MojoParameters params) throws IOException {
    File directory = fileSet.getDirectory();
    List<String> excludes = new ArrayList<>();
    // Output directory will be always excluded
    excludes.add(params.getOutputDirectory() + "/**");
    for (String file : new String[] { DOCKER_EXCLUDE, DOCKER_IGNORE } ) {
        File dockerIgnore = new File(directory, file);
        if (dockerIgnore.exists()) {
            excludes.addAll(Arrays.asList(FileUtils.fileReadArray(dockerIgnore)));
            excludes.add(DOCKER_IGNORE);
        }
    }
    fileSet.setExcludes(excludes.toArray(new String[0]));
}
 
Example #14
Source File: AbstractMojoTest.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Execute a Mojo.
 *
 * @param projectName the name of the project to test for the unit test.
 * @param goalName the goal to run.
 * @return the verifier.
 * @throws Exception any exception.
 */
protected Verifier executeMojo(String projectName, String goalName) throws Exception {
	String tempDirPath = System.getProperty("maven.test.tmpdir", //$NON-NLS-1$
			System.getProperty("java.io.tmpdir")); //$NON-NLS-1$
	File tempDir = new File(tempDirPath);
	File baseDir = new File(tempDir, projectName);
	assertNotNull(baseDir);

	FileUtils.deleteDirectory(baseDir);

	URL url = getClass().getResource("/projects/" + projectName); //$NON-NLS-1$
	if (url == null) {
		throw new IllegalArgumentException("Resource not found: " + projectName); //$NON-NLS-1$
	}
	File resourceFile = new File(new URI(url.toExternalForm()));
	assertTrue(resourceFile.isDirectory());
	FileUtils.copyDirectoryStructure(resourceFile, baseDir);

	assertTrue(baseDir.exists());
	assertTrue(baseDir.isDirectory());

	recursiveDeleteOnShutdownHook(baseDir);

	Verifier verifier = new Verifier(baseDir.getAbsolutePath());
	verifier.setAutoclean(false);
	verifier.setDebug(false);
	final String m2home = findDefaultMavenHome();
	if (m2home != null && !m2home.isEmpty()) {
		verifier.setForkJvm(false);
		verifier.getSystemProperties().put("maven.multiModuleProjectDirectory", m2home); //$NON-NLS-1$
		verifier.getVerifierProperties().put("use.mavenRepoLocal", Boolean.FALSE.toString()); //$NON-NLS-1$
	}
	verifier.executeGoals(Arrays.asList("clean", goalName)); //$NON-NLS-1$
	return verifier;
}
 
Example #15
Source File: AbstractMojoTest.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Recursive deletion of a folder when the VM is exiting.
 *
 * @param path the path of the folder to delete.
 */
protected static void recursiveDeleteOnShutdownHook(final File path) {
	Runtime.getRuntime().addShutdownHook(new Thread(
			new Runnable() {
				@Override
				public void run() {
					try {
						FileUtils.deleteDirectory(path);
					} catch (IOException e) {
						throw new RuntimeException("Failed to delete " + path, e); //$NON-NLS-1$
					}
				}}));
}
 
Example #16
Source File: DownstreamParentTest.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
/** Replicates the behaviour of getBasedir in JUnit's TestResources class */
public File getBasedir(String project) throws IOException {
    File src = (new File(PROJECTS_DIR, project)).getCanonicalFile();
    assertTrue(src.isDirectory(), "Test project directory does not exist: " + src.getPath());
    File basedir = (new File(WORK_DIR, getClass().getSimpleName() + "_" + project)).getCanonicalFile();
    FileUtils.deleteDirectory(basedir);
    assertTrue(basedir.mkdirs(), "Test project working directory created");
    FileUtils.copyDirectoryStructure(src, basedir);
    return basedir;
}
 
Example #17
Source File: XtendCompilerMojoIT.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
public void assertFileDoesNotContain(Verifier verifier, String file, String contained) {
	verifier.assertFilePresent(file);
	try {
		String content = FileUtils.fileRead(new File(file), "UTF-8");
		if (content.contains(contained)) {
			Assert.fail("Content of " + file + " does contain " + contained + ", but it should not. Contents: " + content);
		}
	} catch (IOException e) {
		Assert.fail(e.getMessage());
	}
}
 
Example #18
Source File: Bug504Test.java    From sarl with Apache License 2.0 4 votes vote down vote up
@Test
public void compile() throws Exception {
	Verifier verifier = executeMojo("bug504", "compile");
	Path path = FileSystems.getDefault().getPath(
			"src", "main", "generated-sources", "sarl",
			"io", "sarl", "elevatorsim", "SimulatorInteraction.java");
	assertNotNull(path);
	verifier.assertFilePresent(path.toString());
	File file = new File(verifier.getBasedir(), path.toString());
	String fileContent = FileUtils.fileRead(file);
	assertEquals(multilineString(
			"package io.sarl.elevatorsim;",
			"",
			"import io.sarl.elevatorsim.SimulatorPush;",
			"import io.sarl.elevatorsim.events.SendCarAction;",
			"import io.sarl.lang.annotation.SarlElementType;",
			"import io.sarl.lang.annotation.SarlSpecification;",
			"import io.sarl.lang.annotation.SyntheticMember;",
			"import io.sarl.lang.core.Agent;",
			"import io.sarl.lang.core.Skill;",
			"import java.io.IOException;",
			"import org.eclipse.xtext.xbase.lib.Exceptions;",
			"",
			"@SarlSpecification(\"" + SARLVersion.SPECIFICATION_RELEASE_VERSION_STRING + "\")",
			"@SarlElementType(" + SarlPackage.SARL_SKILL + ")",
			"@SuppressWarnings(\"all\")",
			"public class SimulatorInteraction extends Skill implements SimulatorPush {",
			"  public void sendCar(final int a, final int b, final int c, final Object d, final Object e) {",
			"  }",
			"  ",
			"  @Override",
			"  public void pushSendCarAction(final SendCarAction action) {",
			"    try {",
			"      this.sendCar(action.car, action.floor, action.nextDirection, ",
			"        null, null);",
			"    } catch (final Throwable _t) {",
			"      if (_t instanceof IOException) {",
			"        final IOException e = (IOException)_t;",
			"        e.printStackTrace();",
			"      } else {",
			"        throw Exceptions.sneakyThrow(_t);",
			"      }",
			"    }",
			"  }",
			"  ",
			"  @SyntheticMember",
			"  public SimulatorInteraction() {",
			"    super();",
			"  }",
			"  ",
			"  @SyntheticMember",
			"  public SimulatorInteraction(final Agent arg0) {",
			"    super(arg0);",
			"  }",
			"}"), fileContent);
}
 
Example #19
Source File: DevTest.java    From ci.maven with Apache License 2.0 4 votes vote down vote up
@Test
public void resolveDependencyTest() throws Exception {      
   assertFalse(checkLogMessage(10000,  "Press the Enter key to run tests on demand."));

   // create the HealthCheck class, expect a compilation error
   File systemHealthRes = new File("../resources/SystemHealth.java");
   assertTrue(systemHealthRes.exists());
   File systemHealthSrc = new File(tempProj, "/src/main/java/com/demo/SystemHealth.java");
   File systemHealthTarget = new File(targetDir, "/classes/com/demo/SystemHealth.class");

   FileUtils.copyFile(systemHealthRes, systemHealthSrc);
   assertTrue(systemHealthSrc.exists());
   
   assertFalse(checkLogMessage(200000, "Source compilation had errors"));
   assertFalse(systemHealthTarget.exists());
   
   // add mpHealth dependency to pom.xml
   String mpHealthComment = "<!-- <dependency>\n" + 
         "        <groupId>io.openliberty.features</groupId>\n" + 
         "        <artifactId>mpHealth-1.0</artifactId>\n" + 
         "        <type>esa</type>\n" + 
         "        <scope>provided</scope>\n" + 
         "    </dependency> -->";
   String mpHealth = "<dependency>\n" + 
         "        <groupId>io.openliberty.features</groupId>\n" + 
         "        <artifactId>mpHealth-1.0</artifactId>\n" + 
         "        <type>esa</type>\n" + 
         "        <scope>provided</scope>\n" + 
         "    </dependency>";
   replaceString(mpHealthComment, mpHealth, pom);
   
   assertFalse(checkLogMessage(100000,"The following features have been installed"));
   
   String str = "// testing";
   BufferedWriter javaWriter = new BufferedWriter(new FileWriter(systemHealthSrc, true));
   javaWriter.append(' ');
   javaWriter.append(str);

   javaWriter.close();

   Thread.sleep(1000); // wait for compilation
   assertFalse(checkLogMessage(100000, "Source compilation was successful."));
   Thread.sleep(15000); // wait for compilation
   assertTrue(systemHealthTarget.exists());
}
 
Example #20
Source File: BaseDevTest.java    From ci.maven with Apache License 2.0 4 votes vote down vote up
protected static void setUpBeforeClass(String params, String projectRoot, boolean isDevMode) throws IOException, InterruptedException, FileNotFoundException {
   basicDevProj = new File(projectRoot);

   tempProj = Files.createTempDirectory("temp").toFile();
   assertTrue(tempProj.exists());

   assertTrue(basicDevProj.exists());

   FileUtils.copyDirectoryStructure(basicDevProj, tempProj);
   assertTrue(tempProj.listFiles().length > 0);

   logFile = new File(basicDevProj, "logFile.txt");
   assertTrue(logFile.createNewFile());

   pom = new File(tempProj, "pom.xml");
   assertTrue(pom.exists());

   replaceVersion();

   startProcess(params, isDevMode);
}