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.plugins.dependency.utils;
20  
21  import java.io.BufferedReader;
22  import java.io.File;
23  import java.io.IOException;
24  import java.io.StringReader;
25  import java.io.Writer;
26  import java.nio.charset.Charset;
27  import java.nio.file.Files;
28  import java.nio.file.OpenOption;
29  import java.nio.file.StandardOpenOption;
30  import java.util.Objects;
31  
32  import org.apache.maven.artifact.Artifact;
33  import org.apache.maven.artifact.ArtifactUtils;
34  import org.apache.maven.plugin.logging.Log;
35  
36  /**
37   * Utility class with static helper methods.
38   *
39   * @author <a href="mailto:brianf@apache.org">Brian Fox</a>
40   */
41  public final class DependencyUtil {
42  
43      /**
44       * Builds the file name. If removeVersion is set, then the file name must be reconstructed from the artifactId,
45       * Classifier (if used) and Type. Otherwise, this method returns the artifact file name.
46       *
47       * @param artifact File to be formatted.
48       * @param removeVersion Specifies if the version should be removed from the file name.
49       * @return Formatted file name in the format artifactId-[version]-[classifier].[type]
50       * @see #getFormattedFileName(Artifact, boolean, boolean)
51       */
52      public static String getFormattedFileName(Artifact artifact, boolean removeVersion) {
53          return getFormattedFileName(artifact, removeVersion, false);
54      }
55  
56      /**
57       * Builds the file name. If removeVersion is set, then the file name must be reconstructed from the groupId (if
58       * <b>prependGroupId</b> is true) artifactId, Classifier (if used) and Type. Otherwise, this method returns the
59       * artifact file name.
60       *
61       * @param artifact File to be formatted.
62       * @param removeVersion Specifies if the version should be removed from the file name.
63       * @param prependGroupId Specifies if the groupId should be prepended to the file name.
64       * @return Formatted file name in the format [groupId].artifactId-[version]-[classifier].[type]
65       */
66      public static String getFormattedFileName(Artifact artifact, boolean removeVersion, boolean prependGroupId) {
67          return getFormattedFileName(artifact, removeVersion, prependGroupId, false);
68      }
69  
70      /**
71       * Builds the file name. If removeVersion is set, then the file name must be reconstructed from the groupId (if
72       * <b>prependGroupId</b> is true) artifactId, Classifier (if used), and Type. Otherwise, this method returns the
73       * artifact file name.
74       *
75       * @param artifact file to be formatted
76       * @param removeVersion Specifies if the version should be removed from the file name
77       * @param prependGroupId Specifies if the groupId should be prepended to the file name
78       * @param useBaseVersion Specifies if the baseVersion of the artifact should be used instead of the version
79       * @return Formatted file name in the format [groupId].artifactId-[version]-[classifier].[type]
80       */
81      public static String getFormattedFileName(
82              Artifact artifact, boolean removeVersion, boolean prependGroupId, boolean useBaseVersion) {
83          return getFormattedFileName(artifact, removeVersion, prependGroupId, useBaseVersion, false);
84      }
85  
86      /**
87       * Builds the file name. If removeVersion is set, then the file name must be reconstructed from the groupId (if
88       * <b>prependGroupId</b> is true) artifactId, Classifier (if used) and Type. Otherwise, this method returns the
89       * artifact file name.
90       *
91       * @param artifact File to be formatted.
92       * @param removeVersion Specifies if the version should be removed from the file name.
93       * @param prependGroupId Specifies if the groupId should be prepended to the file name.
94       * @param useBaseVersion Specifies if the baseVersion of the artifact should be used instead of the version.
95       * @param removeClassifier Specifies if the classifier of the artifact should be remved from the file name.
96       * @return Formatted file name in the format [groupId].artifactId-[version]-[classifier].[type]
97       */
98      public static String getFormattedFileName(
99              Artifact artifact,
100             boolean removeVersion,
101             boolean prependGroupId,
102             boolean useBaseVersion,
103             boolean removeClassifier) {
104         StringBuilder destFileName = new StringBuilder();
105 
106         if (prependGroupId) {
107             destFileName.append(artifact.getGroupId()).append(".");
108         }
109 
110         String versionString = "";
111         if (!removeVersion) {
112             if (useBaseVersion) {
113                 versionString = "-" + ArtifactUtils.toSnapshotVersion(artifact.getVersion());
114             } else {
115                 versionString = "-" + artifact.getVersion();
116             }
117         }
118 
119         String classifierString = "";
120 
121         if (!removeClassifier && StringUtils.isNotEmpty(artifact.getClassifier())) {
122             classifierString = "-" + artifact.getClassifier();
123         }
124         destFileName.append(artifact.getArtifactId()).append(versionString);
125         destFileName.append(classifierString).append(".");
126         destFileName.append(artifact.getArtifactHandler().getExtension());
127 
128         return destFileName.toString();
129     }
130 
131     /**
132      * Formats the outputDirectory based on type.
133      *
134      * @param useSubdirsPerScope if a new sub directory should be used for each scope.
135      * @param useSubdirsPerType if a new sub directory should be used for each type.
136      * @param useSubdirPerArtifact if a new sub directory should be used for each artifact.
137      * @param useRepositoryLayout if dependencies must be moved into a Maven repository layout, if set, other
138      *         settings
139      *         will be ignored.
140      * @param removeVersion if the version must not be mentioned in the filename
141      * @param removeType if the type must not be mentioned in the filename
142      * @param outputDirectory base outputDirectory.
143      * @param artifact information about the artifact.
144      * @return a formatted File object to use for output.
145      */
146     public static File getFormattedOutputDirectory(
147             boolean useSubdirsPerScope,
148             boolean useSubdirsPerType,
149             boolean useSubdirPerArtifact,
150             boolean useRepositoryLayout,
151             boolean removeVersion,
152             boolean removeType,
153             File outputDirectory,
154             Artifact artifact) {
155         StringBuilder sb = new StringBuilder(128);
156         if (useRepositoryLayout) {
157             // group id
158             sb.append(artifact.getGroupId().replace('.', File.separatorChar)).append(File.separatorChar);
159             // artifact id
160             sb.append(artifact.getArtifactId()).append(File.separatorChar);
161             // version
162             sb.append(artifact.getBaseVersion()).append(File.separatorChar);
163         } else {
164             if (useSubdirsPerScope) {
165                 sb.append(artifact.getScope()).append(File.separatorChar);
166             }
167             if (useSubdirsPerType) {
168                 sb.append(artifact.getType()).append("s").append(File.separatorChar);
169             }
170             if (useSubdirPerArtifact) {
171                 String artifactString = getDependencyId(artifact, removeVersion, removeType);
172                 sb.append(artifactString).append(File.separatorChar);
173             }
174         }
175         return new File(outputDirectory, sb.toString());
176     }
177 
178     private static String getDependencyId(Artifact artifact, boolean removeVersion, boolean removeType) {
179         StringBuilder sb = new StringBuilder();
180 
181         sb.append(artifact.getArtifactId());
182 
183         if (!removeVersion) {
184             sb.append("-");
185             sb.append(artifact.getVersion());
186         }
187 
188         if (StringUtils.isNotEmpty(artifact.getClassifier())) {
189             sb.append("-");
190             sb.append(artifact.getClassifier());
191         }
192 
193         // if the classifier and type are the same (sources), then don't
194         // repeat.
195         // avoids names like foo-sources-sources
196         if (!removeType && !Objects.equals(artifact.getClassifier(), artifact.getType())) {
197             sb.append("-");
198             sb.append(artifact.getType());
199         }
200 
201         return sb.toString();
202     }
203 
204     /**
205      * Writes the specified string to the specified file.
206      *
207      * @param string the string to write
208      * @param file the file to write to
209      * @param append append to existing file or not
210      * @param log ignored
211      * @throws IOException if an I/O error occurs
212      * @deprecated specify an encoding instead of a log
213      */
214     @Deprecated
215     public static synchronized void write(String string, File file, boolean append, Log log) throws IOException {
216         write(string, file, append, "UTF-8");
217     }
218 
219     /**
220      * Writes the specified string to the specified file.
221      *
222      * @param string the string to write
223      * @param file the file to write to
224      * @param append append to existing file or not
225      * @param encoding character set name
226      * @throws IOException if an I/O error occurs
227      */
228     public static synchronized void write(String string, File file, boolean append, String encoding)
229             throws IOException {
230         Files.createDirectories(file.getParentFile().toPath());
231 
232         OpenOption appendOption = append ? StandardOpenOption.APPEND : StandardOpenOption.TRUNCATE_EXISTING;
233 
234         try (Writer writer = Files.newBufferedWriter(
235                 file.toPath(),
236                 Charset.forName(encoding),
237                 appendOption,
238                 StandardOpenOption.CREATE,
239                 StandardOpenOption.WRITE)) {
240             writer.write(string);
241         }
242     }
243 
244     /**
245      * Writes the specified string to the log at info level.
246      *
247      * @param string the string to write
248      * @param log where to log information
249      * @throws IOException if an I/O error occurs
250      */
251     public static synchronized void log(String string, Log log) throws IOException {
252         try (BufferedReader reader = new BufferedReader(new StringReader(string))) {
253             reader.lines().forEach(log::info);
254         }
255     }
256 
257     /**
258      * Mainly used to parse excludes, includes configuration.
259      *
260      * @param str the string to split
261      * @return the result items
262      */
263     public static String[] tokenizer(String str) {
264         String s = cleanToBeTokenizedString(str);
265         if (s.isEmpty()) {
266             return new String[0];
267         }
268         return cleanToBeTokenizedString(str).split(",");
269     }
270 
271     /**
272      * Clean up configuration string before it can be tokenized.
273      *
274      * @param str the string which should be cleaned
275      * @return cleaned up string
276      */
277     public static String cleanToBeTokenizedString(String str) {
278         String ret = "";
279         if (!(str == null || str.isEmpty())) {
280             // remove initial and ending spaces, plus all spaces next to commas
281             ret = str.trim().replaceAll("\\s*,\\s*", ",");
282         }
283 
284         return ret;
285     }
286 }