View Javadoc
1   /* ***************************************************************************
2    * Copyright (c) 2008 Brabenetz Harald, Austria.
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.settings4j.contentresolver;
18  
19  import java.io.File;
20  import java.io.IOException;
21  
22  import org.apache.commons.io.FileUtils;
23  import org.settings4j.ContentResolver;
24  
25  /**
26   * {@link ContentResolver} implementation to read content from the File System.
27   * <p>
28   * The optional Path Prefix is "file:".
29   * <p>
30   * Absolute Windows paths contains a <b>":"</b>.<br/>
31   * Absolute Unix paths starts with <b>"/"</b>.<br/>
32   * Other Paths are relative and uses the {@link #getRootFolder()} as root.
33   * Which is per default <code>new File(".")</code>.<br/>
34   * 
35   * @author Harald.Brabenetz
36   */
37  public class FSContentResolver implements ContentResolver {
38  
39      /** General Logger for this Class. */
40      private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(FSContentResolver.class);
41  
42      /** Pseudo URL prefix for loading from the class path: "classpath:". */
43      public static final String FILE_URL_PREFIX = "file:";
44  
45      private File rootFolder;
46  
47      /** {@inheritDoc} */
48      public void addContentResolver(final ContentResolver contentResolver) {
49          throw new UnsupportedOperationException("FSContentResolver cannot add other ContentResolvers");
50      }
51  
52      /** {@inheritDoc} */
53      public byte[] getContent(final String key) { 
54          String normalizedKey = key;
55          if (normalizedKey.startsWith(FILE_URL_PREFIX)) {
56              normalizedKey = normalizedKey.substring(FILE_URL_PREFIX.length());
57          }
58  
59          File file = new File(normalizedKey);
60          if (file.exists()) {
61              try {
62                  return FileUtils.readFileToByteArray(file);
63              } catch (final IOException e) {
64                  LOG.info(e.getMessage(), e);
65              }
66          } else {
67              file = new File(getRootFolder(), normalizedKey);
68              if (file.exists()) {
69                  try {
70                      return FileUtils.readFileToByteArray(file);
71                  } catch (final IOException e) {
72                      LOG.info(e.getMessage(), e);
73                  }
74              }
75          }
76          return null;
77      }
78  
79  
80      /**
81       * @param key The Settings4j Key.
82       * @param value The value to Store.
83       * @throws IOException if an error occured.
84       */
85      public void setContent(final String key, final byte[] value) throws IOException {
86  
87          final String normalizedKey;
88          if (key.startsWith(FILE_URL_PREFIX)) {
89              normalizedKey = key.substring(FILE_URL_PREFIX.length());
90          } else {
91              normalizedKey = key;
92          }
93  
94          File file;
95  
96          if (normalizedKey.startsWith("/")) {
97              // Unix-Root
98              file = new File(normalizedKey);
99          } else if (normalizedKey.indexOf(':') >= 0) {
100             // Windows-Root
101             file = new File(normalizedKey);
102         } else {
103             file = new File(getRootFolder(), normalizedKey);
104         }
105         LOG.debug("Store content in: {}", file.getAbsolutePath());
106 
107         FileUtils.writeByteArrayToFile(file, value);
108     }
109 
110     /**
111      * return the root of this FileSystem ContenResolver.
112      * <p>
113      * if no one is set, the "." will be returned.
114      * 
115      * @return the root of this FileSystem ContenResolver.
116      */
117     public File getRootFolder() {
118         if (rootFolder == null) {
119             rootFolder = new File(".");
120             LOG.info("FSContentResolver.rootFolder is null. " //
121                 + "The RootPath Folder will be used: " + rootFolder.getAbsolutePath());
122         }
123         return rootFolder;
124     }
125 
126     /**
127      * @param rootFolderPath the root folder Path.
128      */
129     public void setRootFolderPath(final String rootFolderPath) {
130         final File newRootFolder = new File(rootFolderPath);
131         if (!newRootFolder.exists()) {
132             try {
133                 FileUtils.forceMkdir(newRootFolder);
134                 rootFolder = newRootFolder;
135                 LOG.info("Set RootPath for FSConntentResolver: {}", newRootFolder.getAbsolutePath());
136             } catch (final IOException e) {
137                 LOG.warn("cannot create rootFolder: {}!", rootFolderPath);
138             }
139         } else {
140             rootFolder = newRootFolder;
141         }
142     }
143 }