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 */
038public abstract class AbstractVersionEnforcer
039    extends AbstractStandardEnforcerRule
040{
041
042    /**
043     * Specify the required version. Some examples are:
044     * <ul>
045     * <li><code>2.0.4</code> Version 2.0.4 and higher (different from Maven meaning)</li>
046     * <li><code>[2.0,2.1)</code> Versions 2.0 (included) to 2.1 (not included)</li>
047     * <li><code>[2.0,2.1]</code> Versions 2.0 to 2.1 (both included)</li>
048     * <li><code>[2.0.5,)</code> Versions 2.0.5 and higher</li>
049     * <li><code>(,2.0.5],[2.1.1,)</code> Versions up to 2.0.5 (included) and 2.1.1 or higher</li>
050     * </ul>
051     * 
052     * @see {@link #setVersion(String)}
053     * @see {@link #getVersion()}
054     */
055    private String version;
056
057    /**
058     * Compares the specified version to see if it is allowed by the defined version range.
059     *
060     * @param log the log
061     * @param variableName name of variable to use in messages (Example: "Maven" or "Java" etc).
062     * @param requiredVersionRange range of allowed versions.
063     * @param actualVersion the version to be checked.
064     * @throws EnforcerRuleException the enforcer rule exception
065     */
066    // CHECKSTYLE_OFF: LineLength
067    public void enforceVersion( Log log, String variableName, String requiredVersionRange, ArtifactVersion actualVersion )
068        throws EnforcerRuleException
069    // CHECKSTYLE_ON: LineLength
070    {
071        if ( StringUtils.isEmpty( requiredVersionRange ) )
072        {
073            throw new EnforcerRuleException( variableName + " version can't be empty." );
074        }
075        else
076        {
077
078            VersionRange vr;
079            String msg = "Detected " + variableName + " Version: " + actualVersion;
080
081            // short circuit check if the strings are exactly equal
082            if ( actualVersion.toString().equals( requiredVersionRange ) )
083            {
084                log.debug( msg + " is allowed in the range " + requiredVersionRange + "." );
085            }
086            else
087            {
088                try
089                {
090                    vr = VersionRange.createFromVersionSpec( requiredVersionRange );
091
092                    if ( containsVersion( vr, actualVersion ) )
093                    {
094                        log.debug( msg + " is allowed in the range " + requiredVersionRange + "." );
095                    }
096                    else
097                    {
098                        String message = getMessage();
099
100                        if ( StringUtils.isEmpty( message ) )
101                        {
102                            message = msg + " is not in the allowed range " + vr + ".";
103                        }
104
105                        throw new EnforcerRuleException( message );
106                    }
107                }
108                catch ( InvalidVersionSpecificationException e )
109                {
110                    throw new EnforcerRuleException( "The requested " + variableName + " version "
111                        + requiredVersionRange + " is invalid.", e );
112                }
113            }
114        }
115    }
116
117    /**
118     * Copied from Artifact.VersionRange. This is tweaked to handle singular ranges properly. Currently the default
119     * containsVersion method assumes a singular version means allow everything. This method assumes that "2.0.4" ==
120     * "[2.0.4,)"
121     *
122     * @param allowedRange range of allowed versions.
123     * @param theVersion the version to be checked.
124     * @return true if the version is contained by the range.
125     */
126    public static boolean containsVersion( VersionRange allowedRange, ArtifactVersion theVersion )
127    {
128        boolean matched = false;
129        ArtifactVersion recommendedVersion = allowedRange.getRecommendedVersion();
130        if ( recommendedVersion == null )
131        {
132            List<Restriction> restrictions = allowedRange.getRestrictions();
133            for ( Restriction restriction : restrictions )
134            {
135                if ( restriction.containsVersion( theVersion ) )
136                {
137                    matched = true;
138                    break;
139                }
140            }
141        }
142        else
143        {
144            // only singular versions ever have a recommendedVersion
145            @SuppressWarnings( "unchecked" )
146            int compareTo = recommendedVersion.compareTo( theVersion );
147            matched = ( compareTo <= 0 );
148        }
149        return matched;
150    }
151
152    @Override
153    public String getCacheId()
154    {
155        if ( StringUtils.isNotEmpty( version ) )
156        {
157            // return the hashcodes of the parameter that matters
158            return "" + version.hashCode();
159        }
160        else
161        {
162            return "0";
163        }
164
165    }
166
167    @Override
168    public boolean isCacheable()
169    {
170        // the maven version is not going to change between projects in the same build.
171        return true;
172    }
173
174    @Override
175    public boolean isResultValid( EnforcerRule theCachedRule )
176    {
177        // i will always return the hash of the parameters as my id. If my parameters are the same, this
178        // rule must always have the same result.
179        return true;
180    }
181
182    /**
183     * Gets the required version.
184     *
185     * @return the required version
186     */
187    public final String getVersion()
188    {
189        return this.version;
190    }
191
192    /**
193     * Specify the required version. Some examples are:
194     * <ul>
195     * <li><code>2.0.4</code> Version 2.0.4 and higher (different from Maven meaning)</li>
196     * <li><code>[2.0,2.1)</code> Versions 2.0 (included) to 2.1 (not included)</li>
197     * <li><code>[2.0,2.1]</code> Versions 2.0 to 2.1 (both included)</li>
198     * <li><code>[2.0.5,)</code> Versions 2.0.5 and higher</li>
199     * <li><code>(,2.0.5],[2.1.1,)</code> Versions up to 2.0.5 (included) and 2.1.1 or higher</li>
200     * </ul>
201     *
202     * @param theVersion the required version to set
203     */
204    public final void setVersion( String theVersion )
205    {
206        this.version = theVersion;
207    }
208
209}