View Javadoc

1   /*
2   * $Id: FileChecker.java 21720 2011-04-22 19:50:04Z mike.schilling $
3   * --------------------------------------------------------------------------------------
4   * Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com
5   *
6   * The software in this package is published under the terms of the CPAL v1.0
7   * license, a copy of which has been included with this distribution in the
8   * LICENSE.txt file.
9   */
10  package org.mule.tools.anttasks;
11  
12  import org.apache.tools.ant.BuildException;
13  import org.apache.tools.ant.Location;
14  import org.apache.tools.ant.Task;
15  
16  import java.io.File;
17  import java.text.MessageFormat;
18  
19  /**
20  * Check file parameters to Ant tasks
21  */
22  public class FileChecker extends Task
23  {
24      private Location location;
25  
26      /**
27  * Create a FileChecker
28  */
29      public FileChecker(Location location)
30      {
31          this.location = location;
32      }
33  
34      /**
35  * Check that a specified file parameter is valid
36  */
37      public void checkFile(File file, String parameterName, boolean isDirectory, boolean needWrite) throws BuildException
38      {
39          if (file == null)
40          {
41              throw new BuildException(MessageFormat.format("No {0} specified", parameterName), getLocation());
42          }
43          if (!file.exists())
44          {
45              throw new BuildException(
46                  MessageFormat.format("{0} \"{1}\" does not exist", parameterName, file),
47                  getLocation());
48          }
49          if (!file.canRead())
50          {
51              throw new BuildException(
52                  MessageFormat.format("{0} \"{1}\" is not readable", parameterName, file),
53                  getLocation());
54          }
55          if (needWrite && !file.canWrite())
56          {
57              throw new BuildException(
58                  MessageFormat.format("{0} \"{1}\" is not writable", parameterName, file),
59                  getLocation());
60          }
61          if (isDirectory)
62          {
63              if (!file.isDirectory())
64              {
65                  throw new BuildException(
66                      MessageFormat.format("{0} \"{1}\" is not a directory", parameterName, file),
67                      getLocation());
68              }
69          }
70          else
71          {
72              if (file.isDirectory())
73              {
74                  throw new BuildException(
75                      MessageFormat.format("{0} \"{1}\" is a directory", parameterName, file),
76                      getLocation());
77              }
78          }
79      }
80  }
81