View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.enforcer.rules.version;
20  
21  import javax.inject.Named;
22  
23  import java.util.Arrays;
24  import java.util.Iterator;
25  import java.util.List;
26  import java.util.regex.Matcher;
27  import java.util.regex.Pattern;
28  
29  import org.apache.commons.lang3.SystemUtils;
30  import org.apache.maven.artifact.versioning.ArtifactVersion;
31  import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
32  import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
33  import org.apache.maven.artifact.versioning.VersionRange;
34  import org.apache.maven.enforcer.rule.api.EnforcerRuleException;
35  import org.codehaus.plexus.util.StringUtils;
36  
37  /**
38   * This rule checks that the Java version is allowed.
39   *
40   * @author <a href="mailto:brianf@apache.org">Brian Fox</a>
41   */
42  @Named("requireJavaVersion")
43  public final class RequireJavaVersion extends AbstractVersionEnforcer {
44  
45      private static final Pattern JDK8_VERSION_PATTERN = Pattern.compile("([\\d.]+)");
46  
47      /**
48       * Display the normalized JDK version.
49       */
50      private boolean display = false;
51  
52      @Override
53      public void setVersion(String theVersion) {
54  
55          if ("8".equals(theVersion)) {
56              super.setVersion("1.8");
57              return;
58          }
59  
60          if (!theVersion.contains("8")) {
61              super.setVersion(theVersion);
62              return;
63          }
64  
65          Matcher matcher = JDK8_VERSION_PATTERN.matcher(theVersion);
66  
67          StringBuffer result = new StringBuffer();
68          while (matcher.find()) {
69              if ("8".equals(matcher.group(1))) {
70                  matcher.appendReplacement(result, "1.8");
71              } else {
72                  matcher.appendReplacement(result, "$1");
73              }
74          }
75          matcher.appendTail(result);
76  
77          super.setVersion(result.toString());
78      }
79  
80      @Override
81      public void execute() throws EnforcerRuleException {
82          String javaVersion = SystemUtils.JAVA_VERSION;
83          String javaVersionNormalized = normalizeJDKVersion(javaVersion);
84          if (display) {
85              getLog().info("Detected Java Version: '" + javaVersion + "'");
86              getLog().info("Normalized Java Version: '" + javaVersionNormalized + "'");
87          } else {
88              getLog().debug("Detected Java Version: '" + javaVersion + "'");
89              getLog().debug("Normalized Java Version: '" + javaVersionNormalized + "'");
90          }
91  
92          ArtifactVersion detectedJdkVersion = new DefaultArtifactVersion(javaVersionNormalized);
93  
94          getLog().debug("Parsed Version: Major: " + detectedJdkVersion.getMajorVersion() + " Minor: "
95                  + detectedJdkVersion.getMinorVersion() + " Incremental: " + detectedJdkVersion.getIncrementalVersion()
96                  + " Build: " + detectedJdkVersion.getBuildNumber() + " Qualifier: "
97                  + detectedJdkVersion.getQualifier());
98  
99          setCustomMessageIfNoneConfigured(detectedJdkVersion, getVersion());
100 
101         enforceVersion("JDK", getVersion(), detectedJdkVersion);
102     }
103 
104     /**
105      * Converts a jdk string from 1.5.0-11b12 to a single 3 digit version like 1.5.0-11
106      *
107      * @param theJdkVersion to be converted.
108      * @return the converted string.
109      */
110     public static String normalizeJDKVersion(String theJdkVersion) {
111 
112         theJdkVersion = theJdkVersion.replaceAll("_|-", ".");
113         String tokenArray[] = StringUtils.split(theJdkVersion, ".");
114         List<String> tokens = Arrays.asList(tokenArray);
115         StringBuilder buffer = new StringBuilder(theJdkVersion.length());
116 
117         Iterator<String> iter = tokens.iterator();
118         for (int i = 0; i < tokens.size() && i < 4; i++) {
119             String section = iter.next();
120             section = section.replaceAll("[^0-9]", "");
121 
122             if (section != null && !section.isEmpty()) {
123                 buffer.append(Integer.parseInt(section));
124 
125                 if (i != 2) {
126                     buffer.append('.');
127                 } else {
128                     buffer.append('-');
129                 }
130             }
131         }
132 
133         String version = buffer.toString();
134         version = StringUtils.stripEnd(version, "-");
135         return StringUtils.stripEnd(version, ".");
136     }
137 
138     private void setCustomMessageIfNoneConfigured(ArtifactVersion detectedJdkVersion, String allowedVersionRange) {
139         if (getMessage() == null) {
140             String version;
141             try {
142                 VersionRange vr = VersionRange.createFromVersionSpec(allowedVersionRange);
143                 version = AbstractVersionEnforcer.toString(vr);
144             } catch (InvalidVersionSpecificationException e) {
145                 getLog().debug("Could not parse allowed version range " + allowedVersionRange + " " + e.getMessage());
146                 version = allowedVersionRange;
147             }
148             String message = String.format(
149                     "Detected JDK version %s (JAVA_HOME=%s) is not in the allowed range %s.",
150                     detectedJdkVersion, SystemUtils.JAVA_HOME, version);
151             super.setMessage(message);
152         }
153     }
154 
155     @Override
156     public String toString() {
157         return String.format(
158                 "%s[message=%s, version=%s, display=%b]",
159                 getClass().getSimpleName(), getMessage(), getVersion(), display);
160     }
161 }