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.FileInputStream;
21  import java.io.FileOutputStream;
22  import java.io.IOException;
23  import java.nio.channels.FileChannel;
24  
25  /**
26   * File rename action.
27   */
28  public class FileRenameAction extends AbstractAction {
29  
30      /**
31       * Source.
32       */
33      private final File source;
34  
35      /**
36       * Destination.
37       */
38      private final File destination;
39  
40      /**
41       * If true, rename empty files, otherwise delete empty files.
42       */
43      private final boolean renameEmptyFiles;
44  
45      /**
46       * Creates an FileRenameAction.
47       *
48       * @param src current file name.
49       * @param dst new file name.
50       * @param renameEmptyFiles if true, rename file even if empty, otherwise delete empty files.
51       */
52      public FileRenameAction(final File src, final File dst, final boolean renameEmptyFiles) {
53          source = src;
54          destination = dst;
55          this.renameEmptyFiles = renameEmptyFiles;
56      }
57  
58      /**
59       * Rename file.
60       *
61       * @return true if successfully renamed.
62       */
63      @Override
64      public boolean execute() {
65          return execute(source, destination, renameEmptyFiles);
66      }
67  
68      /**
69       * Gets the destination.
70       * 
71       * @return the destination.
72       */
73      public File getDestination() {
74          return this.destination;
75      }
76  
77      /**
78       * Gets the source.
79       * 
80       * @return the source.
81       */
82      public File getSource() {
83          return this.source;
84      }
85  
86      /**
87       * Whether to rename empty files. If true, rename empty files, otherwise delete empty files.
88       * 
89       * @return Whether to rename empty files.
90       */
91      public boolean isRenameEmptyFiles() {
92          return renameEmptyFiles;
93      }
94  
95      /**
96       * Rename file.
97       *
98       * @param source current file name.
99       * @param destination new file name.
100      * @param renameEmptyFiles if true, rename file even if empty, otherwise delete empty files.
101      * @return true if successfully renamed.
102      */
103     public static boolean execute(final File source, final File destination, final boolean renameEmptyFiles) {
104         if (renameEmptyFiles || source.length() > 0) {
105             final File parent = destination.getParentFile();
106             if (parent != null && !parent.exists()) {
107                 // LOG4J2-679: ignore mkdirs() result: in multithreaded scenarios,
108                 // if one thread succeeds the other thread returns false
109                 // even though directories have been created. Check if dir exists instead.
110                 parent.mkdirs();
111                 if (!parent.exists()) {
112                     LOGGER.error("Unable to create directory {}", parent.getAbsolutePath());
113                     return false;
114                 }
115             }
116             try {
117                 if (!source.renameTo(destination)) {
118                     try {
119                         copyFile(source, destination);
120                         return source.delete();
121                     } catch (final IOException iex) {
122                         LOGGER.error("Unable to rename file {} to {} - {}", source.getAbsolutePath(),
123                                 destination.getAbsolutePath(), iex.getMessage());
124                     }
125                 }
126                 return true;
127             } catch (final Exception ex) {
128                 try {
129                     copyFile(source, destination);
130                     return source.delete();
131                 } catch (final IOException iex) {
132                     LOGGER.error("Unable to rename file {} to {} - {}", source.getAbsolutePath(),
133                             destination.getAbsolutePath(), iex.getMessage());
134                 }
135             }
136         } else {
137             try {
138                 source.delete();
139             } catch (final Exception ex) {
140                 LOGGER.error("Unable to delete empty file " + source.getAbsolutePath());
141             }
142         }
143 
144         return false;
145     }
146 
147     private static void copyFile(final File source, final File destination) throws IOException {
148         if (!destination.exists()) {
149             destination.createNewFile();
150         }
151 
152         // LOG4J2-1173: Files.copy(source.toPath(), destination.toPath()) throws IOException
153         // when copying to a directory mapped to a remote Linux host
154 
155         try (FileInputStream srcStream = new FileInputStream(source);
156                 FileOutputStream destStream = new FileOutputStream(destination);
157                 FileChannel srcChannel = srcStream.getChannel();
158                 FileChannel destChannel = destStream.getChannel();) {
159 
160             destChannel.transferFrom(srcChannel, 0, srcChannel.size());
161         }
162     }
163 
164     @Override
165     public String toString() {
166         return FileRenameAction.class.getSimpleName() + '[' + source + " to " + destination //
167                 + ", renameEmptyFiles=" + renameEmptyFiles + ']';
168     }
169 
170 }