/** @throws IOException java.util.jar.JarFile#getJarEntry(java.lang.String) */
  public void test_getJarEntryLjava_lang_String() throws IOException {
    try {
      Support_Resources.copyFile(resources, null, jarName);
      JarFile jarFile = new JarFile(new File(resources, jarName));
      assertEquals("Error in returned entry", 311, jarFile.getJarEntry(entryName).getSize());
      jarFile.close();
    } catch (Exception e) {
      fail("Exception during test: " + e.toString());
    }

    Support_Resources.copyFile(resources, null, jarName);
    JarFile jarFile = new JarFile(new File(resources, jarName));
    Enumeration<JarEntry> enumeration = jarFile.entries();
    assertTrue(enumeration.hasMoreElements());
    while (enumeration.hasMoreElements()) {
      JarEntry je = enumeration.nextElement();
      jarFile.getJarEntry(je.getName());
    }

    enumeration = jarFile.entries();
    assertTrue(enumeration.hasMoreElements());
    JarEntry je = enumeration.nextElement();
    try {
      jarFile.close();
      jarFile.getJarEntry(je.getName());
      // fail("IllegalStateException expected.");
    } catch (IllegalStateException ee) { // Per documentation exception
      // may be thrown.
      // expected
    }
  }
Example #2
0
  public void loadOldStylePluginFrom(File pluginFile) throws IOException {
    JarFile jarFile = new JarFile(pluginFile);
    // add jar to our extension classLoader
    SoapUIExtensionClassLoader extensionClassLoader = getExtensionClassLoader();
    extensionClassLoader.addFile(pluginFile);

    // look for factories
    JarEntry entry = jarFile.getJarEntry("META-INF/factories.xml");
    if (entry != null) {
      getFactoryRegistry().addConfig(jarFile.getInputStream(entry), extensionClassLoader);
    }

    // look for listeners
    entry = jarFile.getJarEntry("META-INF/listeners.xml");
    if (entry != null) {
      getListenerRegistry().addConfig(jarFile.getInputStream(entry), extensionClassLoader);
    }

    // look for actions
    entry = jarFile.getJarEntry("META-INF/actions.xml");
    if (entry != null) {
      getActionRegistry().addConfig(jarFile.getInputStream(entry), extensionClassLoader);
    }

    // add jar to resource classloader so embedded images can be found with
    // UISupport.loadImageIcon(..)
    UISupport.addResourceClassLoader(new URLClassLoader(new URL[] {pluginFile.toURI().toURL()}));
  }
Example #3
0
 /** @see java.lang.ClassLoader#findResources(java.lang.String) */
 @Override
 public Enumeration<URL> findResources(String resourceName) throws IOException {
   String webInfResourceName = "WEB-INF/classes/" + resourceName;
   List<URL> urlList = new ArrayList<URL>();
   int jarFileListSize = jarFileList.size();
   for (int i = 0; i < jarFileListSize; i++) {
     JarFile jarFile = jarFileList.get(i);
     JarEntry jarEntry = jarFile.getJarEntry(resourceName);
     // to better support war format, look for the resourceName in the WEB-INF/classes directory
     if (loadWebInf && jarEntry == null) jarEntry = jarFile.getJarEntry(webInfResourceName);
     if (jarEntry != null) {
       try {
         String jarFileName = jarFile.getName();
         if (jarFileName.contains("\\")) jarFileName = jarFileName.replace('\\', '/');
         urlList.add(new URL("jar:file:" + jarFileName + "!/" + jarEntry));
       } catch (MalformedURLException e) {
         System.out.println(
             "Error making URL for ["
                 + resourceName
                 + "] in jar ["
                 + jarFile
                 + "] in war file ["
                 + outerFile
                 + "]: "
                 + e.toString());
       }
     }
   }
   // add all resources found in parent loader too
   Enumeration<URL> superResources = super.findResources(resourceName);
   while (superResources.hasMoreElements()) urlList.add(superResources.nextElement());
   return Collections.enumeration(urlList);
 }
Example #4
0
  /** @see java.lang.ClassLoader#findResource(java.lang.String) */
  @Override
  protected URL findResource(String resourceName) {
    if (resourceCache.containsKey(resourceName)) return resourceCache.get(resourceName);

    // try the runtime/classes directory for conf files and such
    String runtimePath = System.getProperty("moqui.runtime");
    String fullPath = runtimePath + "/classes/" + resourceName;
    File resourceFile = new File(fullPath);
    if (resourceFile.exists())
      try {
        return resourceFile.toURI().toURL();
      } catch (MalformedURLException e) {
        System.out.println(
            "Error making URL for ["
                + resourceName
                + "] in runtime classes directory ["
                + runtimePath
                + "/classes/"
                + "]: "
                + e.toString());
      }

    String webInfResourceName = "WEB-INF/classes/" + resourceName;
    int jarFileListSize = jarFileList.size();
    for (int i = 0; i < jarFileListSize; i++) {
      JarFile jarFile = jarFileList.get(i);
      JarEntry jarEntry = jarFile.getJarEntry(resourceName);
      // to better support war format, look for the resourceName in the WEB-INF/classes directory
      if (loadWebInf && jarEntry == null) jarEntry = jarFile.getJarEntry(webInfResourceName);
      if (jarEntry != null) {
        try {
          String jarFileName = jarFile.getName();
          if (jarFileName.contains("\\")) jarFileName = jarFileName.replace('\\', '/');
          URL resourceUrl = new URL("jar:file:" + jarFileName + "!/" + jarEntry);
          resourceCache.put(resourceName, resourceUrl);
          return resourceUrl;
        } catch (MalformedURLException e) {
          System.out.println(
              "Error making URL for ["
                  + resourceName
                  + "] in jar ["
                  + jarFile
                  + "] in war file ["
                  + outerFile
                  + "]: "
                  + e.toString());
        }
      }
    }
    return super.findResource(resourceName);
  }
Example #5
0
 public static Properties loadProperties(String fileName) {
   diag_println(DIAG_OFF, ".props : ", fileName);
   Properties props = new Properties();
   if (notNullOrEmpty(fileName)) {
     InputStream in = null;
     try {
       JarFile jarFile = null;
       if (isJarUri(fileName)) {
         URL url = new URL(fileName);
         url = new URL(url.getFile());
         String[] parts = url.getFile().split("!/");
         jarFile = new JarFile(new File(parts[0]));
         JarEntry jarEntry = jarFile.getJarEntry(parts[1]);
         in = jarFile.getInputStream(jarEntry);
       } else {
         File file = new File(fileName);
         if (file.isFile()) {
           in = new FileInputStream(file);
         } else {
           in = PluginUtils.class.getResourceAsStream(fileName);
         }
       }
       props.load(in);
       if (jarFile != null) jarFile.close();
     } catch (Exception e) {
       Log.log(Log.ERROR, PluginUtils.class + ".loadProperties", e);
     } finally {
       IOUtilities.closeQuietly((Closeable) in);
     }
   }
   return props;
 }
Example #6
0
  /**
   * Gets the manifest.
   *
   * @param jarName the jar name
   * @param lineSeparator the line separator
   * @return the manifest
   */
  public String getManifest(final String jarName, final String lineSeparator) {
    StringBuilder sb = new StringBuilder();

    String lib = getLibraryPathName(jarBaseName);
    if (!isEmpty(lib)) {
      lib = lib.replaceAll("file:", "");
      final File[] files = new File(lib).listFiles(new FilenameFilterJar());
      if ((files != null) && (files.length > 0)) {
        for (File jar : files) {
          if (jar.getName().matches(".*" + jarName + ".*") && jar.exists()) {
            try {
              JarFile jarFile = new JarFile(jar);
              final JarEntry entry = jarFile.getJarEntry("META-INF/MANIFEST.MF");
              final InputStream is = jarFile.getInputStream(entry);
              final BufferedReader br = new BufferedReader(new InputStreamReader(is));
              String line;
              while ((line = br.readLine()) != null) {
                sb.append(lineSeparator).append(line);
              }
              if (jarFile != null) {
                jarFile.close();
                jarFile = null;
              }
            } catch (final Exception e) {
            }
          }
        }
      }
    }
    return sb.toString();
  }
    private Class<?> loadClassFromJar(String className) throws ClassNotFoundException {
      Class<?> result = null;

      result = classes.get(className); // checks in cached classes
      if (result != null) {
        return result;
      }

      try {
        final JarFile jar = new JarFile(jarFile);
        try {
          final String path = className.replace('.', '/');
          final JarEntry entry = jar.getJarEntry(path + ".class");
          final InputStream in = jar.getInputStream(entry);
          try {
            final byte[] classBytes = IOUtils.toByteArray(in);
            result = defineClass(className, classBytes, 0, classBytes.length, null);
            classes.put(className, result);
            return result;
          } finally {
            in.close();
          }
        } finally {
          jar.close();
        }
      } catch (Exception e) {
        throw new ClassNotFoundException("Can't find class " + className + " in jar " + jarFile, e);
      }
    }
  @RequestMapping("/source")
  public void source(
      Model model,
      @RequestParam("id") String jarid,
      @RequestParam("clz") String clazzName,
      @RequestParam(value = "type", required = false, defaultValue = "asmdump") String type) {
    model.addAttribute("clzName", clazzName);
    model.addAttribute("id", jarid);

    if (Database.get(jarid) == null) {
      return;
    }

    FileItem path = (FileItem) Database.get(jarid).getObj();
    model.addAttribute("jarFile", path);
    try {
      JarFile jarFile = new JarFile(path.getFullName());
      String code = "";

      JarEntry entry = jarFile.getJarEntry(clazzName);
      InputStream inputStream = jarFile.getInputStream(entry);

      if (type.equals("asmdump")) {
        code = asmDump(inputStream);
      } else if (type.equals("decomp")) {
        code = jclazzDecomp(clazzName, inputStream);
      }
      model.addAttribute("code", code);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Example #9
0
  public boolean isDirectory(URI uri) {
    try {
      if (uri.getPath() != null && uri.getPath().endsWith(".jar!")) {
        // if the uri is the root of a jar, and it ends with a !, it should be considered a
        // directory
        return true;
      }
      String jar = getJar(uri);
      String path = getPath(uri);

      if (!path.endsWith("/")) {
        path = path + "/";
      }

      JarFile jarFile = new JarFile(jar);
      try {
        JarEntry jarEntry = jarFile.getJarEntry(path);
        if (jarEntry != null && jarEntry.isDirectory()) {
          return true;
        }
        // maybe the path is not in the jar as a seperate entry, but there are files in the path
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
          if (entries.nextElement().getName().startsWith(path)) {
            return true;
          }
        }
        return false;
      } finally {
        jarFile.close();
      }
    } catch (IOException e) {
      return false;
    }
  }
  public static void readFileFromJar(String jarFilePath, String metaInfo) {
    LogUtil.d("readFileFromJar:", jarFilePath, metaInfo);
    JarFile jarFile = null;
    try {
      jarFile = new JarFile(jarFilePath);
      JarEntry entry = jarFile.getJarEntry(metaInfo);
      if (entry != null) {
        InputStream input = jarFile.getInputStream(entry);

        return;
      }

    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (jarFile != null) {
        try {
          jarFile.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return;
  }
Example #11
0
  private static void copyFiles(Manifest manifest, JarFile in, JarOutputStream out, long timestamp)
      throws IOException {
    byte[] buffer = new byte[4096];
    int num;
    Map<String, Attributes> entries = manifest.getEntries();
    List<String> names = new ArrayList<String>(entries.keySet());
    Collections.sort(names);
    for (String name : names) {
      JarEntry inEntry = in.getJarEntry(name);
      JarEntry outEntry = null;
      if (inEntry.getMethod() == ZipEntry.STORED) {
        outEntry = new JarEntry(inEntry);
      } else {
        outEntry = new JarEntry(name);
      }
      outEntry.setTime(timestamp);
      out.putNextEntry(outEntry);

      InputStream data = in.getInputStream(inEntry);
      while ((num = data.read(buffer)) > 0) {
        out.write(buffer, 0, num);
      }
      out.flush();
    }
  }
Example #12
0
 public static DatabaseBridge loadBridge(File file) {
   DatabaseBridge theBridge = null;
   PluginDescriptionFile bridgeDescription = null;
   try {
     // Load the jar
     JarFile jar = new JarFile(file);
     // Load the info about the bridge
     JarEntry entry = jar.getJarEntry("bridge.yml");
     InputStream stream = jar.getInputStream(entry);
     bridgeDescription = new PluginDescriptionFile(stream);
     // Get the main class
     String main = bridgeDescription.getMain();
     try {
       URL test =
           new URL(
               "http://guardian.nekotech.tk:8080/job/Guardian-MySQL/Guardian-MySQL-RB/api/json");
       HttpURLConnection connection = (HttpURLConnection) test.openConnection();
       connection.connect();
       JSONObject object =
           (JSONObject) new JSONParser().parse(new InputStreamReader(connection.getInputStream()));
       String version = bridgeDescription.getVersion();
       if (!version.equals("Unknown")
           && Integer.parseInt(version) < Integer.parseInt(object.get("number").toString())) {
         BukkitUtils.info("Guardian-Bridge is out of date, please download the latest");
       }
     } catch (Exception ex) {
       BukkitUtils.severe("Error occurred while checking if Guardian is up to date", ex);
     }
     // Clean it all up
     stream.close();
     jar.close();
     // Get a new classloader
     URLClassLoader classLoader =
         new URLClassLoader(
             new URL[] {file.toURI().toURL()}, DatabaseBridge.class.getClassLoader());
     // Load the class
     Class<?> clazz = classLoader.loadClass(main);
     // Construct it
     Object object = clazz.newInstance();
     // Verify it
     if (!(object instanceof DatabaseBridge)) {
       return null;
     }
     // Its all good
     theBridge = (DatabaseBridge) object;
   } catch (FileNotFoundException ex) {
     BukkitUtils.severe("Database bridge does not contain a valid bridge.yml");
   } catch (ZipException ex) {
     BukkitUtils.severe("The database bridge appears to be an invalid jar file");
   } catch (Exception ex) {
     ex.printStackTrace();
   }
   Guardian.getInstance().getConf().bridgeDescription = bridgeDescription;
   BukkitUtils.info(
       "Loading " + bridgeDescription.getName() + " v" + bridgeDescription.getVersion());
   // Lets return it
   return theBridge;
 }
Example #13
0
  /**
   * @param file Plugin file object
   * @return The current plugin's description element.
   * @throws InvalidPluginException
   * @throws InvalidDescriptionFileException
   */
  protected synchronized PluginDescriptionFile getDescription(File file)
      throws InvalidPluginException, InvalidDescriptionFileException {
    if (!file.exists()) {
      throw new InvalidPluginException(file.getName() + " does not exist!");
    }

    PluginDescriptionFile description = null;
    JarFile jar = null;
    InputStream in = null;
    try {
      // Spout plugin properties file
      jar = new JarFile(file);
      JarEntry entry = jar.getJarEntry(YAML_SPOUT);

      // Fallback plugin properties file
      if (entry == null) {
        entry = jar.getJarEntry(YAML_OTHER);
      }

      if (entry == null) {
        throw new InvalidPluginException("Jar has no properties.yml or plugin.yml!");
      }

      in = jar.getInputStream(entry);
      description = new PluginDescriptionFile(in);
    } catch (IOException e) {
      throw new InvalidPluginException(e);
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException e) {
          engine.getLogger().log(Level.WARNING, "Problem closing input stream", e);
        }
      }
      if (jar != null) {
        try {
          jar.close();
        } catch (IOException e) {
          engine.getLogger().log(Level.WARNING, "Problem closing jar input stream", e);
        }
      }
    }
    return description;
  }
Example #14
0
 /**
  * Gets the contents of a jar entry as a StringBuffer
  *
  * @param jar The jar to extract from
  * @param entryName The name of the entry to be extracted
  * @return The contents of a jar entry, or null if no such entry exists
  * @throws IOException
  */
 public static StringBuffer getFileContents(JarFile jar, String entryName) throws IOException {
   JarEntry entry = jar.getJarEntry(entryName);
   if (entry == null) {
     return null;
   }
   BufferedInputStream entryStream = new BufferedInputStream(jar.getInputStream(entry));
   StringBuffer buffer = Utils.inputStreamToStringBuffer(entryStream);
   return buffer;
 }
  // Regression test for issue introduced by HARMONY-4569: signed archives containing files with
  // size 0 could not get verified.
  public void testJarVerificationEmptyEntry() throws IOException {
    Support_Resources.copyFile(resources, null, emptyEntryJar);
    File f = new File(resources, emptyEntryJar);

    JarFile jarFile = new JarFile(f);

    ZipEntry zipEntry = jarFile.getJarEntry(emptyEntry1);
    int res = jarFile.getInputStream(zipEntry).read(new byte[100], 0, 100);
    assertEquals("Wrong length of empty jar entry", -1, res);

    zipEntry = jarFile.getJarEntry(emptyEntry2);
    res = jarFile.getInputStream(zipEntry).read(new byte[100], 0, 100);
    assertEquals("Wrong length of empty jar entry", -1, res);

    zipEntry = jarFile.getJarEntry(emptyEntry3);
    res = jarFile.getInputStream(zipEntry).read();
    assertEquals("Wrong length of empty jar entry", -1, res);
  }
    /*
     * Returns the JAR Resource for the specified name.
     */
    Resource getResource(final String name, boolean check) {
      final JarEntry entry = jar.getJarEntry(name);
      if (entry != null) return checkResource(name, check, entry);

      if (index == null) return null;

      HashSet visited = new HashSet();
      return getResource(name, check, visited);
    }
Example #17
0
 static boolean isConnectorJar(File file) {
   try (JarFile jarFile = new JarFile(file)) {
     @SuppressWarnings("resource")
     JarEntry entry = jarFile.getJarEntry(ConfigurationConstants.FILENAME_CONNECTOR_PROPERTIES);
     return entry != null;
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
Example #18
0
 private JarEntryInfo findJarEntry(String sName) {
   for (JarFileInfo jarFileInfo : lstJarFile) {
     JarFile jarFile = jarFileInfo.jarFile;
     JarEntry jarEntry = jarFile.getJarEntry(sName);
     if (jarEntry != null) {
       return new JarEntryInfo(jarFileInfo, jarEntry);
     }
   }
   return null;
 } // findJarEntry()
Example #19
0
  public InputStream getInputStream(URI uri) throws IOException {
    String jar = getJar(uri);
    String path = getPath(uri);

    @SuppressWarnings("resource")
    // jarFile's are closed the moment when there are no more references to it.
    JarFile jarFile = new JarFile(jar);
    JarEntry jarEntry = jarFile.getJarEntry(path);
    return jarFile.getInputStream(jarEntry);
  }
Example #20
0
 private void loadRepositories(JarFile jarFile) throws IOException {
   JarEntry repositoriesXML = jarFile.getJarEntry("repositories.xml");
   if (repositoriesXML != null) {
     InputStream input = jarFile.getInputStream(repositoriesXML);
     RepositoryDecoder repositoryDecoder = new RepositoryDecoder();
     Collection<RemoteRepository> repositories = new ArrayList<RemoteRepository>();
     Collections.addAll(repositories, (RemoteRepository[]) repositoryDecoder.decode(input));
     setRepositories(repositories);
   }
 }
  /** The jar is intact, but the entry object is modified. */
  public void testJarVerificationModifiedEntry() throws IOException {
    Support_Resources.copyFile(resources, null, integrateJar);
    File f = new File(resources, integrateJar);

    JarFile jarFile = new JarFile(f);
    ZipEntry zipEntry = jarFile.getJarEntry(integrateJarEntry);
    zipEntry.setSize(zipEntry.getSize() + 1);
    jarFile.getInputStream(zipEntry).skip(Long.MAX_VALUE);

    jarFile = new JarFile(f);
    zipEntry = jarFile.getJarEntry(integrateJarEntry);
    zipEntry.setSize(zipEntry.getSize() - 1);
    try {
      // jarFile.getInputStream(zipEntry).skip(Long.MAX_VALUE);
      jarFile.getInputStream(zipEntry).read(new byte[5000], 0, 5000);
      fail("SecurityException expected");
    } catch (SecurityException e) {
      // desired
    }
  }
Example #22
0
 private List<JarEntryInfo> findJarEntries(String sName) {
   List<JarEntryInfo> lst = new ArrayList<JarEntryInfo>();
   for (JarFileInfo jarFileInfo : lstJarFile) {
     JarFile jarFile = jarFileInfo.jarFile;
     JarEntry jarEntry = jarFile.getJarEntry(sName);
     if (jarEntry != null) {
       lst.add(new JarEntryInfo(jarFileInfo, jarEntry));
     }
   }
   return lst;
 } // findJarEntries()
 private void verifyCustomWsdlFileCorrectness(JarFile outputWar) throws IOException {
   try (InputStream inputWsdlStream =
           getClass().getResourceAsStream(customWsdlFilePath.toString());
       InputStream fromWarInputStream =
           outputWar.getInputStream(
               outputWar.getJarEntry(WEB_INF_CLASSES + WSDL_FILE_NAMES_PARAM_VALUE))) {
     final String customWsdlInput = readStringFromInputStream(inputWsdlStream);
     final String customWsdlInWar = readStringFromInputStream(fromWarInputStream);
     assertEquals(customWsdlInput, customWsdlInWar);
   }
 }
 private Certificate[] getCertificates(final File container, final String entry)
     throws IOException {
   if (container.isDirectory()) {
     return null;
   }
   final JarFile jarFile = this.jarFiles.get(container);
   if (jarFile == null) {
     return null;
   }
   final JarEntry ent = jarFile.getJarEntry(entry);
   return (Certificate[]) ((ent == null) ? null : ent.getCertificates());
 }
Example #25
0
  protected LoadServiceResource tryResourceFromJarURL(
      SearchState state, String baseName, SuffixType suffixType) {
    // if a jar or file URL, return load service resource directly without further searching
    LoadServiceResource foundResource = null;
    if (baseName.startsWith("jar:")) {
      for (String suffix : suffixType.getSuffixes()) {
        String namePlusSuffix = baseName + suffix;
        try {
          URL url = new URL(namePlusSuffix);
          debugLogTry("resourceFromJarURL", url.toString());
          if (url.openStream() != null) {
            foundResource = new LoadServiceResource(url, namePlusSuffix);
            debugLogFound(foundResource);
          }
        } catch (FileNotFoundException e) {
        } catch (MalformedURLException e) {
          throw runtime.newIOErrorFromException(e);
        } catch (IOException e) {
          throw runtime.newIOErrorFromException(e);
        }
        if (foundResource != null) {
          state.loadName = resolveLoadName(foundResource, namePlusSuffix);
          break; // end suffix iteration
        }
      }
    } else if (baseName.startsWith("file:") && baseName.indexOf("!/") != -1) {
      for (String suffix : suffixType.getSuffixes()) {
        String namePlusSuffix = baseName + suffix;
        try {
          String jarFile = namePlusSuffix.substring(5, namePlusSuffix.indexOf("!/"));
          JarFile file = new JarFile(jarFile);
          String filename = namePlusSuffix.substring(namePlusSuffix.indexOf("!/") + 2);
          String canonicalFilename = canonicalizePath(filename);

          debugLogTry("resourceFromJarURL", canonicalFilename.toString());
          if (file.getJarEntry(canonicalFilename) != null) {
            foundResource =
                new LoadServiceResource(
                    new URL("jar:file:" + jarFile + "!/" + canonicalFilename), namePlusSuffix);
            debugLogFound(foundResource);
          }
        } catch (Exception e) {
        }
        if (foundResource != null) {
          state.loadName = resolveLoadName(foundResource, namePlusSuffix);
          break; // end suffix iteration
        }
      }
    }

    return foundResource;
  }
Example #26
0
  public boolean exists(URI uri) {
    try {
      String jar = getJar(uri);
      String path = getPath(uri);

      JarFile jarFile = new JarFile(jar);
      JarEntry jarEntry = jarFile.getJarEntry(path);
      jarFile.close();
      return (jarEntry != null);
    } catch (IOException e) {
      return false;
    }
  }
 public static void addJar(JarFile jar) throws IOException {
   Manifest manifest = jar.getManifest();
   String atList = manifest.getMainAttributes().getValue("FMLAT");
   if (atList == null) return;
   for (String at : atList.split(" ")) {
     JarEntry jarEntry = jar.getJarEntry("META-INF/" + at);
     if (jarEntry != null) {
       embedded.put(
           String.format("%s!META-INF/%s", jar.getName(), at),
           new JarByteSource(jar, jarEntry).asCharSource(Charsets.UTF_8).read());
     }
   }
 }
Example #28
0
  public static ResourceBundle loadLocale(String localeString) {

    JarFile jarFile;
    try {
      jarFile = new JarFile(MyPetPlugin.getPlugin().getFile());
    } catch (IOException ignored) {
      return null;
    }

    ResourceBundle newLocale = null;
    try {
      JarEntry jarEntry = jarFile.getJarEntry("locale/MyPet_" + localeString + ".properties");
      if (jarEntry != null) {
        java.util.ResourceBundle defaultBundle =
            new PropertyResourceBundle(
                new InputStreamReader(jarFile.getInputStream(jarEntry), "UTF-8"));
        newLocale = new ResourceBundle(defaultBundle);
      } else {
        throw new IOException();
      }
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
      DebugLogger.printThrowable(e);
    } catch (IOException ignored) {
    }

    File localeFile =
        new File(
            MyPetPlugin.getPlugin().getDataFolder()
                + File.separator
                + "locale"
                + File.separator
                + "MyPet_"
                + localeString
                + ".properties");
    if (localeFile.exists()) {
      if (newLocale == null) {
        newLocale = new ResourceBundle();
      }
      try {
        java.util.ResourceBundle optionalBundle =
            new PropertyResourceBundle(
                new InputStreamReader(new FileInputStream(localeFile), "UTF-8"));
        newLocale.addExtensionBundle(optionalBundle);
      } catch (IOException e) {
        e.printStackTrace();
        DebugLogger.printThrowable(e);
      }
    }
    return newLocale;
  }
Example #29
0
  public long lastModified(URI uri) throws IOException {
    String jar = getJar(uri);
    String path = getPath(uri);

    JarFile jarFile = new JarFile(jar);
    JarEntry jarEntry = jarFile.getJarEntry(path);
    jarFile.close();

    if (jarEntry == null) {
      throw new FileNotFoundException(uri.toString());
    }

    return jarEntry.getTime();
  }
Example #30
0
  /** @see java.lang.ClassLoader#findResources(java.lang.String) */
  @Override
  public Enumeration<URL> findResources(String resourceName) throws IOException {
    ArrayList<URL> cachedUrls = resourceAllCache.get(resourceName);
    if (cachedUrls != null) return Collections.enumeration(cachedUrls);

    ArrayList<URL> urlList = new ArrayList<>();
    int classesDirectoryListSize = classesDirectoryList.size();
    for (int i = 0; i < classesDirectoryListSize; i++) {
      File classesDir = classesDirectoryList.get(i);
      File testFile = new File(classesDir.getAbsolutePath() + "/" + resourceName);
      try {
        if (testFile.exists() && testFile.isFile()) urlList.add(testFile.toURI().toURL());
      } catch (MalformedURLException e) {
        System.out.println(
            "Error making URL for ["
                + resourceName
                + "] in classes directory ["
                + classesDir
                + "]: "
                + e.toString());
      }
    }
    int jarFileListSize = jarFileList.size();
    for (int i = 0; i < jarFileListSize; i++) {
      JarFile jarFile = jarFileList.get(i);
      JarEntry jarEntry = jarFile.getJarEntry(resourceName);
      if (jarEntry != null) {
        try {
          String jarFileName = jarFile.getName();
          if (jarFileName.contains("\\")) jarFileName = jarFileName.replace('\\', '/');
          urlList.add(new URL("jar:file:" + jarFileName + "!/" + jarEntry));
        } catch (MalformedURLException e) {
          System.out.println(
              "Error making URL for ["
                  + resourceName
                  + "] in jar ["
                  + jarFile
                  + "]: "
                  + e.toString());
        }
      }
    }
    // add all resources found in parent loader too
    Enumeration<URL> superResources = getParent().getResources(resourceName);
    while (superResources.hasMoreElements()) urlList.add(superResources.nextElement());
    resourceAllCache.putIfAbsent(resourceName, urlList);
    // System.out.println("finding all resources with name " + resourceName + " got " + urlList);
    return Collections.enumeration(urlList);
  }