1 17 package org.alfresco.repo.content.filestore; 18 19 import java.io.File ; 20 import java.io.FileOutputStream ; 21 import java.io.IOException ; 22 import java.io.OutputStream ; 23 import java.io.RandomAccessFile ; 24 import java.nio.channels.Channels ; 25 import java.nio.channels.WritableByteChannel ; 26 27 import org.alfresco.repo.content.AbstractContentWriter; 28 import org.alfresco.service.cmr.repository.ContentIOException; 29 import org.alfresco.service.cmr.repository.ContentReader; 30 import org.apache.commons.logging.Log; 31 import org.apache.commons.logging.LogFactory; 32 33 40 public class FileContentWriter extends AbstractContentWriter 41 { 42 private static final Log logger = LogFactory.getLog(FileContentWriter.class); 43 44 private File file; 45 private boolean allowRandomAccess; 46 47 53 public FileContentWriter(File file) 54 { 55 this( 56 file, 57 FileContentStore.STORE_PROTOCOL + file.getAbsolutePath(), 58 null); 59 } 60 61 68 public FileContentWriter(File file, ContentReader existingContentReader) 69 { 70 this( 71 file, 72 FileContentStore.STORE_PROTOCOL + file.getAbsolutePath(), 73 existingContentReader); 74 } 75 76 84 public FileContentWriter(File file, String url, ContentReader existingContentReader) 85 { 86 super(url, existingContentReader); 87 88 this.file = file; 89 allowRandomAccess = true; 90 } 91 92 void setAllowRandomAccess(boolean allow) 93 { 94 this.allowRandomAccess = allow; 95 } 96 97 100 public File getFile() 101 { 102 return file; 103 } 104 105 108 public long getSize() 109 { 110 if (file == null) 111 return 0L; 112 else if (!file.exists()) 113 return 0L; 114 else 115 return file.length(); 116 } 117 118 122 @Override 123 protected ContentReader createReader() throws ContentIOException 124 { 125 FileContentReader reader = new FileContentReader(this.file, getContentUrl()); 126 reader.setAllowRandomAccess(this.allowRandomAccess); 127 return reader; 128 } 129 130 @Override 131 protected WritableByteChannel getDirectWritableChannel() throws ContentIOException 132 { 133 try 134 { 135 if (file.exists() && file.length() > 0) 137 { 138 throw new IOException ("File exists - overwriting not allowed"); 139 } 140 WritableByteChannel channel = null; 142 if (allowRandomAccess) 143 { 144 RandomAccessFile randomAccessFile = new RandomAccessFile (file, "rw"); channel = randomAccessFile.getChannel(); 146 } 147 else 148 { 149 OutputStream os = new FileOutputStream (file); 150 channel = Channels.newChannel(os); 151 } 152 if (logger.isDebugEnabled()) 154 { 155 logger.debug("Opened write channel to file: \n" + 156 " file: " + file + "\n" + 157 " random-access: " + allowRandomAccess); 158 } 159 return channel; 160 } 161 catch (Throwable e) 162 { 163 throw new ContentIOException("Failed to open file channel: " + this, e); 164 } 165 } 166 167 170 public boolean canWrite() 171 { 172 return true; } 174 } 175 | Popular Tags |