001package org.apache.maven.plugins.enforcer;
002
003/*
004 * Licensed to the Apache Software Foundation (ASF) under one
005 * or more contributor license agreements.  See the NOTICE file
006 * distributed with this work for additional information
007 * regarding copyright ownership.  The ASF licenses this file
008 * to you under the Apache License, Version 2.0 (the
009 * "License"); you may not use this file except in compliance
010 * with the License.  You may obtain a copy of the License at
011 *
012 *  http://www.apache.org/licenses/LICENSE-2.0
013 *
014 * Unless required by applicable law or agreed to in writing,
015 * software distributed under the License is distributed on an
016 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
017 * KIND, either express or implied.  See the License for the
018 * specific language governing permissions and limitations
019 * under the License.
020 */
021
022import java.util.List;
023
024import org.apache.maven.artifact.versioning.ArtifactVersion;
025import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
026import org.apache.maven.artifact.versioning.Restriction;
027import org.apache.maven.artifact.versioning.VersionRange;
028import org.apache.maven.enforcer.rule.api.EnforcerRule;
029import org.apache.maven.enforcer.rule.api.EnforcerRuleException;
030import org.apache.maven.plugin.logging.Log;
031import org.codehaus.plexus.util.StringUtils;
032
033/**
034 * Contains the common code to compare a version against a version range.
035 *
036 * @author <a href="mailto:brianf@apache.org">Brian Fox</a>
037 * @version $Id: AbstractVersionEnforcer.java 1496229 2013-06-24 21:43:56Z rfscholte $
038 */
039public abstract class AbstractVersionEnforcer
040    extends AbstractStandardEnforcerRule
041{
042
043    /**
044     * Specify the required version. Some examples are:
045     * <ul>
046     * <li><code>2.0.4</code> Version 2.0.4 and higher (different from Maven meaning)</li>
047     * <li><code>[2.0,2.1)</code> Versions 2.0 (included) to 2.1 (not included)</li>
048     * <li><code>[2.0,2.1]</code> Versions 2.0 to 2.1 (both included)</li>
049     * <li><code>[2.0.5,)</code> Versions 2.0.5 and higher</li>
050     * <li><code>(,2.0.5],[2.1.1,)</code> Versions up to 2.0.5 (included) and 2.1.1 or higher</li>
051     * </ul>
052     * 
053     * @deprecated the visibility will be reduced to private with the next major version
054     * @see {@link #setVersion(String)}
055     * @see {@link #getVersion()}
056
057     */
058    public String version = null;
059
060    /**
061     * Compares the specified version to see if it is allowed by the defined version range.
062     *
063     * @param log the log
064     * @param variableName name of variable to use in messages (Example: "Maven" or "Java" etc).
065     * @param requiredVersionRange range of allowed versions.
066     * @param actualVersion the version to be checked.
067     * @throws EnforcerRuleException the enforcer rule exception
068     */
069    public void enforceVersion( Log log, String variableName, String requiredVersionRange, ArtifactVersion actualVersion )
070        throws EnforcerRuleException
071    {
072        if ( StringUtils.isEmpty( requiredVersionRange ) )
073        {
074            throw new EnforcerRuleException( variableName + " version can't be empty." );
075        }
076        else
077        {
078
079            VersionRange vr;
080            String msg = "Detected " + variableName + " Version: " + actualVersion;
081
082            // short circuit check if the strings are exactly equal
083            if ( actualVersion.toString().equals( requiredVersionRange ) )
084            {
085                log.debug( msg + " is allowed in the range " + requiredVersionRange + "." );
086            }
087            else
088            {
089                try
090                {
091                    vr = VersionRange.createFromVersionSpec( requiredVersionRange );
092
093                    if ( containsVersion( vr, actualVersion ) )
094                    {
095                        log.debug( msg + " is allowed in the range " + requiredVersionRange + "." );
096                    }
097                    else
098                    {
099                        String message = getMessage();
100                        
101                        if ( StringUtils.isEmpty( message ) )
102                        {
103                            message = msg + " is not in the allowed range " + vr + ".";
104                        }
105
106                        throw new EnforcerRuleException( message );
107                    }
108                }
109                catch ( InvalidVersionSpecificationException e )
110                {
111                    throw new EnforcerRuleException( "The requested " + variableName + " version "
112                        + requiredVersionRange + " is invalid.", e );
113                }
114            }
115        }
116    }
117
118    /**
119     * Copied from Artifact.VersionRange. This is tweaked to handle singular ranges properly. Currently the default
120     * containsVersion method assumes a singular version means allow everything. This method assumes that "2.0.4" ==
121     * "[2.0.4,)"
122     *
123     * @param allowedRange range of allowed versions.
124     * @param theVersion the version to be checked.
125     * @return true if the version is contained by the range.
126     */
127    public static boolean containsVersion( VersionRange allowedRange, ArtifactVersion theVersion )
128    {
129        boolean matched = false;
130        ArtifactVersion recommendedVersion = allowedRange.getRecommendedVersion();
131        if ( recommendedVersion == null )
132        {
133            @SuppressWarnings( "unchecked" )
134            List<Restriction> restrictions = allowedRange.getRestrictions();
135            for ( Restriction restriction :  restrictions )
136            {
137                if ( restriction.containsVersion( theVersion ) )
138                {
139                    matched = true;
140                    break;
141                }
142            }
143        }
144        else
145        {
146            // only singular versions ever have a recommendedVersion
147            @SuppressWarnings( "unchecked" )
148            int compareTo = recommendedVersion.compareTo( theVersion );
149            matched = ( compareTo <= 0 );
150        }
151        return matched;
152    }
153
154    /*
155     * (non-Javadoc)
156     *
157     * @see org.apache.maven.enforcer.rule.api.EnforcerRule#getCacheId()
158     */
159    public String getCacheId()
160    {
161        if ( StringUtils.isNotEmpty( version ) )
162        {
163            // return the hashcodes of the parameter that matters
164            return "" + version.hashCode();
165        }
166        else
167        {
168            return "0";
169        }
170
171    }
172
173    /*
174     * (non-Javadoc)
175     *
176     * @see org.apache.maven.enforcer.rule.api.EnforcerRule#isCacheable()
177     */
178    public boolean isCacheable()
179    {
180        // the maven version is not going to change between projects in the same build.
181        return true;
182    }
183
184    /*
185     * (non-Javadoc)
186     *
187     * @see org.apache.maven.enforcer.rule.api.EnforcerRule#isResultValid(org.apache.maven.enforcer.rule.api.EnforcerRule)
188     */
189    public boolean isResultValid( EnforcerRule theCachedRule )
190    {
191        // i will always return the hash of the parameters as my id. If my parameters are the same, this
192        // rule must always have the same result.
193        return true;
194    }
195
196    /**
197     * Gets the required version.
198     *
199     * @return the required version
200     */
201    public final String getVersion()
202    {
203        return this.version;
204    }
205
206    /**
207     * Sets the required version.
208     *
209     * @param theVersion the required version to set
210     */
211    public final void setVersion( String theVersion )
212    {
213        this.version = theVersion;
214    }
215
216}