1. /*
  2. * Copyright 2000,2003-2004 The Apache Software Foundation
  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. */
  17. package org.apache.tools.ant.taskdefs;
  18. import java.io.File;
  19. import org.apache.tools.ant.BuildException;
  20. import org.apache.tools.ant.Task;
  21. /**
  22. * Creates a given directory.
  23. * Creates a directory and any non-existent parent directories, when
  24. * necessary
  25. *
  26. * @since Ant 1.1
  27. *
  28. * @ant.task category="filesystem"
  29. */
  30. public class Mkdir extends Task {
  31. private static final int MKDIR_RETRY_SLEEP_MILLIS = 10;
  32. /**
  33. * our little directory
  34. */
  35. private File dir;
  36. /**
  37. * create the directory and all parents
  38. * @throws BuildException if dir is somehow invalid, or creation failed.
  39. */
  40. public void execute() throws BuildException {
  41. if (dir == null) {
  42. throw new BuildException("dir attribute is required", getLocation());
  43. }
  44. if (dir.isFile()) {
  45. throw new BuildException("Unable to create directory as a file "
  46. + "already exists with that name: "
  47. + dir.getAbsolutePath());
  48. }
  49. if (!dir.exists()) {
  50. boolean result = mkdirs(dir);
  51. if (!result) {
  52. String msg = "Directory " + dir.getAbsolutePath()
  53. + " creation was not successful for an unknown reason";
  54. throw new BuildException(msg, getLocation());
  55. }
  56. log("Created dir: " + dir.getAbsolutePath());
  57. }
  58. }
  59. /**
  60. * the directory to create; required.
  61. *
  62. * @param dir the directory to be made.
  63. */
  64. public void setDir(File dir) {
  65. this.dir = dir;
  66. }
  67. /**
  68. * Attempt to fix possible race condition when creating
  69. * directories on WinXP. If the mkdirs does not work,
  70. * wait a little and try again.
  71. */
  72. private boolean mkdirs(File f) {
  73. if (!f.mkdirs()) {
  74. try {
  75. Thread.sleep(MKDIR_RETRY_SLEEP_MILLIS);
  76. return f.mkdirs();
  77. } catch (InterruptedException ex) {
  78. return f.mkdirs();
  79. }
  80. }
  81. return true;
  82. }
  83. }