View Javadoc

1   /*
2    * Copyright 2006-2012 smartics, Kronseder & Reiner GmbH
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package de.smartics.maven.io;
17  
18  import java.io.File;
19  import java.io.IOException;
20  import java.io.OutputStream;
21  
22  import javax.xml.transform.OutputKeys;
23  import javax.xml.transform.Transformer;
24  import javax.xml.transform.TransformerException;
25  import javax.xml.transform.TransformerFactory;
26  import javax.xml.transform.dom.DOMSource;
27  import javax.xml.transform.stream.StreamResult;
28  
29  import org.apache.maven.plugin.MojoExecutionException;
30  import org.apache.maven.reporting.MavenReportException;
31  import org.w3c.dom.Document;
32  
33  /**
34   * Utilities for Mojos working with IO.
35   *
36   * @author <a href="mailto:robert.reiner@smartics.de">Robert Reiner</a>
37   * @version $Revision:591 $
38   */
39  public final class MojoIoUtils
40  {
41    // ********************************* Fields *********************************
42  
43    // --- constants ------------------------------------------------------------
44  
45    // --- members --------------------------------------------------------------
46  
47    // ****************************** Initializer *******************************
48  
49    // ****************************** Constructors ******************************
50  
51    /**
52     * Utility class pattern.
53     */
54    private MojoIoUtils()
55    {
56    }
57  
58    // ****************************** Inner Classes *****************************
59  
60    // ********************************* Methods ********************************
61  
62    // --- init -----------------------------------------------------------------
63  
64    // --- get&set --------------------------------------------------------------
65  
66    // --- business -------------------------------------------------------------
67  
68    /**
69     * Ensures that the directory with the given name is present and if not,
70     * creates it.
71     *
72     * @param dirName the name of the directory to be created.
73     * @throws MojoExecutionException if the directory is not present and cannot
74     *           be created.
75     */
76    public static File provideMojoDirectory(final String dirName)
77      throws MojoExecutionException
78    {
79      final File dir = new File(dirName);
80      provideMojoDirectory(dir);
81      return dir;
82    }
83  
84    /**
85     * Ensures that the given directory is present and if not, creates it.
86     *
87     * @param directory the directory to be created.
88     * @throws IOException if the directory is not present and cannot be created.
89     */
90    public static void provideDirectory(final File directory) throws IOException
91    {
92      if (!directory.exists())
93      {
94        final boolean created = directory.mkdirs();
95        if (!created && !directory.exists())
96        {
97          throw new IOException("Cannot create directory: " // NOPMD
98                                + directory.getAbsolutePath());
99        }
100     }
101   }
102 
103   /**
104    * Ensures that the given directory is present and if not, creates it.
105    *
106    * @param directory the directory to be created.
107    * @throws MojoExecutionException if the directory is not present and cannot
108    *           be created.
109    */
110   public static void provideMojoDirectory(final File directory)
111     throws MojoExecutionException
112   {
113     if (!directory.exists())
114     {
115       final boolean created = directory.mkdirs();
116       if (!created && !directory.exists())
117       {
118         throw new MojoExecutionException("Cannot create directory: "
119                                          + directory.getAbsolutePath());
120       }
121     }
122   }
123 
124   /**
125    * Ensures that the given directory is present and if not, creates it.
126    *
127    * @param directory the directory to be created.
128    * @throws MavenReportException if the directory is not present and cannot be
129    *           created.
130    */
131   public static void provideReportDirectory(final File directory)
132     throws MavenReportException
133   {
134     if (!directory.exists())
135     {
136       final boolean created = directory.mkdirs();
137       if (!created && !directory.exists())
138       {
139         throw new MavenReportException("Cannot create directory: "
140                                        + directory.getAbsolutePath());
141       }
142     }
143   }
144 
145   /**
146    * Normalises the file name to be used as a URL name.
147    *
148    * @impl Any character that is not a letter between A-Z (upper or lower case),
149    *       a number or a dash, an underscore or a dot, will be mapped to an
150    *       underscore. This algorithm is not part of the public API and stated
151    *       here for informal reason. Any valid URL character may be added at a
152    *       latter time. Client can be sure that the returned value contains only
153    *       characters valid in an URL.
154    * @param input the file name to be normalised.
155    * @return the normalised filename.
156    */
157   public static String normalizeFileName(final String input)
158   {
159     final int length = input.length();
160     final StringBuilder buffer = new StringBuilder(length);
161     for (int i = 0; i < length; i++)
162     {
163       final char c = input.charAt(i);
164       if (isValidUrlChar(c))
165       {
166         buffer.append(c);
167       }
168       else
169       {
170         buffer.append('_');
171       }
172     }
173 
174     return buffer.toString();
175   }
176 
177   private static boolean isValidUrlChar(final char c)
178   {
179     return isUrlLetter(c) || isDigit(c) || c == '_' || c == '-' || c == '.';
180   }
181 
182   private static boolean isUrlLetter(final char c)
183   {
184     return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
185   }
186 
187   private static boolean isDigit(final char c)
188   {
189     return c >= '0' && c <= '9';
190   }
191 
192   /**
193    * Writes the DOM document to the given stream.
194    *
195    * @param document the document to write.
196    * @param out the stream to write to.
197    * @throws TransformerException on any problem writing to the stream.
198    */
199   public static void serialize(final Document document, final OutputStream out)
200     throws TransformerException
201   {
202     serialize(document, out, false);
203   }
204 
205   /**
206    * Writes the DOM document to the given stream.
207    *
208    * @param document the document to write.
209    * @param out the stream to write to.
210    * @throws TransformerException on any problem writing to the stream.
211    */
212   public static void serialize(final Document document, final OutputStream out,
213       final boolean prettyPrint) throws TransformerException
214   {
215     final TransformerFactory factory = TransformerFactory.newInstance();
216     final Transformer serializer = factory.newTransformer();
217     if (prettyPrint)
218     {
219       serializer.setOutputProperty(OutputKeys.INDENT, "yes");
220       serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount",
221           "2");
222     }
223 
224     serializer.transform(new DOMSource(document), new StreamResult(out));
225   }
226 
227   // --- object basics --------------------------------------------------------
228 
229 }