Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   *  Copyright 2001-2009 Stephen Colebourne
   *
   *  Licensed under the Apache License, Version 2.0 (the "License");
   *  you may not use this file except in compliance with the License.
   *  You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
  *  Unless required by applicable law or agreed to in writing, software
  *  distributed under the License is distributed on an "AS IS" BASIS,
  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  */
 package org.joda.time.tz;
 
 import java.io.File;
 import java.util.Map;
 import java.util.Set;
 
ZoneInfoProvider loads compiled data files as generated by ZoneInfoCompiler.

ZoneInfoProvider is thread-safe and publicly immutable.

Author(s):
Brian S O'Neill
Since:
1.0
 
 public class ZoneInfoProvider implements Provider {

    
The directory where the files are held.
 
     private final File iFileDir;
    
The resource path.
 
     private final String iResourcePath;
    
The class loader to use.
 
     private final ClassLoader iLoader;
    
Maps ids to strings or SoftReferences to DateTimeZones.
 
     private final Map<StringObjectiZoneInfoMap;

    
ZoneInfoProvider searches the given directory for compiled data files.

Throws:
java.io.IOException if directory or map file cannot be read
 
     public ZoneInfoProvider(File fileDirthrows IOException {
         if (fileDir == null) {
             throw new IllegalArgumentException("No file directory provided");
         }
         if (!fileDir.exists()) {
             throw new IOException("File directory doesn't exist: " + fileDir);
         }
         if (!fileDir.isDirectory()) {
             throw new IOException("File doesn't refer to a directory: " + fileDir);
         }
 
          = fileDir;
          = null;
          = null;
 
          = loadZoneInfoMap(openResource("ZoneInfoMap"));
     }

    
ZoneInfoProvider searches the given ClassLoader resource path for compiled data files. Resources are loaded from the ClassLoader that loaded this class.

Throws:
java.io.IOException if directory or map file cannot be read
 
     public ZoneInfoProvider(String resourcePaththrows IOException {
         this(resourcePathnullfalse);
     }

    
ZoneInfoProvider searches the given ClassLoader resource path for compiled data files.

Parameters:
loader ClassLoader to load compiled data files from. If null, use system ClassLoader.
Throws:
java.io.IOException if directory or map file cannot be read
 
     public ZoneInfoProvider(String resourcePathClassLoader loader)
         throws IOException
     {
         this(resourcePathloadertrue);
     }

    

Parameters:
favorSystemLoader when true, use the system class loader if loader null. When false, use the current class loader if loader is null.
    private ZoneInfoProvider(String resourcePath,
                             ClassLoader loaderboolean favorSystemLoader
        throws IOException
    {
        if (resourcePath == null) {
            throw new IllegalArgumentException("No resource path provided");
        }
        if (!resourcePath.endsWith("/")) {
            resourcePath += '/';
        }
         = null;
         = resourcePath;
        if (loader == null && !favorSystemLoader) {
            loader = getClass().getClassLoader();
        }
         = loader;
         = loadZoneInfoMap(openResource("ZoneInfoMap"));
    }
    //-----------------------------------------------------------------------
    
If an error is thrown while loading zone data, uncaughtException is called to log the error and null is returned for this and all future requests.

Parameters:
id the id to load
Returns:
the loaded zone
    public DateTimeZone getZone(String id) {
        if (id == null) {
            return null;
        }
        Object obj = .get(id);
        if (obj == null) {
            return null;
        }
        if (id.equals(obj)) {
            // Load zone data for the first time.
            return loadZoneData(id);
        }
        if (obj instanceof SoftReference<?>) {
            @SuppressWarnings("unchecked")
            SoftReference<DateTimeZoneref = (SoftReference<DateTimeZone>) obj;
            DateTimeZone tz = ref.get();
            if (tz != null) {
                return tz;
            }
            // Reference cleared; load data again.
            return loadZoneData(id);
        }
        // If this point is reached, mapping must link to another.
        return getZone((String)obj);
    }

    
Gets a list of all the available zone ids.

Returns:
the zone ids
    public Set<StringgetAvailableIDs() {
        // Return a copy of the keys rather than an umodifiable collection.
        // This prevents ConcurrentModificationExceptions from being thrown by
        // some JVMs if zones are opened while this set is iterated over.
        return new TreeSet<String>(.keySet());
    }

    
Called if an exception is thrown from getZone while loading zone data.

Parameters:
ex the exception
    protected void uncaughtException(Exception ex) {
        Thread t = Thread.currentThread();
        t.getThreadGroup().uncaughtException(tex);
    }

    
Opens a resource from file or classpath.

Parameters:
name the name to open
Returns:
the input stream
Throws:
java.io.IOException if an error occurs
    private InputStream openResource(String namethrows IOException {
        InputStream in;
        if ( != null) {
            in = new FileInputStream(new File(name));
        } else {
            String path = .concat(name);
            if ( != null) {
                in = .getResourceAsStream(path);
            } else {
                in = ClassLoader.getSystemResourceAsStream(path);
            }
            if (in == null) {
                StringBuffer buf = new StringBuffer(40)
                    .append("Resource not found: \"")
                    .append(path)
                    .append("\" ClassLoader: ")
                    .append( != null ? .toString() : "system");
                throw new IOException(buf.toString());
            }
        }
        return in;
    }

    
Loads the time zone data for one id.

Parameters:
id the id to load
Returns:
the zone
    private DateTimeZone loadZoneData(String id) {
        InputStream in = null;
        try {
            in = openResource(id);
            DateTimeZone tz = DateTimeZoneBuilder.readFrom(inid);
            .put(idnew SoftReference<DateTimeZone>(tz));
            return tz;
        } catch (IOException e) {
            uncaughtException(e);
            .remove(id);
            return null;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
            }
        }
    }
    //-----------------------------------------------------------------------
    
Loads the zone info map.

Parameters:
in the input stream
Returns:
the map
    private static Map<StringObjectloadZoneInfoMap(InputStream inthrows IOException {
        Map<StringObjectmap = new ConcurrentHashMap<StringObject>();
        DataInputStream din = new DataInputStream(in);
        try {
            readZoneInfoMap(dinmap);
        } finally {
            try {
                din.close();
            } catch (IOException e) {
            }
        }
        map.put("UTC"new SoftReference<DateTimeZone>(.));
        return map;
    }

    
Reads the zone info map from file.

Parameters:
din the input stream
zimap gets filled with string id to string id mappings
    private static void readZoneInfoMap(DataInputStream dinMap<StringObjectzimapthrows IOException {
        // Read the string pool.
        int size = din.readUnsignedShort();
        String[] pool = new String[size];
        for (int i=0; i<sizei++) {
            pool[i] = din.readUTF().intern();
        }
        // Read the mappings.
        size = din.readUnsignedShort();
        for (int i=0; i<sizei++) {
            try {
                zimap.put(pool[din.readUnsignedShort()], pool[din.readUnsignedShort()]);
            } catch (ArrayIndexOutOfBoundsException e) {
                throw new IOException("Corrupt zone info map");
            }
        }
    }
New to GrepCode? Check out our FAQ X