View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
16   */
17  package org.apache.logging.log4j.core.appender.rolling.action;
18  
19  import java.io.File;
20  import java.io.IOException;
21  import java.nio.file.Files;
22  
23  /**
24   * File rename action.
25   */
26  public class FileRenameAction extends AbstractAction {
27  
28      /**
29       * Source.
30       */
31      private final File source;
32  
33      /**
34       * Destination.
35       */
36      private final File destination;
37  
38      /**
39       * If true, rename empty files, otherwise delete empty files.
40       */
41      private final boolean renameEmptyFiles;
42  
43      /**
44       * Creates an FileRenameAction.
45       *
46       * @param src              current file name.
47       * @param dst              new file name.
48       * @param renameEmptyFiles if true, rename file even if empty, otherwise delete empty files.
49       */
50      public FileRenameAction(final File src, final File dst, final boolean renameEmptyFiles) {
51          source = src;
52          destination = dst;
53          this.renameEmptyFiles = renameEmptyFiles;
54      }
55  
56      /**
57       * Rename file.
58       *
59       * @return true if successfully renamed.
60       */
61      @Override
62      public boolean execute() {
63          return execute(source, destination, renameEmptyFiles);
64      }
65  
66      /**
67       * Rename file.
68       *
69       * @param source           current file name.
70       * @param destination      new file name.
71       * @param renameEmptyFiles if true, rename file even if empty, otherwise delete empty files.
72       * @return true if successfully renamed.
73       */
74      public static boolean execute(final File source, final File destination, final boolean renameEmptyFiles) {
75          if (renameEmptyFiles || source.length() > 0) {
76              final File parent = destination.getParentFile();
77              if (parent != null && !parent.exists()) {
78                  // LOG4J2-679: ignore mkdirs() result: in multithreaded scenarios,
79                  // if one thread succeeds the other thread returns false
80                  // even though directories have been created. Check if dir exists instead.
81                  parent.mkdirs();
82                  if (!parent.exists()) {
83                      LOGGER.error("Unable to create directory {}", parent.getAbsolutePath());
84                      return false;
85                  }
86              }
87              try {
88                  if (!source.renameTo(destination)) {
89                      try {
90                          copyFile(source, destination);
91                          return source.delete();
92                      } catch (final IOException iex) {
93                          LOGGER.error("Unable to rename file {} to {} - {}", source.getAbsolutePath(),
94                              destination.getAbsolutePath(), iex.getMessage());
95                      }
96                  }
97                  return true;
98              } catch (final Exception ex) {
99                  try {
100                     copyFile(source, destination);
101                     return source.delete();
102                 } catch (final IOException iex) {
103                     LOGGER.error("Unable to rename file {} to {} - {}", source.getAbsolutePath(),
104                         destination.getAbsolutePath(), iex.getMessage());
105                 }
106             }
107         } else {
108             try {
109                 source.delete();
110             } catch (final Exception ex) {
111                 LOGGER.error("Unable to delete empty file " + source.getAbsolutePath());
112             }
113         }
114 
115         return false;
116     }
117 
118     private static void copyFile(final File source, final File destination) throws IOException {
119         if (!destination.exists()) {
120             destination.createNewFile();
121         }
122         Files.copy(source.toPath(), destination.toPath());
123     }
124 
125     @Override
126     public String toString() {
127         return FileRenameAction.class.getSimpleName() + '[' + source + " to " + destination //
128                 + ", renameEmptyFiles=" + renameEmptyFiles + ']';
129     }
130 }