List<ResourceProxy> handleJarResource(File jarResource) throws Exception {
    List<ResourceProxy> jarResources = new ArrayList<ResourceProxy>();

    String frontRelativePath = jarResource.getName();

    frontRelativePath = frontRelativePath.replaceAll(JAR_EXTENSION, ""); // $NON-NLS-1$
    frontRelativePath += JAR_RESOURCE_SUFFIX;

    InputStream input = new FileInputStream(jarResource);
    JarInputStream zipInput = new JarInputStream(input);

    ZipEntry zipEntry = zipInput.getNextEntry();
    while (zipEntry != null) {
      String resourceEntryName = zipEntry.getName();
      resourceEntryName = resourceEntryName.replace("\\", SLASH); // $NON-NLS-1$

      if (isValidResource(resourceEntryName) && (!resourceEntryName.contains(META_INF_DIR_NAME))) {
        String relativePath = frontRelativePath + File.separator + resourceEntryName;
        relativePath = relativePath.replace("\\", File.separator); // $NON-NLS-1$
        relativePath = relativePath.replace(SLASH, File.separator);
        jarResources.add(
            new ResourceProxy(
                new File(jarResource.getAbsolutePath() + SLASH + resourceEntryName),
                relativePath)); //$NON-NLS-1$ //$NON-NLS-2$
      }

      zipEntry = zipInput.getNextEntry();
    }

    return jarResources;
  }
 /**
  * Returns a list which contains the pathes of all files which are included in the given url. This
  * method expects as the url param a jar.
  *
  * @param url url of the jar file
  * @return full qualified paths of the contained files
  * @throws Exception
  */
 private List getContainedFilePaths(URL url) throws Exception {
   JarInputStream jis = new JarInputStream(url.openStream());
   ZipEntry zentry = null;
   ArrayList fullNames = new ArrayList();
   while ((zentry = jis.getNextEntry()) != null) {
     String name = zentry.getName();
     // Add only files, no directory entries.
     if (!zentry.isDirectory()) fullNames.add(name);
   }
   jis.close();
   return (fullNames);
 }
Example #3
0
  protected void analyzeJar(Resource res) throws BuildException {
    log("Analyze jar file " + res, Project.MSG_VERBOSE);

    try {
      final JarInputStream jarStream = new JarInputStream(res.getInputStream());

      ZipEntry ze = jarStream.getNextEntry();
      while (null != ze) {
        final String fileName = ze.getName();
        if (fileName.endsWith(".class")) {
          log("Analyze jar class file " + fileName, Project.MSG_VERBOSE);
          asmAnalyser.analyseClass(jarStream, fileName);
        }
        ze = jarStream.getNextEntry();
      }
    } catch (final Exception e) {
      e.printStackTrace();
      throw new BuildException(
          "Failed to analyze class-file " + res + ", exception=" + e, getLocation());
    }
  }
Example #4
0
 public static byte[] addJarEntry(byte[] jarToUpdate, String entryName, byte[] entryContent)
     throws IOException {
   ByteArrayOutputStream out = null;
   ByteArrayInputStream bais = null;
   JarOutputStream jos = null;
   JarInputStream jis = null;
   byte[] buffer = new byte[4096];
   try {
     bais = new ByteArrayInputStream(jarToUpdate);
     jis = new JarInputStream(bais);
     out = new ByteArrayOutputStream();
     jos = new JarOutputStream(out);
     JarEntry inEntry;
     while ((inEntry = (JarEntry) jis.getNextEntry()) != null) {
       if (!inEntry.getName().equals(entryName)) {
         jos.putNextEntry(new JarEntry(inEntry));
       } else {
         throw new IllegalArgumentException(
             "Jar entry " + entryName + " already exists in jar to update");
       }
       int len;
       while ((len = jis.read(buffer)) > 0) {
         jos.write(buffer, 0, len);
       }
       jos.flush();
     }
     JarEntry entry = new JarEntry(entryName);
     jos.putNextEntry(entry);
     jos.write(entryContent);
     jos.closeEntry();
     jos.finish();
     out.flush();
     return out.toByteArray();
   } finally {
     if (jos != null) {
       jos.close();
     }
     if (out != null) {
       out.close();
     }
     if (jis != null) {
       jis.close();
     }
   }
 }
  /*
   Parses a <properties entry="<url>"/>
   and then reads a property specified by <url>
  */
  private static void setProperties(Config compConf, XmlPullParser parser, Bundle declaringBundle)
      throws IllegalXMLException, XmlPullParserException, IOException {
    String entry = null;

    for (int i = 0; i < parser.getAttributeCount(); i++) {
      if (parser.getAttributeName(i).equals("entry")) {
        entry = parser.getAttributeValue(i);
      } else {
        unrecognizedAttr(parser, i); // throws exception
      }
    }

    if (entry == null) {
      missingAttr(parser, "entry"); // throws exception
    }

    // read a property-file and adds it contents to conf's properties.
    Properties dict = new Properties();
    String bundleLocation = declaringBundle.getLocation();

    JarInputStream jis = new JarInputStream(new URL(bundleLocation).openStream());
    ZipEntry zipEntry;

    while ((zipEntry = jis.getNextEntry()) != null && !zipEntry.getName().equals(entry))
      /* skip */ ;

    if (zipEntry == null) {
      throw new IOException("Did not find requested entry " + entry);
    }

    dict.load(jis);

    for (Enumeration e = dict.keys(); e.hasMoreElements(); ) {
      Object key = e.nextElement();
      compConf.setProperty((String) key, dict.get(key));
    }

    // done reading file.

    skip(parser);
  }
 /**
  * Returns the qualified class name for the given class. This method expects as the url param a
  * jar file which contains the given class. It scans the zip entries of the jar file.
  *
  * @param url url of the jar file which contains the class
  * @param className short name of the class for which the full name should be resolved
  * @return full qualified class name
  * @throws Exception
  */
 private String getFullClassName(URL url, String className) throws Exception {
   JarInputStream jis = new JarInputStream(url.openStream());
   ZipEntry zentry = null;
   while ((zentry = jis.getNextEntry()) != null) {
     String name = zentry.getName();
     int lastPos = name.lastIndexOf(".class");
     if (lastPos < 0) {
       continue; // No class file.
     }
     name = name.replace('/', '.');
     int pos = -1;
     if (className != null) {
       pos = name.indexOf(className);
     }
     if (name.length() == pos + className.length() + 6) // "Main" class
     // found
     {
       jis.close();
       return (name.substring(0, lastPos));
     }
   }
   jis.close();
   return (null);
 }
Example #7
0
  /**
   * Extract a kar from a given URI into a repository dir and resource dir and populate
   * shouldInstallFeatures and featureRepos
   *
   * @param repoDir directory to write the repository contents of the kar to
   * @param resourceDir directory to write the resource contents of the kar to
   */
  public void extract(File repoDir, File resourceDir) {
    InputStream is = null;
    JarInputStream zipIs = null;
    FeatureDetector featureDetector = new FeatureDetector();
    this.featureRepos = new ArrayList<URI>();
    this.shouldInstallFeatures = true;

    try {
      is = karUri.toURL().openStream();
      repoDir.mkdirs();

      if (!repoDir.isDirectory()) {
        throw new RuntimeException("The KAR file " + karUri + " is already installed");
      }

      LOGGER.debug("Uncompress the KAR file {} into directory {}", karUri, repoDir);
      zipIs = new JarInputStream(is);
      boolean scanForRepos = true;

      Manifest manifest = zipIs.getManifest();
      if (manifest != null) {
        Attributes attr = manifest.getMainAttributes();
        String featureStartSt =
            (String) attr.get(new Attributes.Name(MANIFEST_ATTR_KARAF_FEATURE_START));
        if ("false".equals(featureStartSt)) {
          shouldInstallFeatures = false;
        }
        String featureReposAttr =
            (String) attr.get(new Attributes.Name(MANIFEST_ATTR_KARAF_FEATURE_REPOS));
        if (featureReposAttr != null) {
          featureRepos.add(new URI(featureReposAttr));
          scanForRepos = false;
        }
      }

      ZipEntry entry = zipIs.getNextEntry();
      while (entry != null) {
        if (entry.getName().startsWith("repository")) {
          String path = entry.getName().substring("repository/".length());
          File destFile = new File(repoDir, path);
          extract(zipIs, entry, destFile);
          if (scanForRepos && featureDetector.isFeaturesRepository(destFile)) {
            Map map = new HashMap<>();
            String uri = Parser.pathToMaven(path, map);
            if (map.get("classifier") != null
                && ((String) map.get("classifier")).equalsIgnoreCase("features"))
              featureRepos.add(URI.create(uri));
            else featureRepos.add(destFile.toURI());
          }
        }

        if (entry.getName().startsWith("resource")) {
          String path = entry.getName().substring("resource/".length());
          File destFile = new File(resourceDir, path);
          extract(zipIs, entry, destFile);
        }
        entry = zipIs.getNextEntry();
      }
    } catch (Exception e) {
      throw new RuntimeException(
          "Error extracting kar file " + karUri + " into dir " + repoDir + ": " + e.getMessage(),
          e);
    } finally {
      closeStream(zipIs);
      closeStream(is);
    }
  }
Example #8
0
      private void enumeratePathArchive(final String archive) throws IOException {
        final boolean trace1 = m_trace1;

        final File fullArchive = new File(m_currentPathDir, archive);

        JarInputStream in = null;
        try {
          // note: Sun's JarFile uses native code and has been known to
          // crash the JVM in some builds; however, it uses random file
          // access and can find "bad" manifests that are not the first
          // entries in their archives (which JarInputStream can't do);
          // [bugs: 4263225, 4696354, 4338238]
          //
          // there is really no good solution here but as a compromise
          // I try to read the manifest again via a JarFile if the stream
          // returns null for it:

          in =
              new JarInputStream(
                  new BufferedInputStream(new FileInputStream(fullArchive), 32 * 1024));

          final IPathHandler handler = m_handler;

          Manifest manifest = in.getManifest(); // can be null
          if (manifest == null) manifest = readManifestViaJarFile(fullArchive); // can be null

          handler.handleArchiveStart(m_currentPathDir, new File(archive), manifest);

          // note: this loop does not skip over the manifest-related
          // entries [the handler needs to be smart about that]
          for (ZipEntry entry; (entry = in.getNextEntry()) != null; ) {
            // TODO: handle nested archives

            if (trace1)
              m_log.trace1(
                  "enumeratePathArchive", "processing archive entry [" + entry.getName() + "] ...");
            handler.handleArchiveEntry(in, entry);
            in.closeEntry();
          }

          // TODO: this needs major testing
          if (m_processManifest) {
            // note: JarInputStream only reads the manifest if it the
            // first jar entry
            if (manifest == null) manifest = in.getManifest();
            if (manifest != null) {
              final Attributes attributes = manifest.getMainAttributes();
              if (attributes != null) {
                // note: Sun's documentation says that multiple Class-Path:
                // entries are merged sequentially
                // (http://java.sun.com/products/jdk/1.2/docs/guide/extensions/spec.html)
                // however, their own code does not implement this
                final String jarClassPath = attributes.getValue(Attributes.Name.CLASS_PATH);
                if (jarClassPath != null) {
                  final StringTokenizer tokenizer = new StringTokenizer(jarClassPath);
                  for (int p = 1; tokenizer.hasMoreTokens(); ) {
                    final String relPath = tokenizer.nextToken();

                    final File archiveParent = fullArchive.getParentFile();
                    final File path =
                        archiveParent != null
                            ? new File(archiveParent, relPath)
                            : new File(relPath);

                    final String fullPath =
                        m_canonical ? Files.canonicalizePathname(path.getPath()) : path.getPath();

                    if (m_pathSet.add(fullPath)) {
                      if (m_verbose)
                        m_log.verbose("  added manifest Class-Path entry [" + path + "]");
                      m_path.add(
                          m_pathIndex + (p++), path); // insert after the current m_path entry
                    }
                  }
                }
              }
            }
          }
        } catch (FileNotFoundException fnfe) // ignore: this should not happen
        {
          if ($assert.ENABLED) throw fnfe;
        } finally {
          if (in != null)
            try {
              in.close();
            } catch (Exception ignore) {
            }
        }
      }