You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

FileBackedDataSource.java 6.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.poifs.nio;
  16. import java.io.File;
  17. import java.io.FileNotFoundException;
  18. import java.io.IOException;
  19. import java.io.OutputStream;
  20. import java.io.RandomAccessFile;
  21. import java.lang.reflect.Method;
  22. import java.nio.ByteBuffer;
  23. import java.nio.channels.Channels;
  24. import java.nio.channels.FileChannel;
  25. import java.nio.channels.WritableByteChannel;
  26. import java.security.AccessController;
  27. import java.security.PrivilegedAction;
  28. import java.util.ArrayList;
  29. import java.util.List;
  30. import org.apache.poi.util.IOUtils;
  31. import org.apache.poi.util.POILogFactory;
  32. import org.apache.poi.util.POILogger;
  33. import org.apache.poi.util.SuppressForbidden;
  34. /**
  35. * A POIFS {@link DataSource} backed by a File
  36. */
  37. public class FileBackedDataSource extends DataSource {
  38. private final static POILogger logger = POILogFactory.getLogger( FileBackedDataSource.class );
  39. private FileChannel channel;
  40. private boolean writable;
  41. // remember file base, which needs to be closed too
  42. private RandomAccessFile srcFile;
  43. // Buffers which map to a file-portion are not closed automatically when the Channel is closed
  44. // therefore we need to keep the list of mapped buffers and do some ugly reflection to try to
  45. // clean the buffer during close().
  46. // See https://bz.apache.org/bugzilla/show_bug.cgi?id=58480,
  47. // http://stackoverflow.com/questions/3602783/file-access-synchronized-on-java-object and
  48. // http://bugs.java.com/view_bug.do?bug_id=4724038 for related discussions
  49. private List<ByteBuffer> buffersToClean = new ArrayList<ByteBuffer>();
  50. public FileBackedDataSource(File file) throws FileNotFoundException {
  51. this(newSrcFile(file, "r"), true);
  52. }
  53. public FileBackedDataSource(File file, boolean readOnly) throws FileNotFoundException {
  54. this(newSrcFile(file, readOnly ? "r" : "rw"), readOnly);
  55. }
  56. public FileBackedDataSource(RandomAccessFile srcFile, boolean readOnly) {
  57. this(srcFile.getChannel(), readOnly);
  58. this.srcFile = srcFile;
  59. }
  60. public FileBackedDataSource(FileChannel channel, boolean readOnly) {
  61. this.channel = channel;
  62. this.writable = !readOnly;
  63. }
  64. public boolean isWriteable() {
  65. return this.writable;
  66. }
  67. public FileChannel getChannel() {
  68. return this.channel;
  69. }
  70. @Override
  71. public ByteBuffer read(int length, long position) throws IOException {
  72. if(position >= size()) {
  73. throw new IndexOutOfBoundsException("Position " + position + " past the end of the file");
  74. }
  75. // Do we read or map (for read/write?
  76. ByteBuffer dst;
  77. int worked = -1;
  78. if (writable) {
  79. dst = channel.map(FileChannel.MapMode.READ_WRITE, position, length);
  80. worked = 0;
  81. // remember the buffer for cleanup if necessary
  82. buffersToClean.add(dst);
  83. } else {
  84. // Read
  85. channel.position(position);
  86. dst = ByteBuffer.allocate(length);
  87. worked = IOUtils.readFully(channel, dst);
  88. }
  89. // Check
  90. if(worked == -1) {
  91. throw new IndexOutOfBoundsException("Position " + position + " past the end of the file");
  92. }
  93. // Ready it for reading
  94. dst.position(0);
  95. // All done
  96. return dst;
  97. }
  98. @Override
  99. public void write(ByteBuffer src, long position) throws IOException {
  100. channel.write(src, position);
  101. }
  102. @Override
  103. public void copyTo(OutputStream stream) throws IOException {
  104. // Wrap the OutputSteam as a channel
  105. WritableByteChannel out = Channels.newChannel(stream);
  106. // Now do the transfer
  107. channel.transferTo(0, channel.size(), out);
  108. }
  109. @Override
  110. public long size() throws IOException {
  111. return channel.size();
  112. }
  113. @Override
  114. public void close() throws IOException {
  115. // also ensure that all buffers are unmapped so we do not keep files locked on Windows
  116. // We consider it a bug if a Buffer is still in use now!
  117. for(ByteBuffer buffer : buffersToClean) {
  118. unmap(buffer);
  119. }
  120. buffersToClean.clear();
  121. if (srcFile != null) {
  122. // see http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4796385
  123. srcFile.close();
  124. } else {
  125. channel.close();
  126. }
  127. }
  128. private static RandomAccessFile newSrcFile(File file, String mode) throws FileNotFoundException {
  129. if(!file.exists()) {
  130. throw new FileNotFoundException(file.toString());
  131. }
  132. return new RandomAccessFile(file, mode);
  133. }
  134. // need to use reflection to avoid depending on the sun.nio internal API
  135. // unfortunately this might break silently with newer/other Java implementations,
  136. // but we at least have unit-tests which will indicate this when run on Windows
  137. private static void unmap(final ByteBuffer buffer) {
  138. // not necessary for HeapByteBuffer, avoid lots of log-output on this class
  139. if(buffer.getClass().getName().endsWith("HeapByteBuffer")) {
  140. return;
  141. }
  142. AccessController.doPrivileged(new PrivilegedAction<Void>() {
  143. @Override
  144. @SuppressForbidden("Java 9 Jigsaw whitelists access to sun.misc.Cleaner, so setAccessible works")
  145. public Void run() {
  146. try {
  147. final Method getCleanerMethod = buffer.getClass().getMethod("cleaner");
  148. getCleanerMethod.setAccessible(true);
  149. final Object cleaner = getCleanerMethod.invoke(buffer);
  150. if (cleaner != null) {
  151. cleaner.getClass().getMethod("clean").invoke(cleaner);
  152. }
  153. } catch (Exception e) {
  154. logger.log(POILogger.WARN, "Unable to unmap memory mapped ByteBuffer.", e);
  155. }
  156. return null; // Void
  157. }
  158. });
  159. }
  160. }