Worldwind public release 0.2.1
[worldwind-tracker.git] / gov / nasa / worldwind / WWIO.java
blob33bc6dffad1a7453c36b1fe84f6279a5b443e267
1 /*
2 Copyright (C) 2001, 2006 United States Government
3 as represented by the Administrator of the
4 National Aeronautics and Space Administration.
5 All Rights Reserved.
6 */
8 /**
9 * @author Tom Gaskins
10 * @version $Id: WWIO.java 1869 2007-05-23 22:18:47Z tgaskins $
12 package gov.nasa.worldwind;
14 import java.net.*;
15 import java.nio.*;
16 import java.nio.channels.*;
17 import java.io.*;
18 import java.util.zip.*;
20 public class WWIO
22 public static boolean saveBuffer(ByteBuffer buffer, File file) throws IOException
24 if (buffer == null)
26 String message = WorldWind.retrieveErrMsg("nullValue.BufferNull");
27 WorldWind.logger().log(java.util.logging.Level.FINE, message);
28 throw new IllegalArgumentException(message);
31 if (file == null)
33 String message = WorldWind.retrieveErrMsg("nullValue.FileIsNull");
34 WorldWind.logger().log(java.util.logging.Level.FINE, message);
35 throw new IllegalArgumentException(message);
38 FileOutputStream fos = null;
39 FileChannel channel = null;
40 FileLock lock;
41 int numBytesWritten = 0;
42 try
44 fos = new FileOutputStream(file);
45 channel = fos.getChannel();
46 lock = channel.tryLock();
47 if (lock == null)
49 // The file is being written to, or some other process is keeping it to itself.
50 // This is an okay condition, but worth noting.
51 String message = WorldWind.retrieveErrMsg("WWIO.UnableToAcquireLockFor") + file.getPath();
52 WorldWind.logger().log(java.util.logging.Level.FINER, message);
53 return false;
56 for (buffer.rewind(); buffer.hasRemaining();)
58 numBytesWritten += channel.write(buffer);
61 return true;
63 catch (IOException e)
65 String message = WorldWind.retrieveErrMsg("WWIO.ErrorSavingBufferTo") + file.getPath();
66 WorldWind.logger().log(java.util.logging.Level.FINE, message, e);
68 if (numBytesWritten > 0) // don't leave behind incomplete files
69 file.delete();
71 throw e;
73 finally
75 try
77 if (channel != null)
78 channel.close(); // also releases the lock
79 else if (fos != null)
80 fos.close();
82 catch (java.io.IOException e)
84 String message = WorldWind.retrieveErrMsg("WWIO.ErrorTryingToClose") + file.getPath();
85 WorldWind.logger().log(java.util.logging.Level.FINE, message);
90 public static MappedByteBuffer mapFile(File file) throws IOException
92 if (file == null)
94 String message = WorldWind.retrieveErrMsg("nullValue.FileIsNull");
95 WorldWind.logger().log(java.util.logging.Level.FINE, message);
96 throw new IllegalArgumentException(message);
99 FileInputStream is = new FileInputStream(file);
102 return is.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
104 finally
106 is.close();
110 public static ByteBuffer readURLContentToBuffer(URL url) throws IOException
112 if (url == null)
114 String message = WorldWind.retrieveErrMsg("nullValue.URLIsNull");
115 WorldWind.logger().log(java.util.logging.Level.FINE, message);
116 throw new IllegalArgumentException(message);
119 InputStream is = url.openStream();
120 return readStreamToBuffer(is);
121 // ByteBuffer buffer;
122 // try
123 // {
124 // URLConnection connection = url.openConnection();
125 // int size = connection.getContentLength();
126 // buffer = ByteBuffer.allocateDirect(size);
127 // byte inputBuffer[] = new byte[size];
128 // int n;
129 // do
130 // {
131 // n = is.read(inputBuffer);
132 // if (n > 0)
133 // buffer.put(inputBuffer, 0, n);
134 // } while (buffer.hasRemaining() && n >= 0);
135 // buffer.flip();
136 // buffer.rewind();
137 // }
138 // finally
139 // {
140 // if (is != null)
141 // {
142 // is.close();
143 // }
144 // }
146 // return buffer;
149 public static ByteBuffer readFileToBuffer(File file) throws IOException
151 if (file == null)
153 String message = WorldWind.retrieveErrMsg("nullValue.FileIsNull");
154 WorldWind.logger().log(java.util.logging.Level.FINE, message);
155 throw new IllegalArgumentException(message);
158 FileInputStream is = new FileInputStream(file);
161 FileChannel fc = is.getChannel();
162 ByteBuffer buffer = ByteBuffer.allocate((int) fc.size());
163 for (int count = 0; count >= 0 && buffer.hasRemaining();)
165 count = fc.read(buffer);
167 buffer.flip();
168 return buffer;
170 finally
172 is.close();
176 public static ByteBuffer readZipEntryToBuffer(File zipFile, String entryName) throws IOException
178 if (zipFile == null)
180 String message = WorldWind.retrieveErrMsg("nullValue.FileIsNull");
181 WorldWind.logger().log(java.util.logging.Level.FINE, message);
182 throw new IllegalArgumentException(message);
185 InputStream is = null;
186 ZipEntry ze;
189 ZipFile zf = new ZipFile(zipFile);
190 if (zf.size() < 1)
192 String message = WorldWind.retrieveErrMsg("WWIO.ZipFileIsEmpty") + zipFile.getPath();
193 WorldWind.logger().log(java.util.logging.Level.FINE, message);
194 throw new java.io.IOException(message);
197 if (entryName != null)
198 { // Read the specified entry
199 ze = zf.getEntry(entryName);
200 if (ze == null)
202 String message = WorldWind.retrieveErrMsg("WWIO.ZipFileEntryNIF") + entryName
203 + WorldWind.retrieveErrMsg("punctuation.space") + zipFile.getPath();
204 WorldWind.logger().log(java.util.logging.Level.FINE, message);
205 throw new IOException(message);
208 else
209 { // Read the first entry
210 ze = zf.entries().nextElement(); // get the first entry
213 is = zf.getInputStream(ze);
214 ByteBuffer buffer = null;
215 if (ze.getSize() > 0)
217 buffer = transferStreamToByteBuffer(is, (int) ze.getSize());
218 buffer.flip();
220 return buffer;
222 finally
224 if (is != null)
225 is.close();
229 private static ByteBuffer transferStreamToByteBuffer(InputStream stream, int numBytes) throws IOException
231 if (stream == null)
233 String message = WorldWind.retrieveErrMsg("nullValue.InputStreamIsNull");
234 WorldWind.logger().log(java.util.logging.Level.FINE, message);
235 throw new IllegalArgumentException(message);
238 if (numBytes < 1)
240 String message = WorldWind.retrieveErrMsg("WWIO.NumberBytesTransferLessThanOne");
241 WorldWind.logger().log(java.util.logging.Level.FINE, message);
242 throw new IllegalArgumentException(message);
245 int bytesRead = 0;
246 int count = 0;
247 byte[] bytes = new byte[numBytes];
248 while (count >= 0 && (numBytes - bytesRead) > 0)
250 count = stream.read(bytes, bytesRead, numBytes - bytesRead);
251 if (count > 0)
253 bytesRead += count;
256 return ByteBuffer.wrap(bytes);
259 public static ByteBuffer readStreamToBuffer(InputStream inputStream) throws IOException
261 final int PAGE_SIZE = 8192;
263 ReadableByteChannel channel = Channels.newChannel(inputStream);
264 ByteBuffer buffer = ByteBuffer.allocate(PAGE_SIZE);
266 int count = 0;
267 while (count >= 0)
269 count = channel.read(buffer);
270 if (count > 0 && !buffer.hasRemaining())
272 ByteBuffer biggerBuffer = ByteBuffer.allocate(buffer.limit() + PAGE_SIZE);
273 biggerBuffer.put((ByteBuffer) buffer.rewind());
274 buffer = biggerBuffer;
278 if (buffer != null)
279 buffer.flip();
281 return buffer;
284 public static String replaceSuffix(String in, String newSuffix)
286 if (in == null)
288 String message = WorldWind.retrieveErrMsg("nullValue.InputFileNameIsNull");
289 WorldWind.logger().log(java.util.logging.Level.FINE, message);
290 throw new IllegalArgumentException(message);
293 return in.substring(0, in.lastIndexOf(".")) + (newSuffix != null ? newSuffix : "");
296 public static File saveBufferToTempFile(ByteBuffer buffer, String suffix) throws IOException
298 if (buffer == null)
300 String message = WorldWind.retrieveErrMsg("nullValue.ByteBufferIsNull");
301 gov.nasa.worldwind.WorldWind.logger().log(java.util.logging.Level.FINE, message);
302 throw new IllegalArgumentException(message);
305 File outputFile = java.io.File.createTempFile("WorldWind", suffix != null ? suffix : "");
306 outputFile.deleteOnExit();
307 buffer.rewind();
308 WWIO.saveBuffer(buffer, outputFile);
310 return outputFile;
313 public static String getSuffixForMimeType(String mimeType)
315 if (mimeType == null)
317 String msg = WorldWind.retrieveErrMsg("nullValue.MimeTypeIsNull");
318 WorldWind.logger().log(java.util.logging.Level.FINE, msg);
319 throw new IllegalArgumentException(msg);
322 if (mimeType.equalsIgnoreCase("image/jpeg") || mimeType.equalsIgnoreCase("image/jpg"))
323 return ".jpg";
324 if (mimeType.equalsIgnoreCase("image/png"))
325 return ".png";
327 return null;
330 public static boolean isFileOutOfDate(URL url, long expiryTime)
332 if (url == null)
334 String message = WorldWind.retrieveErrMsg("nullValue.URLIsNull");
335 gov.nasa.worldwind.WorldWind.logger().log(java.util.logging.Level.FINE, message);
336 throw new IllegalArgumentException(message);
341 // Determine whether the file can be treated like a File, e.g., a jar entry.
342 URI uri = url.toURI();
343 if (uri.isOpaque())
344 return false; // TODO: Determine how to check the date of non-Files
346 File file = new File(uri);
348 return file.exists() && file.lastModified() < expiryTime;
350 catch (URISyntaxException e)
352 String message = WorldWind.retrieveErrMsg("WWIO.ExceptionValidatingFileExpiration");
353 WorldWind.logger().log(java.util.logging.Level.FINE, message + url);
354 return false;