Java Code Examples for org.codehaus.plexus.util.FileUtils

The following examples show how to use org.codehaus.plexus.util.FileUtils. These examples are extracted from open source projects. 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 Project: rice   Source File: ThemeBuilderUtils.java    License: Educational Community License v2.0 6 votes vote down vote up
/**
 * Stores the given properties object in a file named <code>theme-derived.properties</code> within the
 * given theme directory
 *
 * @param themeDirectory directory the properties file should be created in
 * @param themeProperties properties that should be written to the properties file
 * @throws IOException
 */
public static void storeThemeProperties(String themeDirectory, Properties themeProperties) throws IOException {
    File propertiesFile = new File(themeDirectory, ThemeBuilderConstants.THEME_DERIVED_PROPERTIES_FILE);

    // need to remove file if already exists so the new properties will be written
    if (propertiesFile.exists()) {
        FileUtils.forceDelete(propertiesFile);
    }

    FileWriter fileWriter = null;

    try {
        fileWriter = new FileWriter(propertiesFile);

        themeProperties.store(fileWriter, null);
    } finally {
        if (fileWriter != null) {
            fileWriter.close();
        }
    }
}
 
Example 2
Source Project: butterfly   Source File: AddProperty.java    License: MIT License 6 votes vote down vote up
private TOExecutionResult addProperty(File transformedAppFolder, TransformationContext transformationContext) {
    File fileToBeChanged = getAbsoluteFile(transformedAppFolder, transformationContext);
    TOExecutionResult result;
    try {
        String propertyToBeAdded = String.format("%s = %s", propertyName, propertyValue);
        if (fileToBeChanged.length() != 0) {
            FileUtils.fileAppend(fileToBeChanged.getAbsolutePath(), EolHelper.findEolDefaultToOs(fileToBeChanged));
        }
        FileUtils.fileAppend(fileToBeChanged.getAbsolutePath(), propertyToBeAdded);
        String details = String.format("Property '%s' has been added and set to '%s' at '%s'", propertyName, propertyValue, getRelativePath());
        result = TOExecutionResult.success(this, details);
    } catch (IOException e) {
        result = TOExecutionResult.error(this, new TransformationOperationException("Property file could not be modified", e));
    }
    return result;
}
 
Example 3
Source Project: butterfly   Source File: MoveFile.java    License: MIT License 6 votes vote down vote up
@Override
protected TOExecutionResult execution(File transformedAppFolder, TransformationContext transformationContext) {
    File fileFrom = getAbsoluteFile(transformedAppFolder, transformationContext);
    File fileTo = getFileTo(transformedAppFolder, transformationContext);
    TOExecutionResult result;

    // TODO
    // Check if it is really a file and if it exists!

    try {
        if (fileFrom.isDirectory()) {
            IOException ex = new IOException(getRelativePath(transformedAppFolder, fileFrom) + " (Is a directory)");
            result = TOExecutionResult.error(this, new TransformationOperationException("File could not be moved", ex));
        } else {
            String details = String.format("File '%s' has been moved to '%s'", getRelativePath(), getRelativePath(transformedAppFolder, fileTo));
            FileUtils.copyFileToDirectory(fileFrom, fileTo);
            FileUtils.fileDelete(fileFrom.getAbsolutePath());
            result = TOExecutionResult.success(this, details);
        }
    } catch (IOException e) {
        result = TOExecutionResult.error(this, new TransformationOperationException("File could not be moved", e));
    }

    return result;
}
 
Example 4
Source Project: butterfly   Source File: CopyFile.java    License: MIT License 6 votes vote down vote up
@Override
protected TOExecutionResult execution(File transformedAppFolder, TransformationContext transformationContext) {
    // TODO Validation must be done here!!!

    File fileFrom = getAbsoluteFile(transformedAppFolder, transformationContext);
    File fileTo = getFileTo(transformedAppFolder, transformationContext);
    TOExecutionResult result;

    try {
        if (fileFrom.isDirectory()) {
            IOException ex = new IOException(getRelativePath(transformedAppFolder, fileFrom) + " (Is a directory)");
            result = TOExecutionResult.error(this, new TransformationOperationException("File could not be copied", ex));
        } else {
            String details = String.format("File '%s' has been copied to '%s'", getRelativePath(), getRelativePath(transformedAppFolder, fileTo));
            FileUtils.copyFileToDirectory(fileFrom, fileTo);
            result = TOExecutionResult.success(this, details);
        }
    } catch (IOException e) {
        result = TOExecutionResult.error(this, new TransformationOperationException("File could not be copied", e));
    }

    return result;
}
 
Example 5
Source Project: helm-maven-plugin   Source File: AbstractHelmMojo.java    License: MIT License 6 votes vote down vote up
List<String> getChartDirectories(String path) throws MojoExecutionException {
	List<String> exclusions = new ArrayList<>();

	if (getExcludes() != null) {
		exclusions.addAll(Arrays.asList(getExcludes()));
	}

	exclusions.addAll(FileUtils.getDefaultExcludesAsList());

	MatchPatterns exclusionPatterns = MatchPatterns.from(exclusions);

	try (Stream<Path> files = Files.walk(Paths.get(path), FileVisitOption.FOLLOW_LINKS)) {
		List<String> chartDirs = files.filter(p -> p.getFileName().toString().equalsIgnoreCase("chart.yaml"))
				.map(p -> p.getParent().toString())
				.filter(shouldIncludeDirectory(exclusionPatterns))
				.collect(Collectors.toList());

		if (chartDirs.isEmpty()) {
			getLog().warn("No Charts detected - no Chart.yaml files found below " + path);
		}

		return chartDirs;
	} catch (IOException e) {
		throw new MojoExecutionException("Unable to scan chart directory at " + path, e);
	}
}
 
Example 6
Source Project: jaxb2-maven-plugin   Source File: FileSystemUtilities.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Convenience method to successfully create a directory - or throw an exception if failing to create it.
 *
 * @param aDirectory        The directory to create.
 * @param cleanBeforeCreate if {@code true}, the directory and all its content will be deleted before being
 *                          re-created. This will ensure that the created directory is really clean.
 * @throws MojoExecutionException if the aDirectory could not be created (and/or cleaned).
 */
public static void createDirectory(final File aDirectory, final boolean cleanBeforeCreate)
        throws MojoExecutionException {

    // Check sanity
    Validate.notNull(aDirectory, "aDirectory");
    validateFileOrDirectoryName(aDirectory);

    // Clean an existing directory?
    if (cleanBeforeCreate) {
        try {
            FileUtils.deleteDirectory(aDirectory);
        } catch (IOException e) {
            throw new MojoExecutionException("Could not clean directory [" + getCanonicalPath(aDirectory) + "]", e);
        }
    }

    // Now, make the required directory, if it does not already exist as a directory.
    final boolean existsAsFile = aDirectory.exists() && aDirectory.isFile();
    if (existsAsFile) {
        throw new MojoExecutionException("[" + getCanonicalPath(aDirectory) + "] exists and is a file. "
                + "Cannot make directory");
    } else if (!aDirectory.exists() && !aDirectory.mkdirs()) {
        throw new MojoExecutionException("Could not create directory [" + getCanonicalPath(aDirectory) + "]");
    }
}
 
Example 7
Source Project: appassembler   Source File: AbstractAppAssemblerMojo.java    License: MIT License 6 votes vote down vote up
protected void removeDirectory( File directory )
    throws MojoExecutionException
{
    if ( directory.exists() )
    {
        try
        {
            this.getLog().info( "Removing " + directory );
            FileUtils.deleteDirectory( directory );
        }
        catch ( IOException e )
        {
            throw new MojoExecutionException( e.getMessage(), e );
        }
    }
}
 
Example 8
Source Project: emodb   Source File: EmoStartMojo.java    License: Apache License 2.0 6 votes vote down vote up
private void copyEmoServiceArtifactToWorkingDirectory() throws MojoExecutionException, MojoFailureException {
    // NOTE: this emo service artifact is an "uberjar" created by the maven-shade-plugin
    final ArtifactItem emoServiceArtifact = new ArtifactItem();
    emoServiceArtifact.setGroupId("com.bazaarvoice.emodb");
    emoServiceArtifact.setArtifactId("emodb-web");
    emoServiceArtifact.setVersion(pluginVersion());

    resolveArtifactItems(asList(emoServiceArtifact));
    final File emoServiceJar = emoServiceArtifact.getResolvedArtifact().getArtifact().getFile();
    try {
        // copy to "emodb.jar" so that we always overwrite any prior
        FileUtils.copyFile(emoServiceJar, new File(emoProcessWorkingDirectory(), "emodb.jar"));
    } catch (IOException e) {
        throw new MojoFailureException("failed to copy: " + emoServiceArtifact, e);
    }
}
 
Example 9
public void testGenerationWithChkConfig()
    throws Exception
{
    runTest( "jsw", "src/test/resources/project-12/pom.xml", "src/test/resources/project-12/descriptor.xml",
             "target/output-12-jsw" );

    File jswDir = getTestFile( "target/output-12-jsw/app" );
    File wrapper = new File( jswDir, "conf/wrapper.conf" );

    String wrapperContents = FileUtils.fileRead( wrapper );

    assertFalse( "Wrapper conf contains chkconfig.start", wrapperContents.contains( "chkconfig.start" ) );
    assertFalse( "Wrapper conf contains chkconfig.stop", wrapperContents.contains( "chkconfig.stop" ) );

    File script = new File( jswDir, "bin/app" );
    String scriptContents = FileUtils.fileRead( script );

    assertTrue( "Chkconfig replace did not work", scriptContents.contains( "chkconfig: 3 21 81" ) );
}
 
Example 10
Source Project: aspectj-maven-plugin   Source File: AjcHelper.java    License: MIT License 6 votes vote down vote up
/**
 * Based on a set of weavedirs returns a set of all the files to be weaved.
 *
 * @return
 * @throws MojoExecutionException
 */
public static Set<String> getWeaveSourceFiles( String[] weaveDirs )
    throws MojoExecutionException
{
    Set<String> result = new HashSet<String>();

    for ( int i = 0; i < weaveDirs.length; i++ )
    {
        String weaveDir = weaveDirs[i];
        if ( FileUtils.fileExists( weaveDir ) )
        {
            try
            {
                result.addAll( FileUtils.getFileNames( new File( weaveDir ), "**/*.class", DEFAULT_EXCLUDES, true ) );
            }
            catch ( IOException e )
            {
                throw new MojoExecutionException( "IO Error resolving weavedirs", e );
            }
        }
    }
    return result;
}
 
Example 11
Source Project: tcases   Source File: ApiTestMojoTest.java    License: MIT License 6 votes vote down vote up
/**
 * Clean configured output directory.
 */
private void clean( ApiTestMojo apiMojo)
  {
  File outDir = apiMojo.getOutDirFile();
  if( outDir.exists())
    {
    try
      {
      FileUtils.cleanDirectory( outDir);
      }
    catch( Exception e)
      {
      throw new RuntimeException( "Can't clear outDir=" + outDir, e);
      }
    }
  }
 
Example 12
Source Project: xml-maven-plugin   Source File: TransformMojoTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Builds the it7 test project.
 * @throws Exception The test failed.
 */
public void testIt7()
    throws Exception
{
    final File dir = new File( "src/test/it7" );
    final File target = new File( dir, "target/generated-resources/xml/xslt/doc1.xml" );
    TransformMojo mojo = (TransformMojo) newMojo( dir.getPath() );
    FileUtils.fileDelete( target.getPath() );
    mojo.execute();
    String result = read( target );
    assertFalse( result.startsWith( "<?xml" ) );
    mojo = (TransformMojo) newMojo( "src/test/it7" );
    TransformationSet[] transformationSets =
        (TransformationSet[]) getVariableValueFromObject( mojo, "transformationSets" );
    transformationSets[0].getOutputProperties()[0].setValue( "no" );
    FileUtils.fileDelete( target.getPath() );
    mojo.execute();
    result = read( target );
    assertTrue( result.startsWith( "<?xml" ) );
}
 
Example 13
Source Project: ci.maven   Source File: PluginConfigXmlIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testBootstrapPropertiesFileElements() throws Exception {
    File in = new File(CONFIG_XML);
    FileInputStream input = new FileInputStream(in);
    
    // get input XML Document
    DocumentBuilderFactory inputBuilderFactory = DocumentBuilderFactory.newInstance();
    inputBuilderFactory.setIgnoringComments(true);
    inputBuilderFactory.setCoalescing(true);
    inputBuilderFactory.setIgnoringElementContentWhitespace(true);
    inputBuilderFactory.setValidating(false);
    DocumentBuilder inputBuilder = inputBuilderFactory.newDocumentBuilder();
    Document inputDoc = inputBuilder.parse(input);
    
    // parse input XML Document
    XPath xPath = XPathFactory.newInstance().newXPath();
    String expression = "/liberty-plugin-config/bootstrapPropertiesFile/text()";
    String nodeValue = (String) xPath.compile(expression).evaluate(inputDoc, XPathConstants.STRING);
    File f1 = new File(SOURCE_BOOTSTRAP_PROPERTIES);
    File f2 = new File(nodeValue);
    assertEquals("bootstrapPropertiesFile value", f1.getAbsolutePath(), f2.getAbsolutePath());
    assertEquals("verify target server bootstrap.properties", FileUtils.fileRead(f2),
            FileUtils.fileRead(TARGET_BOOTSTRAP_PROPERTIES));
}
 
Example 14
Source Project: tomee   Source File: MonkeyTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void run() throws Exception {
    final File tomee = prepareProject();
    try {
        invoke(tomee); // invalid, should fail
    } catch (final ClassFormatError cfe) {
        // ok, we created an invalid jar
    }

    new Monkey(tomee).run();
    final File[] libs = new File(tomee, "lib").listFiles(new FilenameFilter() {
        @Override
        public boolean accept(final File dir, final String name) {
            return name.endsWith(".jar");
        }
    });
    assertEquals(1, libs.length);
    final File jar = libs[0];
    assertTrue(jar.getName().contains("tomee-monkey-"));
    assertEquals(2, invoke(tomee));

    FileUtils.deleteDirectory(tomee.getParentFile().getParentFile());
}
 
Example 15
Source Project: buildnumber-maven-plugin   Source File: BuildNumberMojoTest.java    License: MIT License 6 votes vote down vote up
@Test
public void basicItSvnJavaTest()
    throws Exception
{
    Assume.assumeTrue( isSvn18() );

    File projDir = resources.getBasedir( "basic-it-svnjava" );

    MavenExecution mavenExec = maven.forProject( projDir );
    MavenExecutionResult result = mavenExec.execute( "clean" );
    result.assertErrorFreeLog();
    File testDir = result.getBasedir();
    FileUtils.copyDirectoryStructure( new File( testDir, "dotSvnDir" ), new File( testDir, ".svn" ) );
    result = mavenExec.execute( "clean", "verify" );
    result.assertLogText( "Storing buildNumber: 19665" );
    result.assertLogText( "Storing buildScmBranch: trunk" );

    File artifact = new File( testDir, "target/buildnumber-maven-plugin-basic-it-svnjava-1.0-SNAPSHOT.jar" );
    JarFile jarFile = new JarFile( artifact );
    Attributes manifest = jarFile.getManifest().getMainAttributes();
    jarFile.close();
    String scmRev = manifest.getValue( "SCM-Revision" );
    Assert.assertEquals( "19665", scmRev );
}
 
Example 16
Source Project: maven-native   Source File: NativeLinkMojo.java    License: MIT License 6 votes vote down vote up
private List<String> getLibFileNames()
    throws MojoExecutionException
{
    List<String> libList = new ArrayList<>();

    Set<Artifact> artifacts = this.project.getArtifacts();

    for ( Iterator<Artifact> iter = artifacts.iterator(); iter.hasNext(); )
    {
        Artifact artifact = iter.next();

        if ( INCZIP_TYPE.equals( artifact.getType() ) )
        {
            continue;
        }

        String libFileName = FileUtils.filename( this.getDependencyFile( artifact, true ).getPath() );

        libList.add( libFileName );
    }

    libList = this.reorderLibDependencies( libList );

    return libList;
}
 
Example 17
Source Project: aspectj-maven-plugin   Source File: AjcHelper.java    License: MIT License 6 votes vote down vote up
/**
 * Reads a build config file, and returns the List of all compiler arguments.
 *
 * @param fileName the filename of the argfile
 * @param outputDir the build output area
 * @return
 * @throws IOException
 */
public static List<String> readBuildConfigFile( String fileName, File outputDir )
    throws IOException
{
    List<String> arguments = new ArrayList<String>();
    File argFile = new File( outputDir, fileName );
    if ( FileUtils.fileExists( argFile.getAbsolutePath() ) )
    {
        FileReader reader = new FileReader( argFile );
        BufferedReader bufRead = new BufferedReader( reader );
        String line = null;
        do
        {
            line = bufRead.readLine();
            if ( null != line )
            {
                arguments.add( line );
            }
        }
        while ( null != line );
    }
    return arguments;
}
 
Example 18
Source Project: maven-native   Source File: NativeLinkMojo.java    License: MIT License 6 votes vote down vote up
private File getDependencyFile( Artifact artifact, boolean doCopy )
    throws MojoExecutionException
{

    File newLocation = new File( this.externalLibDirectory,
            artifact.getArtifactId() + "." + artifact.getArtifactHandler().getExtension() );

    try
    {
        if ( doCopy && !artifact.getFile().isDirectory()
                && ( !newLocation.exists() || newLocation.lastModified() <= artifact.getFile().lastModified() ) )
        {
            FileUtils.copyFile( artifact.getFile(), newLocation );
        }
    }
    catch ( IOException ioe )
    {
        throw new MojoExecutionException( "Unable to copy dependency to staging area.  Could not copy "
                + artifact.getFile() + " to " + newLocation, ioe );
    }

    return newLocation;
}
 
Example 19
Source Project: flow   Source File: PrepareFrontendMojoTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void writeTokenFile_devModePropertiesAreWritten()
        throws IOException, MojoExecutionException, MojoFailureException {

    mojo.execute();

    String json = org.apache.commons.io.FileUtils
            .readFileToString(tokenFile, StandardCharsets.UTF_8);
    JsonObject buildInfo = JsonUtil.parse(json);

    Assert.assertTrue(
            Constants.SERVLET_PARAMETER_ENABLE_PNPM
                    + "should have been written",
            buildInfo.getBoolean(Constants.SERVLET_PARAMETER_ENABLE_PNPM));
    Assert.assertTrue(
            Constants.REQUIRE_HOME_NODE_EXECUTABLE
                    + "should have been written",
            buildInfo.getBoolean(Constants.REQUIRE_HOME_NODE_EXECUTABLE));

    Assert.assertFalse(buildInfo
            .hasKey(Constants.SERVLET_PARAMETER_DEVMODE_OPTIMIZE_BUNDLE));
}
 
Example 20
Source Project: appassembler   Source File: ScriptGeneratorBackgroundTest.java    License: MIT License 6 votes vote down vote up
private void testShellScriptGenerationWithFalseShowConsoleWindow( Platform platform )
    throws Exception
{
    ScriptGenerator generator = (ScriptGenerator) lookup( ScriptGenerator.ROLE );

    Daemon daemon = new Daemon();

    daemon.setShowConsoleWindow( false );
    daemon.setId( "test" );
    daemon.setMainClass( "foo.Bar" );
    daemon.setJvmSettings( new JvmSettings() );
    daemon.getJvmSettings().setExtraArguments( Arrays.asList( new String[] { "Yo", "dude" } ) );
    daemon.setEnvironmentSetupFileName( "setup" );
    daemon.setRepositoryName( "repo" );
    File outputDirectory = getTestFile( "target/test-output/background-shell/" + platform.getName() );

    generator.createBinScript( platform.getName(), daemon, outputDirectory, "bin" );

    File expectedFile =
        getTestFile( PREFIX + "expected-false-showConsoleWindow-" + daemon.getId() + platform.getBinFileExtension() );
    File actualFile = new File( outputDirectory, "bin/" + daemon.getId() + platform.getBinFileExtension() );

    assertEquals( FileUtils.fileRead( expectedFile ), FileUtils.fileRead( actualFile ) );
}
 
Example 21
protected void setupDirectories() {

		final File generateDirectory = getGenerateDirectory();
		if (getRemoveOldOutput() && generateDirectory.exists()) {
			try {
				FileUtils.deleteDirectory(this.getGenerateDirectory());
			} catch (IOException ex) {
				getLog().warn("Failed to remove old generateDirectory [" + generateDirectory + "].", ex);
			}
		}

		// Create the destination path if it does not exist.
		if (generateDirectory != null && !generateDirectory.exists()) {
			generateDirectory.mkdirs();
		}

		final File episodeFile = getEpisodeFile();
		if (getEpisode() && episodeFile != null) {
			final File parentFile = episodeFile.getParentFile();
			parentFile.mkdirs();
		}
	}
 
Example 22
Source Project: aspectj-maven-plugin   Source File: AjcHelper.java    License: MIT License 6 votes vote down vote up
/**
 * Creates a file that can be used as input to the ajc compiler using the -argdfile flag.
 * Each line in these files should contain one option or filename.
 * Comments, as in Java, start with // and extend to the end of the line.
 *
 * @param arguments All arguments passed to ajc in this run
 * @param fileName the filename of the argfile
 * @param outputDir the build output area.
 * @throws IOException
 */
public static void writeBuildConfigToFile( List<String> arguments, String fileName, File outputDir )
    throws IOException
{
    FileUtils.forceMkdir( outputDir );
    File argFile = new File( outputDir, fileName );
    argFile.getParentFile().mkdirs();
    argFile.createNewFile();
    BufferedWriter writer = new BufferedWriter( new FileWriter( argFile ) );
    for ( String argument : arguments )
    {
        writer.write( argument );
        writer.newLine();
    }
    writer.flush();
    writer.close();
}
 
Example 23
Source Project: buildnumber-maven-plugin   Source File: BuildNumberMojoTest.java    License: MIT License 6 votes vote down vote up
@Test
public void basicItGitTest()
    throws Exception
{
    File projDir = resources.getBasedir( "basic-it-git" );

    MavenExecution mavenExec = maven.forProject( projDir );
    MavenExecutionResult result = mavenExec.execute( "clean" );
    result.assertErrorFreeLog();
    File testDir = result.getBasedir();
    FileUtils.copyDirectoryStructure( new File( testDir, "dotGitDir" ), new File( testDir, ".git" ) );
    result = mavenExec.execute( "clean", "verify" );
    result.assertLogText( "Storing buildNumber: 6d36c746e82f00c5913954f9178f40224497b2f3" );
    result.assertLogText( "Storing buildScmBranch: master" );

    File artifact = new File( testDir, "target/buildnumber-maven-plugin-basic-it-1.0-SNAPSHOT.jar" );
    JarFile jarFile = new JarFile( artifact );
    Attributes manifest = jarFile.getManifest().getMainAttributes();
    jarFile.close();
    String scmRev = manifest.getValue( "SCM-Revision" );
    Assert.assertEquals( "6d36c746e82f00c5913954f9178f40224497b2f3", scmRev );
}
 
Example 24
Source Project: copy-rename-maven-plugin   Source File: RenameMojo.java    License: MIT License 6 votes vote down vote up
private void copy(File srcFile,File destFile) throws MojoExecutionException{

		if(!srcFile.exists()){
			if(ignoreFileNotFoundOnIncremental && buildContext.isIncremental()){
				getLog().warn("sourceFile "+srcFile.getAbsolutePath()+ " not found during incremental build");
			} else {
				getLog().error("sourceFile "+srcFile.getAbsolutePath()+ " does not exist");
			}
		}  else if(destFile == null){
			getLog().error("destinationFile not specified");
		} else if(destFile.exists() && (destFile.isFile() == srcFile.isFile()) && !overWrite){
			getLog().error(destFile.getAbsolutePath()+" already exists and overWrite not set");
		} else{
			try {
				FileUtils.rename(srcFile, destFile);
				getLog().info("Renamed "+ srcFile.getAbsolutePath()+ " to "+ destFile.getAbsolutePath());
				buildContext.refresh(destFile);
			} catch (IOException e) {
				throw new MojoExecutionException("could not rename "+srcFile.getAbsolutePath()+" to "+destFile
                    .getAbsolutePath(),e);
			}
		}


	}
 
Example 25
Source Project: versions-maven-plugin   Source File: RevertMojo.java    License: Apache License 2.0 6 votes vote down vote up
public void execute()
    throws MojoExecutionException, MojoFailureException
{
    File outFile = project.getFile();
    File backupFile = new File( outFile.getParentFile(), outFile.getName() + ".versionsBackup" );

    if ( backupFile.exists() )
    {
        getLog().info( "Restoring " + outFile + " from " + backupFile );
        try
        {
            FileUtils.copyFile( backupFile, outFile );
            FileUtils.forceDelete( backupFile );
        }
        catch ( IOException e )
        {
            throw new MojoExecutionException( e.getMessage(), e );
        }
    }
}
 
Example 26
Source Project: versions-maven-plugin   Source File: CommitMojo.java    License: Apache License 2.0 6 votes vote down vote up
public void execute()
    throws MojoExecutionException, MojoFailureException
{
    File outFile = project.getFile();
    File backupFile = new File( outFile.getParentFile(), outFile.getName() + ".versionsBackup" );

    if ( backupFile.exists() )
    {
        getLog().info( "Accepting all changes to " + outFile );
        try
        {
            FileUtils.forceDelete( backupFile );
        }
        catch ( IOException e )
        {
            throw new MojoExecutionException( e.getMessage(), e );
        }
    }
}
 
Example 27
Source Project: beihu-boot   Source File: ApiBootMybatisEnhanceCodegen.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * load codegen.setting.json parse to CodegenSetting entity
 */
private String loadCodegenSetting() {
    try {
        // formatter codegen.setting.json path
        String settingJsonPath = String.format("%s%s", EnhanceCodegenConstant.CLASSES_PATH.replace(EnhanceCodegenConstant.POINT, File.separator), EnhanceCodegenConstant.SETTING_JSON);

        // read codegen.setting.json content
        File file = new File(projectBaseDir + settingJsonPath);
        return FileUtils.fileRead(file);
    } catch (Exception e) {
        getLog().error(e);
    }
    return null;
}
 
Example 28
Source Project: ci.maven   Source File: PluginConfigXmlIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testBootstrapPropertiesFileElements() throws Exception {
    File in = new File(CONFIG_XML);
    FileInputStream input = new FileInputStream(in);
    
    // get input XML Document
    DocumentBuilderFactory inputBuilderFactory = DocumentBuilderFactory.newInstance();
    inputBuilderFactory.setIgnoringComments(true);
    inputBuilderFactory.setCoalescing(true);
    inputBuilderFactory.setIgnoringElementContentWhitespace(true);
    inputBuilderFactory.setValidating(false);
    DocumentBuilder inputBuilder = inputBuilderFactory.newDocumentBuilder();
    Document inputDoc = inputBuilder.parse(input);
    
    // parse input XML Document
    XPath xPath = XPathFactory.newInstance().newXPath();
    String expression = "/liberty-plugin-config/bootstrapPropertiesFile";
    NodeList nodes = (NodeList) xPath.compile(expression).evaluate(inputDoc, XPathConstants.NODESET);
    assertEquals("Number of bootstrapPropertiesFile element ==>", 0, nodes.getLength());
    
    expression = "/liberty-plugin-config/bootstrapProperties";
    nodes = (NodeList) xPath.compile(expression).evaluate(inputDoc, XPathConstants.NODESET);
    assertEquals("Number of bootstrapProperties element ==>", 1, nodes.getLength());
    
    assertEquals("verify target server bootstrap.properties", "# Generated by liberty-maven-plugin\nlocation=pom.xml\n",
            FileUtils.fileRead(TARGET_BOOTSTRAP_PROPERTIES).replaceAll("\r",""));
}
 
Example 29
Source Project: api-boot   Source File: ApiBootMybatisEnhanceCodegen.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * load codegen.setting.json parse to CodegenSetting entity
 * read codegen.setting.json content
 */
private String loadCodegenSetting() {
    try {
        // formatter codegen.setting.json path
        String settingJsonPath = String.format("%s%s", EnhanceCodegenConstant.CLASSES_PATH.replace(EnhanceCodegenConstant.POINT, File.separator), EnhanceCodegenConstant.SETTING_JSON);
        File file = new File(projectBaseDir + settingJsonPath);
        if (file.exists()) {
            return FileUtils.fileRead(file);
        }
    } catch (Exception e) {
        getLog().error(e);
    }
    return null;
}
 
Example 30
Source Project: ci.maven   Source File: PluginConfigXmlIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testBootstrapPropertiesFileElements() throws Exception {
    File in = new File(CONFIG_XML);
    FileInputStream input = new FileInputStream(in);
    
    // get input XML Document
    DocumentBuilderFactory inputBuilderFactory = DocumentBuilderFactory.newInstance();
    inputBuilderFactory.setIgnoringComments(true);
    inputBuilderFactory.setCoalescing(true);
    inputBuilderFactory.setIgnoringElementContentWhitespace(true);
    inputBuilderFactory.setValidating(false);
    DocumentBuilder inputBuilder = inputBuilderFactory.newDocumentBuilder();
    Document inputDoc = inputBuilder.parse(input);

    // parse input XML Document
    XPath xPath = XPathFactory.newInstance().newXPath();
    String expression = "/liberty-plugin-config/bootstrapPropertiesFile";
    NodeList nodes = (NodeList) xPath.compile(expression).evaluate(inputDoc, XPathConstants.NODESET);
    assertEquals("Number of bootstrapPropertiesFile element ==>", 1, nodes.getLength());
    
    expression = "/liberty-plugin-config/bootstrapProperties";
    nodes = (NodeList) xPath.compile(expression).evaluate(inputDoc, XPathConstants.NODESET);
    assertEquals("Number of bootstrapProperties element ==>", 0, nodes.getLength());
    
    expression = "/liberty-plugin-config/bootstrapPropertiesFile/text()";
    String nodeValue = (String) xPath.compile(expression).evaluate(inputDoc, XPathConstants.STRING);
    File f1 = new File(SOURCE_BOOTSTRAP_PROPERTIES);
    File f2 = new File(nodeValue);
    assertEquals("bootstrapPropertiesFile value", f1.getAbsolutePath(), f2.getAbsolutePath());
    assertEquals("verify target server bootstrap.properties", FileUtils.fileRead(f2),
            FileUtils.fileRead(TARGET_BOOTSTRAP_PROPERTIES));
}