com.atlassian.maven.enforcer.FileContainsRule Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of maven-enforcer-rules Show documentation
Show all versions of maven-enforcer-rules Show documentation
The Loving Iron Fist of Maven™ extended with more enforcer rules.
The newest version!
package com.atlassian.maven.enforcer;
import org.apache.maven.enforcer.rule.api.EnforcerRule;
import org.apache.maven.enforcer.rule.api.EnforcerRuleException;
import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
import java.util.regex.Pattern;
@SuppressWarnings("unused")
public class FileContainsRule implements EnforcerRule
{
private File file;
private String containsString;
private String containsPattern;
public void execute(final EnforcerRuleHelper helper) throws EnforcerRuleException
{
if (file == null)
throw new EnforcerRuleException("A must be specified in the configuration.");
if (containsString != null)
{
final Pattern searchPattern = Pattern.compile(Pattern.quote(containsString));
enforceFileContainsPattern(file, searchPattern);
}
if (containsPattern != null)
{
final Pattern searchPattern = Pattern.compile(containsPattern);
enforceFileContainsPattern(file, searchPattern);
}
}
private void enforceFileContainsPattern(final File file, final Pattern pattern) throws EnforcerRuleException
{
try
{
final Scanner s = new Scanner(file);
try
{
if (s.findWithinHorizon(pattern, 0) == null)
throw new EnforcerRuleException("Pattern " + pattern + " was not found in file " + file);
}
finally
{
s.close();
}
}
catch (FileNotFoundException e)
{
throw new EnforcerRuleException("File not found: " + file);
}
}
public String getCacheId()
{
return Integer.toString(Arrays.hashCode(new Object[] { file, containsString, containsPattern }));
}
public boolean isCacheable()
{
return true;
}
public boolean isResultValid(EnforcerRule arg0)
{
return true;
}
public void setFile(File file)
{
this.file = file;
}
public void setContainsString(String containsString)
{
this.containsString = containsString;
}
public void setContainsPattern(String containsPattern)
{
this.containsPattern = containsPattern;
}
}