001: /*
002: * Copyright 2001-2006 C:1 Financial Services GmbH
003: *
004: * This software is free software; you can redistribute it and/or
005: * modify it under the terms of the GNU Lesser General Public
006: * License Version 2.1, as published by the Free Software Foundation.
007: *
008: * This software is distributed in the hope that it will be useful,
009: * but WITHOUT ANY WARRANTY; without even the implied warranty of
010: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
011: * Lesser General Public License for more details.
012: *
013: * You should have received a copy of the GNU Lesser General Public
014: * License along with this library; if not, write to the Free Software
015: * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
016: */
017:
018: package de.finix.contelligent.persistence;
019:
020: import java.io.File;
021: import java.io.FileInputStream;
022: import java.io.FileNotFoundException;
023: import java.io.IOException;
024: import java.io.InputStream;
025: import java.util.Iterator;
026: import java.util.List;
027:
028: import de.finix.contelligent.exception.ComponentPersistenceException;
029: import de.finix.contelligent.logging.LoggingService;
030: import de.finix.contelligent.util.FileUtils;
031:
032: /**
033: * This implementation of interface {@link FileAdapter} uses a local directory
034: * to store and retrieve files.
035: */
036: public class LocalFileAdapter extends AbstractFileAdapter {
037: final static org.apache.log4j.Logger log = LoggingService
038: .getLogger(LocalFileAdapter.class);
039:
040: final private String fileRepository;
041:
042: /**
043: * Creates a new <code>LocalFileAdapter</code> instance.
044: *
045: * @param fileRepository
046: * path to the files in the local filesystem
047: * @param parentAdapter
048: * the parent FileAdapter
049: * @exception InstantiationException
050: * if an error occurs
051: */
052: public LocalFileAdapter(final String fileRepository,
053: final FileAdapter parentAdapter) throws IOException {
054: super (parentAdapter);
055: this .fileRepository = fileRepository.endsWith("/") ? fileRepository
056: : (fileRepository + '/');
057:
058: File dir = new File(fileRepository);
059: if (dir.exists()) {
060: if (!dir.isDirectory()) {
061: log.fatal("<init> - fileRepository '" + fileRepository
062: + "' is a normal file!");
063: throw new IOException("<init> - fileRepository '"
064: + fileRepository + "' is a normal file!");
065: }
066: } else {
067: dir.mkdirs();
068: log.debug("<init> - created repository '" + fileRepository
069: + "'.");
070: }
071: }
072:
073: /**
074: * Implementation of {@link FileAdapter#destroy}. Deletes the directory
075: * created by this adapter.
076: */
077: public void destroy() {
078: log.debug("destroy() - beginning destruction of repository '"
079: + fileRepository + "' => ALL data will be lost ...");
080: File dir = new File(fileRepository);
081: boolean rs = FileUtils.removeDir(dir, true);
082: if (rs) {
083: log.debug("destroy() - remove of repository '"
084: + fileRepository + "' was successful.");
085: } else {
086: log.warn("destroy() - remove of repository '"
087: + fileRepository + "' wasn't successful!");
088: }
089: }
090:
091: /**
092: * Implementation of {@link FileAdapter#deleteResource{}.
093: */
094: public boolean deleteResource(String name) {
095: String fileName = fileRepository + name;
096: File file = new File(fileName);
097: return file.delete();
098: }
099:
100: /**
101: * Describe <code>storeResourceFromStream</code> method here.
102: *
103: * @param name
104: * a <code>String</code> value
105: * @param stream
106: * an <code>InputStream</code> value
107: * @exception ComponentPersistenceException
108: * if an error occurs
109: */
110: public void storeResourceFromStream(String name, InputStream stream)
111: throws IOException {
112: String fileName = fileRepository + name;
113: int index = fileName.lastIndexOf('/');
114:
115: if (index != -1) {
116: String dirPath = fileName.substring(0, index);
117: File dir = new File(dirPath);
118: if (!dir.exists()) {
119: dir.mkdirs();
120: if (log.isDebugEnabled()) {
121: log
122: .debug("storeResourceFromStream() - creating directory '"
123: + dirPath + "' ...");
124: }
125: }
126: }
127: File file = new File(fileName);
128: if (log.isDebugEnabled()) {
129: log.debug("storeResourceFromStream() - storing resource '"
130: + name + "' in file '" + fileName + "' ...");
131: }
132: FileUtils.copy(stream, file);
133: }
134:
135: public String toString() {
136: return "LocalFileAdapter(" + fileRepository + ")";
137: }
138:
139: public String getRepository() {
140: return fileRepository;
141: }
142:
143: public File getResourceAsFile(String resName) {
144: return new File(fileRepository + resName);
145: }
146:
147: /**
148: * Implementation of {@link AbstractFileAdapter#findResource}.
149: */
150: protected InputStream findResource(String resName) {
151: File file = new File(fileRepository + resName);
152: if (!file.exists()) {
153: return null;
154: } else {
155: try {
156: return new FileInputStream(file);
157: } catch (FileNotFoundException e) {
158: log
159: .error("findResource() - could not created FileInputStream using file '"
160: + file
161: + "' for resource '"
162: + resName
163: + "'!");
164: return null;
165: }
166: }
167: }
168:
169: /**
170: * Implementation of {@link AbstractFileAdapter#getLastModified}.
171: */
172: protected long getLastModified(String resName) {
173: File file = new File(fileRepository + resName);
174: if (!file.exists()) {
175: return 0L;
176: } else {
177: return file.lastModified();
178: }
179: }
180:
181: /**
182: * Moves the given list of resources-names into the given adapter using
183: * {@link #getResourceAsFile} abd removes any successfully moved file from
184: * the given list so the list must be modifyable! If the list is not empty
185: * after this method returns those remaining files could not be moved!
186: *
187: * @param fileNameList
188: * a <code>List</code> of String instances, the name iof the
189: * resources to move
190: * @param to
191: * a <code>LocalFileAdapter</code> value
192: */
193: public void moveFiles(List fileNameList, LocalFileAdapter to) {
194: Iterator fileNames = fileNameList.iterator();
195: while (fileNames.hasNext()) {
196: String resourceName = (String) fileNames.next();
197: try {
198: File sourceFile = this .getResourceAsFile(resourceName);
199: File targetFile = to.getResourceAsFile(resourceName);
200: File parentDir = targetFile.getParentFile();
201: if (!parentDir.exists())
202: parentDir.mkdirs();
203: if (sourceFile.renameTo(targetFile)) {
204: fileNames.remove();
205: } else {
206: log.error("moveFiles() - could not rename file '"
207: + sourceFile + "' into '" + targetFile
208: + "'!");
209: }
210: } catch (Exception e) {
211: log
212: .error("moveFiles() - Exception while moving resource '"
213: + resourceName + "' to adapter: " + e);
214: }
215: }
216: }
217:
218: /*
219: * public boolean txMoveFiles(List fileNameList, LocalFileAdapter to) throws
220: * Exception { Map tmpFileMap = new HashMap(); // (File, File) entries,
221: * mapping real to tmp file try { Iterator fileNames =
222: * fileNameList.iterator(); while (fileNames.hasNext()) { String
223: * resourceName = (String)fileNames.next(); File realFile =
224: * to.getResourceAsFile(resourceName); if (realFile.exists()) { File tmpFile =
225: * File.createTempFile("Contelligent", null, realFile.getParentFile());
226: * FileUtils.copy(realFile, tmpFile); tmpFileMap.put(realFile, tmpFile); } } }
227: * catch (Exception e) { log.error("moveFiles() - error while copying
228: * existing files in target adapter '"+to+"' (deleting all copies): "+e);
229: * Iterator tmpFiles = tmpFileMap.values().iterator(); while
230: * (tmpFiles.hasNext()) { File tmpFile = (File)tmpFiles.next();
231: * tmpFile.delete(); } return false; }
232: *
233: * Map movedFileMap = new HashMap(); // (File, File) entries, mapping source
234: * to target file try { Iterator fileNames = fileNameList.iterator(); while
235: * (fileNames.hasNext()) { String resourceName = (String)fileNames.next();
236: * File sourceFile = this.getResourceAsFile(resourceName); File targetFile =
237: * to.getResourceAsFile(resourceName); if (sourceFile.renameTo(targetFile)) {
238: * log.error("moveFiles() - could not rename file '"+sourceFile+"' into
239: * '"+targetFile+"'!"); throw new Exception("Could not rename file
240: * '"+sourceFile+"' into '"+targetFile+"'!"); } else {
241: * movedFileMap.put(sourceFile, targetFile); } } return true; } catch
242: * (Exception e) { log.error("moveFiles() - Exception while moving files to
243: * adapter '"+to+"' -> trying to move back the moved files: "+e); Iterator
244: * files = movedFileMap.entrySet().iterator(); while (files.hasNext()) {
245: * Map.Entry entry = (Map.Entry)files.next(); File orgFile =
246: * (File)entry.getKey(); File file = (File)entry.getValue(); if
247: * (file.renameTo(orgFile)) files.remove(); }
248: *
249: * files = tmpFileMap.entrySet().iterator(); while (files.hasNext()) {
250: * Map.Entry entry = (Map.Entry)files.next(); File realFile =
251: * (File)entry.getKey(); File tmpFile = (File)entry.getValue(); if
252: * (tmpFile.renameTo(realFile)) files.remove(); }
253: *
254: * if (!movedFileMap.isEmpty() || !tmpFileMap.isEmpty()) { StringBuffer
255: * errorMsg = new StringBuffer(256); if (!movedFileMap.isEmpty()) {
256: * log.error("moveFiles() - could not move back all files, remaining:
257: * "+movedFileMap); errorMsg.append("To restore Please manually move the
258: * following files to restore the"); files =
259: * movedFileMap.entrySet().iterator(); while (files.hasNext()) { Map.Entry
260: * entry = (Map.Entry)files.next(); File orgFile = (File)entry.getKey();
261: * File file = (File)entry.getValue(); } } } return false; } finally {
262: * Iterator tmpFiles = tmpFileMap.values().iterator(); while
263: * (tmpFiles.hasNext()) { File tmpFile = (File)tmpFiles.next();
264: * tmpFile.delete(); } } }
265: */
266: }
|