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 1634140 2014-10-24 21:23:01Z khmarbaise $
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     * @see {@link #setVersion(String)}
054     * @see {@link #getVersion()}
055     */
056    private String version;
057
058    /**
059     * Compares the specified version to see if it is allowed by the defined version range.
060     *
061     * @param log the log
062     * @param variableName name of variable to use in messages (Example: "Maven" or "Java" etc).
063     * @param requiredVersionRange range of allowed versions.
064     * @param actualVersion the version to be checked.
065     * @throws EnforcerRuleException the enforcer rule exception
066     */
067    // CHECKSTYLE_OFF: LineLength
068    public void enforceVersion( Log log, String variableName, String requiredVersionRange, ArtifactVersion actualVersion )
069        throws EnforcerRuleException
070    // CHECKSTYLE_ON: LineLength
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     * @see org.apache.maven.enforcer.rule.api.EnforcerRule#getCacheId()
157     */
158    public String getCacheId()
159    {
160        if ( StringUtils.isNotEmpty( version ) )
161        {
162            // return the hashcodes of the parameter that matters
163            return "" + version.hashCode();
164        }
165        else
166        {
167            return "0";
168        }
169
170    }
171
172    /*
173     * (non-Javadoc)
174     * @see org.apache.maven.enforcer.rule.api.EnforcerRule#isCacheable()
175     */
176    public boolean isCacheable()
177    {
178        // the maven version is not going to change between projects in the same build.
179        return true;
180    }
181
182    /*
183     * (non-Javadoc)
184     * @see
185     * org.apache.maven.enforcer.rule.api.EnforcerRule#isResultValid(org.apache.maven.enforcer.rule.api.EnforcerRule)
186     */
187    public boolean isResultValid( EnforcerRule theCachedRule )
188    {
189        // i will always return the hash of the parameters as my id. If my parameters are the same, this
190        // rule must always have the same result.
191        return true;
192    }
193
194    /**
195     * Gets the required version.
196     *
197     * @return the required version
198     */
199    public final String getVersion()
200    {
201        return this.version;
202    }
203
204    /**
205     * Specify the required version. Some examples are:
206     * <ul>
207     * <li><code>2.0.4</code> Version 2.0.4 and higher (different from Maven meaning)</li>
208     * <li><code>[2.0,2.1)</code> Versions 2.0 (included) to 2.1 (not included)</li>
209     * <li><code>[2.0,2.1]</code> Versions 2.0 to 2.1 (both included)</li>
210     * <li><code>[2.0.5,)</code> Versions 2.0.5 and higher</li>
211     * <li><code>(,2.0.5],[2.1.1,)</code> Versions up to 2.0.5 (included) and 2.1.1 or higher</li>
212     * </ul>
213     *
214     * @param theVersion the required version to set
215     */
216    public final void setVersion( String theVersion )
217    {
218        this.version = theVersion;
219    }
220
221}