View Javadoc
1   /**
2    * This file Copyright (c) 2017-2018 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.cms.core;
35  
36  import info.magnolia.cms.util.ClasspathResourcesUtil;
37  import info.magnolia.init.MagnoliaConfigurationProperties;
38  
39  import java.io.File;
40  import java.io.FileInputStream;
41  import java.io.FileNotFoundException;
42  import java.io.IOException;
43  import java.io.InputStream;
44  import java.net.URL;
45  import java.nio.file.Paths;
46  
47  import javax.inject.Inject;
48  import javax.inject.Singleton;
49  
50  import org.apache.commons.io.IOUtils;
51  import org.apache.commons.lang3.StringUtils;
52  import org.slf4j.Logger;
53  import org.slf4j.LoggerFactory;
54  
55  /**
56   * Class to retrieve files or directories used by Magnolia. Examples: app root dir, tmp dir, ..
57   */
58  @Singleton
59  public class FileSystemHelper {
60  
61      private static final Logger log = LoggerFactory.getLogger(FileSystemHelper.class);
62  
63      private final MagnoliaConfigurationProperties magnoliaConfigurationProperties;
64  
65      @Inject
66      public FileSystemHelper(MagnoliaConfigurationProperties magnoliaConfigurationProperties) {
67          this.magnoliaConfigurationProperties = magnoliaConfigurationProperties;
68      }
69  
70      /**
71       * Gets the temporary directory set in magnolia properties.
72       * {@link info.magnolia.init.MagnoliaConfigurationProperties#MAGNOLIA_UPLOAD_TMPDIR}
73       */
74      public File getTempDirectory() {
75          String path = magnoliaConfigurationProperties.getProperty(MagnoliaConfigurationProperties.MAGNOLIA_UPLOAD_TMPDIR);
76          if (path == null) {
77              throw new IllegalArgumentException(MagnoliaConfigurationProperties.MAGNOLIA_UPLOAD_TMPDIR + " is not set in magnolia properties. Please revise your configuration.");
78          }
79          File tempDir;
80          if (Paths.get(path).isAbsolute()) {
81              tempDir = new File(path);
82          } else {
83              tempDir = new File(getAppRootDir(), path);
84          }
85          // check if temp directory exist, if not create it
86          if (!tempDir.exists() && !tempDir.mkdir()) {
87              throw new IllegalStateException("Can't create temporary directory under path [" + tempDir + "]. Magnolia configuration property '" + MagnoliaConfigurationProperties.MAGNOLIA_UPLOAD_TMPDIR + "' is set to [" + path +"]. Please revise your environment.");
88          }
89          if (!tempDir.canWrite()) {
90              throw new IllegalStateException("Temp directory [" + tempDir + "] isn't writable. Magnolia configuration property '" + MagnoliaConfigurationProperties.MAGNOLIA_UPLOAD_TMPDIR + "' is set to [" + path +"]. Please revise your environment.");
91          }
92          return tempDir;
93      }
94  
95      /**
96       * Gets the root directory for the magnolia web application.
97       */
98      public File getAppRootDir() {
99          return new File(magnoliaConfigurationProperties.getProperty(MagnoliaConfigurationProperties.MAGNOLIA_APP_ROOTDIR));
100     }
101 
102     /**
103      * Gets absolute filesystem path, adds application root if path is not absolute.
104      */
105     public String getAbsoluteFileSystemPath(String path) {
106         if (path == null) {
107             throw new IllegalArgumentException("Can't convert null path to an absolute file system path.");
108         }
109         if (Paths.get(path).isAbsolute()) {
110             return path;
111         }
112 
113         File file = new File(getAppRootDir(), path);
114         try {
115             return file.getCanonicalPath();
116         } catch (IOException e) {
117             log.debug("Can't resolve canonical path for {}. Returning absolute path.", path, e);
118             return file.getAbsolutePath();
119         }
120     }
121 
122     /**
123      * Try to get the configuration file and replace tokens.
124      * Get it first in the file system, then from the resources.
125      */
126     public String getTokenizedConfigFile(String path) throws IOException {
127         final InputStream stream = getConfigFile(path);
128         if (stream == null) {
129             throw new IOException("Can't load configuration file: " + path);
130         }
131         return replaceTokens(stream);
132     }
133 
134     private InputStream getConfigFile(String fileName) {
135         File file = new File(getAppRootDir(), fileName);
136         // relative to webapp root
137         if (file.exists()) {
138             try {
139                 URL url = new URL("file:" + file.getAbsolutePath());
140                 return url.openStream();
141             } catch (IOException e) {
142                 log.error("Unable to read config file from [{}]: ", fileName, e);
143                 return null;
144             }
145         }
146 
147         // try it directly
148         file = new File(fileName);
149         if (file.exists()) {
150             try {
151                 return new FileInputStream(file);
152             } catch (FileNotFoundException e) {
153                 log.error("Unable to read config file from [{}]:", fileName, e);
154                 return null;
155             }
156         }
157 
158         // try resources
159         try {
160             return ClasspathResourcesUtil.getStream(fileName);
161         } catch (IOException e) {
162             log.error("Unable to read config file from the resources [{}]", fileName, e);
163             return null;
164         }
165     }
166 
167     private String replaceTokens(InputStream stream) throws IOException {
168         String config = IOUtils.toString(stream);
169         IOUtils.closeQuietly(stream);
170         for (String key: magnoliaConfigurationProperties.getKeys()) {
171             config = StringUtils.replace(config, "${" + key + "}", magnoliaConfigurationProperties.getProperty(key));
172         }
173         return config;
174     }
175 
176 }