All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.atlassian.maven.enforcer.FileContainsRule Maven / Gradle / Ivy

There is a newer version: 1.5.11
Show 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;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy