Updated to worldwind release 20070817
[worldwind-tracker.git] / gov / nasa / worldwind / util / WWIO.java
blobad99f914121a15a347f3ccff3e616f40dca50da3
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 2471 2007-07-31 21:50:57Z tgaskins $
12 package gov.nasa.worldwind.util;
14 import java.io.*;
15 import java.net.*;
16 import java.nio.*;
17 import java.nio.channels.*;
18 import java.util.logging.Level;
19 import java.util.zip.*;
21 public class WWIO
23 public static final String ILLEGAL_FILE_PATH_PART_CHARACTERS = "[" + "?/\\\\=+<>:;\\.,\"\\|^\\[\\]" + "]";
25 public static String formPath(String... pathParts)
27 StringBuilder sb = new StringBuilder();
29 for (String pathPart : pathParts)
31 if (pathPart == null)
32 continue;
34 if (sb.length() > 0)
35 sb.append(File.separator);
36 sb.append(pathPart.replaceAll(ILLEGAL_FILE_PATH_PART_CHARACTERS, "_"));
39 return sb.toString();
42 public static boolean saveBuffer(ByteBuffer buffer, File file) throws IOException
44 if (buffer == null)
46 String message = Logging.getMessage("nullValue.BufferNull");
47 Logging.logger().severe(message);
48 throw new IllegalArgumentException(message);
51 if (file == null)
53 String message = Logging.getMessage("nullValue.FileIsNull");
54 Logging.logger().severe(message);
55 throw new IllegalArgumentException(message);
58 FileOutputStream fos = null;
59 FileChannel channel = null;
60 FileLock lock;
61 int numBytesWritten = 0;
62 try
64 fos = new FileOutputStream(file);
65 channel = fos.getChannel();
66 lock = channel.tryLock();
67 if (lock == null)
69 // The file is being written to, or some other process is keeping it to itself.
70 // This is an okay condition, but worth noting.
71 Logging.logger().log(Level.FINER, "WWIO.UnableToAcquireLockFor", file.getPath());
72 return false;
75 for (buffer.rewind(); buffer.hasRemaining();)
77 numBytesWritten += channel.write(buffer);
80 return true;
82 catch (IOException e)
84 Logging.logger().log(Level.SEVERE, Logging.getMessage("WWIO.ErrorSavingBufferTo", file.getPath()), e);
86 if (numBytesWritten > 0) // don't leave behind incomplete files
87 file.delete();
89 throw e;
91 finally
93 try
95 if (channel != null)
96 channel.close(); // also releases the lock
97 else if (fos != null)
98 fos.close();
100 catch (java.io.IOException e)
102 Logging.logger().severe(Logging.getMessage("WWIO.ErrorTryingToClose", file.getPath()));
107 public static MappedByteBuffer mapFile(File file) throws IOException
109 if (file == null)
111 String message = Logging.getMessage("nullValue.FileIsNull");
112 Logging.logger().severe(message);
113 throw new IllegalArgumentException(message);
116 FileInputStream is = new FileInputStream(file);
119 return is.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
121 finally
123 is.close();
127 public static ByteBuffer readURLContentToBuffer(URL url) throws IOException
129 if (url == null)
131 String message = Logging.getMessage("nullValue.URLIsNull");
132 Logging.logger().severe(message);
133 throw new IllegalArgumentException(message);
136 InputStream is = url.openStream();
137 return readStreamToBuffer(is);
138 // ByteBuffer buffer;
139 // try
140 // {
141 // URLConnection connection = url.openConnection();
142 // int size = connection.getContentLength();
143 // buffer = ByteBuffer.allocateDirect(size);
144 // byte inputBuffer[] = new byte[size];
145 // int n;
146 // do
147 // {
148 // n = is.read(inputBuffer);
149 // if (n > 0)
150 // buffer.put(inputBuffer, 0, n);
151 // } while (buffer.hasRemaining() && n >= 0);
152 // buffer.flip();
153 // buffer.rewind();
154 // }
155 // finally
156 // {
157 // if (is != null)
158 // {
159 // is.close();
160 // }
161 // }
163 // return buffer;
166 public static ByteBuffer readFileToBuffer(File file) throws IOException
168 if (file == null)
170 String message = Logging.getMessage("nullValue.FileIsNull");
171 Logging.logger().severe(message);
172 throw new IllegalArgumentException(message);
175 FileInputStream is = new FileInputStream(file);
178 FileChannel fc = is.getChannel();
179 ByteBuffer buffer = ByteBuffer.allocate((int) fc.size());
180 for (int count = 0; count >= 0 && buffer.hasRemaining();)
182 count = fc.read(buffer);
184 buffer.flip();
185 return buffer;
187 finally
189 is.close();
193 public static ByteBuffer readZipEntryToBuffer(File zipFile, String entryName) throws IOException
195 if (zipFile == null)
197 String message = Logging.getMessage("nullValue.FileIsNull");
198 Logging.logger().severe(message);
199 throw new IllegalArgumentException(message);
202 InputStream is = null;
203 ZipEntry ze;
206 ZipFile zf = new ZipFile(zipFile);
207 if (zf.size() < 1)
209 String message = Logging.getMessage("WWIO.ZipFileIsEmpty", zipFile.getPath());
210 Logging.logger().severe(message);
211 throw new java.io.IOException(message);
214 if (entryName != null)
215 { // Read the specified entry
216 ze = zf.getEntry(entryName);
217 if (ze == null)
219 String message = Logging.getMessage("WWIO.ZipFileEntryNIF", entryName, zipFile.getPath());
220 Logging.logger().severe(message);
221 throw new IOException(message);
223 } else
224 { // Read the first entry
225 ze = zf.entries().nextElement(); // get the first entry
228 is = zf.getInputStream(ze);
229 ByteBuffer buffer = null;
230 if (ze.getSize() > 0)
232 buffer = transferStreamToByteBuffer(is, (int) ze.getSize());
233 buffer.flip();
235 return buffer;
237 finally
239 if (is != null)
240 is.close();
244 private static ByteBuffer transferStreamToByteBuffer(InputStream stream, int numBytes) throws IOException
246 if (stream == null)
248 String message = Logging.getMessage("nullValue.InputStreamIsNull");
249 Logging.logger().severe(message);
250 throw new IllegalArgumentException(message);
253 if (numBytes < 1)
255 Logging.logger().severe("WWIO.NumberBytesTransferLessThanOne");
256 throw new IllegalArgumentException(Logging.getMessage("WWIO.NumberBytesTransferLessThanOne"));
259 int bytesRead = 0;
260 int count = 0;
261 byte[] bytes = new byte[numBytes];
262 while (count >= 0 && (numBytes - bytesRead) > 0)
264 count = stream.read(bytes, bytesRead, numBytes - bytesRead);
265 if (count > 0)
267 bytesRead += count;
270 return ByteBuffer.wrap(bytes);
273 public static ByteBuffer readStreamToBuffer(InputStream inputStream) throws IOException
275 final int PAGE_SIZE = 8192;
277 ReadableByteChannel channel = Channels.newChannel(inputStream);
278 ByteBuffer buffer = ByteBuffer.allocateDirect(PAGE_SIZE);
280 int count = 0;
281 while (count >= 0)
283 count = channel.read(buffer);
284 if (count > 0 && !buffer.hasRemaining())
286 ByteBuffer biggerBuffer = ByteBuffer.allocate(buffer.limit() + PAGE_SIZE);
287 biggerBuffer.put((ByteBuffer) buffer.rewind());
288 buffer = biggerBuffer;
292 if (buffer != null)
293 buffer.flip();
295 return buffer;
298 public static String replaceSuffix(String in, String newSuffix)
300 if (in == null)
302 String message = Logging.getMessage("nullValue.InputFileNameIsNull");
303 Logging.logger().severe(message);
304 throw new IllegalArgumentException(message);
307 return in.substring(0, in.lastIndexOf(".")) + (newSuffix != null ? newSuffix : "");
310 public static File saveBufferToTempFile(ByteBuffer buffer, String suffix) throws IOException
312 if (buffer == null)
314 String message = Logging.getMessage("nullValue.ByteBufferIsNull");
315 Logging.logger().severe(message);
316 throw new IllegalArgumentException(message);
319 File outputFile = java.io.File.createTempFile("WorldWind", suffix != null ? suffix : "");
320 outputFile.deleteOnExit();
321 buffer.rewind();
322 WWIO.saveBuffer(buffer, outputFile);
324 return outputFile;
327 public static String getSuffixForMimeType(String mimeType)
329 if (mimeType == null)
331 String msg = Logging.getMessage("nullValue.MimeTypeIsNull");
332 Logging.logger().severe(msg);
333 throw new IllegalArgumentException(msg);
336 if (mimeType.equalsIgnoreCase("image/jpeg") || mimeType.equalsIgnoreCase("image/jpg"))
337 return ".jpg";
338 if (mimeType.equalsIgnoreCase("image/png"))
339 return ".png";
341 return null;
344 public static boolean isFileOutOfDate(URL url, long expiryTime)
346 if (url == null)
348 String message = Logging.getMessage("nullValue.URLIsNull");
349 Logging.logger().severe(message);
350 throw new IllegalArgumentException(message);
355 // Determine whether the file can be treated like a File, e.g., a jar entry.
356 URI uri = url.toURI();
357 if (uri.isOpaque())
358 return false; // TODO: Determine how to check the date of non-Files
360 File file = new File(uri);
362 return file.exists() && file.lastModified() < expiryTime;
364 catch (URISyntaxException e)
366 Logging.logger().log(Level.SEVERE, "WWIO.ExceptionValidatingFileExpiration", url);
367 return false;