File Source: ResourceManager.java

         /* 
    P/P   *  Method: com.dmdirc.util.resourcemanager.ResourceManager__static_init
          */
     1  /*
     2   * Copyright (c) 2006-2009 Chris Smith, Shane Mc Cormack, Gregory Holmes
     3   *
     4   * Permission is hereby granted, free of charge, to any person obtaining a copy
     5   * of this software and associated documentation files (the "Software"), to deal
     6   * in the Software without restriction, including without limitation the rights
     7   * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
     8   * copies of the Software, and to permit persons to whom the Software is
     9   * furnished to do so, subject to the following conditions:
    10   *
    11   * The above copyright notice and this permission notice shall be included in
    12   * all copies or substantial portions of the Software.
    13   *
    14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    20   * SOFTWARE.
    21   */
    22  
    23  package com.dmdirc.util.resourcemanager;
    24  
    25  import com.dmdirc.logger.ErrorLevel;
    26  import com.dmdirc.logger.Logger;
    27  
    28  import java.io.File;
    29  import java.io.FileOutputStream;
    30  import java.io.IOException;
    31  import java.io.InputStream;
    32  import java.io.UnsupportedEncodingException;
    33  import java.util.List;
    34  import java.util.Map;
    35  import java.util.Map.Entry;
    36  
    37  /**
    38   * Provides a launch method independant way of accessing resources.
    39   */
         /* 
    P/P   *  Method: void com.dmdirc.util.resourcemanager.ResourceManager()
          */
    40  public abstract class ResourceManager {
    41      
    42      /** Previously assigned ResourceManager. */
    43      private static ResourceManager me;
    44      
    45      /**
    46       * Returns an appropriate instance of ResourceManager.
    47       *
    48       * @return ResourceManager implementation
    49       */
    50      public static final synchronized ResourceManager getResourceManager() {
                 /* 
    P/P           *  Method: ResourceManager getResourceManager()
                  * 
                  *  Preconditions:
                  *    init'ed(me)
                  * 
                  *  Presumptions:
                  *    init'ed(com.dmdirc.logger.ErrorLevel.MEDIUM)
                  *    java.lang.ClassLoader:getResource(...)@52 != null
                  *    java.lang.ClassLoader:getResource(...)@61 != null
                  *    java.lang.ClassLoader:getResource(...)@66 != null
                  *    java.lang.System:getProperty(...)@69 != null
                  *    ...
                  * 
                  *  Postconditions:
                  *    me == One-of{old me, &new FileResourceManager(getResourceManager#1), &new ZipResourceManager(getResourceManager#2), &new ZipResourceManager(getResourceManager#3)}
                  *    init'ed(me)
                  *    return_value == me
                  *    new ArrayList(ZipResourceManager#2) num objects <= 1
                  *    new FileResourceManager(getResourceManager#1) num objects <= 1
                  *    init'ed(new FileResourceManager(getResourceManager#1).basePath)
                  *    new ZipFile(ZipResourceManager#1) num objects <= 1
                  *    new ZipResourceManager(getResourceManager#2) num objects <= 1
                  *    init'ed(new ZipResourceManager(getResourceManager#2).entries)
                  *    init'ed(new ZipResourceManager(getResourceManager#2).zipFile)
                  *    ...
                  * 
                  *  Test Vectors:
                  *    me: Inverse{null}, Addr_Set{null}
                  *    java.lang.String:equals(...)@65: {0}, {1}
                  *    java.lang.String:equals(...)@68: {0}, {1}
                  *    java.lang.String:startsWith(...)@69: {0}, {1}
                  */
    51          if (me == null) {
    52              String path = Thread.currentThread().getContextClassLoader().
    53                      getResource("com/dmdirc/Main.class").getPath();
    54              
    55              try {
    56                  path = java.net.URLDecoder.decode(path, "UTF-8");
    57              } catch (UnsupportedEncodingException ex) {
    58                  Logger.userError(ErrorLevel.MEDIUM, "Unable to decode path");
    59              }
    60              
    61              final String protocol = Thread.currentThread().getContextClassLoader().
    62                      getResource("com/dmdirc/Main.class").getProtocol();
    63              
    64              try {
    65                  if ("file".equals(protocol)) {
    66                      me = new FileResourceManager(Thread.currentThread().
    67                              getContextClassLoader().getResource("").getPath());
    68                  } else if ("jar".equals(protocol)) {
    69                      if (System.getProperty("os.name").startsWith("Windows")) {
    70                          me = new ZipResourceManager(path.substring(6, path.length() - 23));
    71                      } else {
    72                          me = new ZipResourceManager(path.substring(5, path.length() - 23));
    73                      }
    74                  }
    75              } catch (IOException ex) {
    76                  Logger.appError(ErrorLevel.MEDIUM, "Unable to determine how DMDirc"
    77                          + " has been executed", ex);
    78              }
    79          }
    80          return me;
    81      }
    82      
    83      /**
    84       * Returns a resource manager for the specified URL. The following URL types
    85       * are valid:
    86       * 
    87       * <ul>
    88       *  <li>file://path/</li>
    89       *  <li>zip://path/filename.zip</li>
    90       *  <li>jar://path/filename.jar</li>
    91       * </ul>
    92       *
    93       * @param url The URL for which a resource manager is required
    94       * @return A resource manager for the specified URL
    95       * 
    96       * @throws IOException if an IO Error occurs opening the file
    97       * @throws IllegalArgumentException if the URL type is not valid
    98       */
    99      public static final ResourceManager getResourceManager(final String url)
   100              throws IOException, IllegalArgumentException {
                 /* 
    P/P           *  Method: ResourceManager getResourceManager(String)
                  * 
                  *  Preconditions:
                  *    url != null
                  * 
                  *  Presumptions:
                  *    java.lang.String:startsWith(...)@103 == 1
                  * 
                  *  Postconditions:
                  *    init'ed(java.lang.String:substring(...)._tainted)
                  *    return_value in Addr_Set{&amp;new ZipResourceManager(getResourceManager#2),&amp;new FileResourceManager(getResourceManager#1)}
                  *    new ArrayList(ZipResourceManager#2) num objects <= 1
                  *    new FileResourceManager(getResourceManager#1) num objects <= 1
                  *    new FileResourceManager(getResourceManager#1).basePath == &amp;java.lang.String:substring(...)
                  *    new ZipFile(ZipResourceManager#1) num objects <= 1
                  *    new ZipResourceManager(getResourceManager#2) num objects <= 1
                  *    new ZipResourceManager(getResourceManager#2).entries == &amp;new ArrayList(ZipResourceManager#2)
                  *    new ZipResourceManager(getResourceManager#2).zipFile == &amp;new ZipFile(ZipResourceManager#1)
                  * 
                  *  Test Vectors:
                  *    java.lang.String:startsWith(...)@101: {0}, {1}
                  *    java.lang.String:startsWith(...)@103: {1}, {0}
                  */
   101          if (url.startsWith("file://")) {
   102              return new FileResourceManager(url.substring(7));
   103          } else if (url.startsWith("jar://") || url.startsWith("zip://")) {
   104              return new ZipResourceManager(url.substring(6));
   105          } else {
   106              throw new IllegalArgumentException("Unknown resource manager type");
   107          }
   108      }
   109      
   110      /**
   111       * Writes a resource to a file.
   112       *
   113       * @param resource Resource to write
   114       * @param file File to write to
   115       *
   116       * @throws IOException if the write operation fails
   117       */
   118      public final void resourceToFile(final byte[] resource, final File file)
   119      throws IOException {
                 /* 
    P/P           *  Method: void resourceToFile(byte[], File)
                  */
   120          final FileOutputStream out = new FileOutputStream(file, false);
   121          
   122          out.write(resource);
   123          
   124          out.flush();
   125          out.close();
   126      }
   127         
   128      /**
   129       * Extracts the specified resource to the specified directory.
   130       *
   131       * @param resourceName The name of the resource to extract
   132       * @param directory The name of the directory to extract to
   133       * @param usePath If true, append the path of the files in the resource
   134       * to the extraction path
   135       *
   136       * @throws IOException if the write operation fails
   137       *
   138       * @return success of failure of the operation
   139       */
   140      public final boolean extractResource(final String resourceName,
   141              final String directory, final boolean usePath) throws IOException {
                 /* 
    P/P           *  Method: bool extractResource(String, String, bool)
                  * 
                  *  Preconditions:
                  *    resourceName != null
                  * 
                  *  Presumptions:
                  *    java.lang.String:lastIndexOf(...)@165 <= 232-2
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  * 
                  *  Test Vectors:
                  *    usePath: {0}, {1}
                  *    java.io.File:exists(...)@157: {1}, {0}
                  *    java.io.File:exists(...)@161: {1}, {0}
                  *    java.io.File:isDirectory(...)@169: {1}, {0}
                  *    java.lang.String:indexOf(...)@150: {-231..-1}, {0..232-1}
                  */
   142          final byte[] resource = getResourceBytes(resourceName);
   143          
   144          if (resource.length == 0) {
   145              return false;
   146          }
   147          
   148          File newDir;
   149          
   150          if (usePath && resourceName.indexOf('/') > -1) {
   151              newDir = new File(directory,
   152                      resourceName.substring(0, resourceName.lastIndexOf('/')) + "/");
   153          } else {
   154              newDir = new File(directory);
   155          }
   156          
   157          if (!newDir.exists()) {
   158              newDir.mkdirs();
   159          }
   160          
   161          if (!newDir.exists()) {
   162              return false;
   163          }
   164          
   165          final File newFile = new File(newDir,
   166                  resourceName.substring(resourceName.lastIndexOf('/') + 1,
   167                  resourceName.length()));
   168          
   169          if (!newFile.isDirectory()) {
   170              resourceToFile(resource, newFile);
   171          }
   172          
   173          return true;
   174      }
   175      
   176      /**
   177       * Extracts the specified resources to the specified directory.
   178       *
   179       * @param resourcesPrefix The prefix of the resources to extract
   180       * @param directory The name of the directory to extract to
   181       * @param usePath If true, append the path of the files in the resource
   182       * to the extraction path
   183       *
   184       * @throws IOException if the write operation fails
   185       */
   186      public final void extractResources(final String resourcesPrefix,
   187              final String directory, final boolean usePath) throws IOException {
                 /* 
    P/P           *  Method: void extractResources(String, String, bool)
                  * 
                  *  Presumptions:
                  *    java.util.Iterator:next(...)@190 != null
                  *    java.util.Map:entrySet(...)@190 != null
                  *    java.util.Map_Entry:getKey(...)@191 != null
                  * 
                  *  Test Vectors:
                  *    java.util.Iterator:hasNext(...)@190: {0}, {1}
                  */
   188          final Map<String, byte[]> resourcesBytes =
   189                  getResourcesStartingWithAsBytes(resourcesPrefix);
   190          for (Entry<String, byte[]> entry : resourcesBytes.entrySet()) {
   191              extractResource(entry.getKey(), directory, usePath);
   192          }
   193      }
   194      
   195      /**
   196       * Extracts the specified resources to the specified directory.
   197       *
   198       * @param resourcesPrefix The prefix of the resources to extract
   199       * @param directory The name of the directory to extract to
   200       *
   201       * @throws IOException if the write operation fails
   202       */
   203      public final void extractResources(final String resourcesPrefix,
   204              final String directory) throws IOException {
                 /* 
    P/P           *  Method: void extractResources(String, String)
                  */
   205          extractResources(resourcesPrefix, directory, true);
   206      }
   207      
   208      /**
   209       * Checks if a resource exists.
   210       * 
   211       * @param resource Resource to check
   212       * 
   213       * @return true iif the resource exists
   214       */
   215      public abstract boolean resourceExists(final String resource);
   216      
   217      /**
   218       * Gets a byte[] of the specified resource.
   219       *
   220       * @param resource Name of the resource to return
   221       *
   222       * @return byte[] for the resource, or an empty byte[] if not found
   223       */
   224      public abstract byte[] getResourceBytes(final String resource);
   225      
   226      /**
   227       * Gets an InputStream for the specified resource.
   228       *
   229       * @param resource Name of the resource to return
   230       *
   231       * @return InputStream for the resource, or null if not found
   232       */
   233      public abstract InputStream getResourceInputStream(final String resource);
   234      
   235      /**
   236       * Gets a Map of byte[]s of the resources ending with the specified
   237       * suffix.
   238       *
   239       * @param resourcesSuffix Suffix of the resources to return
   240       * @since 0.6
   241       * @return Map of byte[]s of resources found
   242       */
   243      public abstract Map<String, byte[]> getResourcesEndingWithAsBytes(
   244              final String resourcesSuffix);
   245      
   246      /**
   247       * Gets a Map of byte[]s of the resources starting with the specified
   248       * prefix.
   249       *
   250       * @param resourcesPrefix Prefix of the resources to return
   251       *
   252       * @return Map of byte[]s of resources found
   253       */
   254      public abstract Map<String, byte[]> getResourcesStartingWithAsBytes(
   255              final String resourcesPrefix);
   256      
   257      /**
   258       * Gets a Map of InputStreams of the resources starting with the specified
   259       * prefix.
   260       *
   261       * @param resourcesPrefix Prefix of the resources to return
   262       *
   263       * @return Map of InputStreams of resources found
   264       */
   265      public abstract Map<String, InputStream> getResourcesStartingWithAsInputStreams(
   266              final String resourcesPrefix);
   267      
   268      /**
   269       * Gets a List of the resources starting with the specified
   270       * prefix.
   271       *
   272       * @param resourcesPrefix Prefix of the resources to return
   273       *
   274       * @return List of resources found
   275       */
   276      public abstract List<String> getResourcesStartingWith(final String resourcesPrefix);
   277  }








SofCheck Inspector Build Version : 2.17854
ResourceManager.java 2009-Jun-25 01:54:24
ResourceManager.class 2009-Sep-02 17:04:13