/**
   * @see com.liferay.modulesadmin.portlet.ModulesAdminPortlet#getBundle( BundleContext,
   *     InputStream)
   */
  public Bundle getBundle(BundleContext bundleContext, InputStream inputStream)
      throws PortalException {

    try {
      if (inputStream.markSupported()) {

        // 1 megabyte is more than enough for even the largest manifest
        // file

        inputStream.mark(1024 * 1000);
      }

      JarInputStream jarInputStream = new JarInputStream(inputStream);

      Manifest manifest = jarInputStream.getManifest();

      if (inputStream.markSupported()) {
        inputStream.reset();
      }

      Attributes attributes = manifest.getMainAttributes();

      String bundleSymbolicNameAttributeValue = attributes.getValue(Constants.BUNDLE_SYMBOLICNAME);

      Parameters parameters = OSGiHeader.parseHeader(bundleSymbolicNameAttributeValue);

      Set<String> bundleSymbolicNameSet = parameters.keySet();

      Iterator<String> bundleSymbolicNameIterator = bundleSymbolicNameSet.iterator();

      String bundleSymbolicName = bundleSymbolicNameIterator.next();

      String bundleVersionAttributeValue = attributes.getValue(Constants.BUNDLE_VERSION);

      Version bundleVersion = Version.parseVersion(bundleVersionAttributeValue);

      for (Bundle bundle : bundleContext.getBundles()) {
        Version curBundleVersion = Version.parseVersion(String.valueOf(bundle.getVersion()));

        if (bundleSymbolicName.equals(bundle.getSymbolicName())
            && bundleVersion.equals(curBundleVersion)) {

          return bundle;
        }
      }

      return null;
    } catch (IOException ioe) {
      throw new PortalException(ioe);
    }
  }
Example #2
0
  public static boolean extractJarDir(String jarfile, String outfile) throws Exception {
    long filesize = new File(jarfile).length();
    JarInputStream jar = new JarInputStream(new FileInputStream(jarfile));
    // while (true) {
    //	JarEntry jarentry = (JarEntry)jar.getNextJarEntry();
    //	if (jarentry==null) break;
    //	String maindir = jarentry.getName();
    //	// get rid of "./" and "/" prefix
    //	if (maindir.startsWith("."))
    //		maindir = maindir.substring(1);
    //	if (maindir.startsWith(File.separator))
    //		maindir = maindir.substring(1);
    //	// Find manifest
    //	System.out.println(maindir);
    //	if (maindir.equals("META-INF/MANIFEST.MF")) {
    //		java.io.InputStream ins = jar;

    java.io.FileOutputStream outs = new java.io.FileOutputStream(outfile);
    Manifest man = jar.getManifest();
    if (man == null) return false;
    man.write(outs);
    byte[] buf = ("MIDlet-Jar-Size: " + filesize).getBytes();
    outs.write(buf, 0, buf.length);
    outs.close();
    //		// copy buffered (is a lot faster than one byte at a time)
    //		byte[] buf = new byte[8192];
    //		int total_bytes=0;
    //		while (true) {
    //			//outs.write(ins.read());
    //			int len = ins.read(buf);
    //			if (len < 0) break;
    //			outs.write(buf,0,len);
    //			total_bytes += len;
    //		}
    //		buf = ("MIDlet-Jar-Size: "+total_bytes).getBytes();
    //		outs.write(buf,0,buf.length);
    //		outs.close();
    //		//ins.close();
    //	}
    // }
    // return false;
    // remove empty lines from the generated jad which may have been
    // introduced by manifest write.
    // some systems have trouble with empty lines
    List<String> lines = new ArrayList<String>();
    BufferedReader in = new BufferedReader(new FileReader(outfile));
    while (true) {
      String line = in.readLine();
      if (line == null) break;
      lines.add(line);
    }
    in.close();
    PrintWriter outp = new PrintWriter(outfile);
    for (String s : lines) {
      if (s.trim().equals("")) continue;
      outp.println(s);
    }
    outp.close();
    return true;
  }
Example #3
0
 private Hashtable<String, String> getJarManifestAttributes(String path) {
   Hashtable<String, String> h = new Hashtable<String, String>();
   JarInputStream jis = null;
   try {
     cp.appendln(Color.black, "Looking for " + path);
     InputStream is = getClass().getResourceAsStream(path);
     if (is == null) {
       if (!path.endsWith("/MIRC.jar")) {
         cp.appendln(Color.red, "...could not find it.");
       } else {
         cp.appendln(
             Color.black,
             "...could not find it. [OK, this is a " + programName + " installation]");
       }
       return null;
     }
     jis = new JarInputStream(is);
     Manifest manifest = jis.getManifest();
     h = getManifestAttributes(manifest);
   } catch (Exception ex) {
     ex.printStackTrace();
   }
   if (jis != null) {
     try {
       jis.close();
     } catch (Exception ignore) {
     }
   }
   return h;
 }
Example #4
0
  public synchronized InputStream getInputStream(ZipEntry ze) throws IOException {
    if (ze == null) return null;
    try {
      JarInputStream is = new JarInputStream(super.getInputStream(wrappedJarFile));
      if (filename.equals(MANIFEST_NAME)) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        is.getManifest().write(baos);
        return new ByteArrayInputStream(baos.toByteArray());
      }
      try {
        JarEntry entry;
        while ((entry = is.getNextJarEntry()) != null) {
          if (entry.getName().equals(ze.getName())) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            copy(is, baos);
            return new ByteArrayInputStream(baos.toByteArray());
          }
        }
      } finally {
        is.close();
      }
    } catch (IOException e) {
      throw new RuntimeException("Undefined Error", e);
    }

    throw new RuntimeException("Entry not found : " + ze.getName());
  }
Example #5
0
  private Set<Resource> addProjectBuildBundles(Resolver resolver) {
    if (!Project.BNDFILE.equals(runFile.getName())) return Collections.emptySet();

    Set<Resource> result = new HashSet<Resource>();
    try {

      Project model = Workspace.getProject(runFile.getProject().getLocation().toFile());
      for (Builder builder : model.getSubBuilders()) {
        File file = new File(model.getTarget(), builder.getBsn() + ".jar");
        if (file.isFile()) {
          JarInputStream stream = null;
          try {
            stream = new JarInputStream(new FileInputStream(file));
            Manifest manifest = stream.getManifest();

            Resource resource = helper.createResource(manifest.getMainAttributes());
            result.add(resource);
            resolver.add(resource);
          } catch (IOException e) {
            Plugin.logError("Error reading project bundle " + file, e);
          } finally {
            if (stream != null) stream.close();
          }
        }
      }
    } catch (Exception e) {
      Plugin.logError("Error getting builders for project: " + runFile.getProject(), e);
    }
    return result;
  }
Example #6
0
 /*
  * Returns the Manifest for the specified JAR file name.
  */
 private static Manifest loadManifest(String fn) {
   try (FileInputStream fis = new FileInputStream(fn);
       JarInputStream jis = new JarInputStream(fis, false)) {
     return jis.getManifest();
   } catch (IOException e) {
     return null;
   }
 }
Example #7
0
 /*
  * Returns the Manifest for the specified JAR file name.
  */
 private static Manifest loadManifest(String fn) {
   try {
     FileInputStream fis = new FileInputStream(fn);
     JarInputStream jis = new JarInputStream(fis, false);
     Manifest man = jis.getManifest();
     jis.close();
     return man;
   } catch (IOException e) {
     return null;
   }
 }
  /** Get the main attributes for the jar file */
  private static Attributes getJarMainAttributes(final File file) {
    debug("getJarMainAttributes: " + file);

    try {
      try (final JarInputStream jarInputStream = new JarInputStream(new FileInputStream(file))) {
        return jarInputStream.getManifest().getMainAttributes();
      }
    } catch (IOException e) {
      return null;
    }
  }
 private void verifyGeneratedWarCorrectness(boolean withKeystoreFile, boolean withCustomWsdl)
     throws IOException {
   try (JarInputStream jarInputStream =
       new JarInputStream(getClass().getResourceAsStream(inputWarFilePath.toString()))) {
     final JarFile outputWar = new JarFile(outputWarFile);
     assertEquals(
         getJarInputStreamEntryNames(jarInputStream),
         getNonAddedOutputWarFileEntryNames(outputWar));
     assertNotNull(jarInputStream.getManifest());
     assertEquals(jarInputStream.getManifest(), outputWar.getManifest());
     verifyPropertyFileCorrectness(outputWar);
     verifyPresenceOfInternalKeyStore(outputWar);
     if (withKeystoreFile) {
       verifyKeystoreFilePresence(outputWar);
     }
     if (withCustomWsdl) {
       verifyCustomWsdlFileCorrectness(outputWar);
     }
   }
 }
 /**
  * Load an extension into this meterpreter. Called from {@link core_loadlib}.
  *
  * @param data The extension jar's content as a byte array
  */
 public String[] loadExtension(byte[] data) throws Exception {
   ClassLoader classLoader = getClass().getClassLoader();
   if (loadExtensions) {
     URL url = MemoryBufferURLConnection.createURL(data, "application/jar");
     classLoader = new URLClassLoader(new URL[] {url}, classLoader);
   }
   JarInputStream jis = new JarInputStream(new ByteArrayInputStream(data));
   String loaderName = (String) jis.getManifest().getMainAttributes().getValue("Extension-Loader");
   ExtensionLoader loader = (ExtensionLoader) classLoader.loadClass(loaderName).newInstance();
   commandManager.resetNewCommands();
   loader.load(commandManager);
   return commandManager.getNewCommands();
 }
 private Set<String> getJarInputStreamEntryNames(JarInputStream jarInputStream)
     throws IOException {
   Set<String> entryNames = new HashSet<>();
   JarEntry jarEntry = jarInputStream.getNextJarEntry();
   while (jarEntry != null) {
     entryNames.add(jarEntry.getName());
     jarEntry = jarInputStream.getNextJarEntry();
   }
   if (jarInputStream.getManifest() != null) {
     entryNames.add(MANIFEST_JAR_ENTRY_NAME);
   }
   return entryNames;
 }
  /*
   * Extract the META-INF/MANIFEST.MF file from an artifact
   */
  private Manifest getManifest(String bundle, Object artifact)
      throws ArtifactResolutionException, ArtifactNotFoundException, ZipException, IOException {
    ZipFile file = null;
    if (!(artifact instanceof Artifact)) {
      // not resolved as mvn artifact, so it's non-mvn protocol, just use the
      // CustomBundleURLStreamHandlerFactory
      // to open stream
      InputStream is = null;
      try {
        is = new BufferedInputStream(new URL(bundle).openStream());
      } catch (Exception e) {
        getLog().warn("Error while opening artifact", e);
      }

      try {
        is.mark(256 * 1024);
        JarInputStream jar = new JarInputStream(is);
        Manifest m = jar.getManifest();
        if (m == null) {
          throw new IOException("Manifest not present in the first entry of the zip");
        }

        return m;
      } finally {
        if (is != null) { // just in case when we did not open bundle
          is.close();
        }
      }
    } else {
      Artifact mvnArtifact = (Artifact) artifact;
      File localFile = new File(localRepo.pathOf(mvnArtifact));
      if (localFile.exists()) {
        // avoid going over to the repository if the file is already on
        // the disk
        file = new ZipFile(localFile);
      } else {
        resolver.resolve(mvnArtifact, remoteRepos, localRepo);
        file = new ZipFile(mvnArtifact.getFile());
      }
      // let's replace syserr for now to hide warnings being issues by the Manifest reading process
      PrintStream original = System.err;
      try {
        System.setErr(new PrintStream(new ByteArrayOutputStream()));
        Manifest manifest =
            new Manifest(file.getInputStream(file.getEntry("META-INF/MANIFEST.MF")));
        return manifest;
      } finally {
        System.setErr(original);
      }
    }
  }
Example #13
0
  private void loadExternalJavaPlugin(File jar) throws Exception {
    JarInputStream jis = new JarInputStream(new FileInputStream(jar));
    Manifest mf = jis.getManifest();
    if (mf != null) {
      String pluginClassName = mf.getMainAttributes().getValue("ChkBugReport-Plugin");
      URL urls[] = {jar.toURI().toURL()};
      URLClassLoader cl = new URLClassLoader(urls, getClass().getClassLoader());
      Class<?> extClass = Class.forName(pluginClassName, true, cl);
      ExternalPlugin ext = (ExternalPlugin) extClass.newInstance();

      // Note: printOut will not work here, since a listener is not set yet
      System.out.println("Loading plugins from: " + jar.getAbsolutePath());
      ext.initExternalPlugin(this);
    }
  }
 private static Attributes loadMainAttributes(final File file) {
   Attributes mainAttributes = null;
   try {
     try (final JarInputStream jarInputStream = new JarInputStream(new FileInputStream(file))) {
       final Manifest manifest = jarInputStream.getManifest();
       if (null != manifest) {
         mainAttributes = manifest.getMainAttributes();
       }
     }
   } catch (IOException e) {
     e.printStackTrace(System.err);
     log.warn(e.getMessage() + ": " + file.getAbsolutePath());
   }
   return mainAttributes;
 }
  /**
   * Attempt to verify that a Jar file is signed. All files (aside from ones in META-INF) must be
   * signed and trusted.
   *
   * @param in input stream
   * @throws SecurityException throw on verification failure
   * @throws IOException on I/O error
   */
  @SuppressWarnings("resource")
  public void verifyJar(InputStream in) throws IOException {
    JarInputStream jarFile = null;

    try {
      jarFile = new JarInputStream(in);
      Manifest manifest = jarFile.getManifest();
      if (manifest == null) {
        throw new SecurityException("The given file was not digitally signed");
      }

      // Ensure all the entries' signatures verify correctly
      byte[] buffer = new byte[8192];
      JarEntry entry;
      while ((entry = jarFile.getNextJarEntry()) != null) {
        if (entry.isDirectory()) continue;

        do {} while (jarFile.read(buffer, 0, buffer.length) != -1);

        Certificate[] certs = entry.getCertificates();
        if (isMetaInf(entry.getName())) {
          continue;
        } else if (certs == null || certs.length == 0) {
          throw new SecurityException("The archive contains files that are not digitally signed");
        } else {
          int i = 0;
          boolean verified = false;
          while (i < certs.length) {
            X509Certificate[] chain = findChain(certs, i);
            try {
              verify(chain);
              verified = true;
              break;
            } catch (SecurityException e) {
            }
            i += chain.length;
          }

          if (!verified) {
            throw new SecurityException(
                "The file(s) are signed by an entity that is not registered as 'trusted' with the launcher");
          }
        }
      }
    } finally {
      LauncherUtils.close(jarFile);
    }
  }
Example #16
0
  /**
   * Answer the manifest for this container (if possible). Manifest is cached until the file is
   * renewed.
   */
  public Manifest getManifest() throws Exception {
    if (getError() != null || getFile() == null) return null;

    if (manifestTime < getFile().lastModified()) {
      InputStream in = new FileInputStream(getFile());
      try {
        JarInputStream jin = new JarInputStream(in);
        manifest = jin.getManifest();
        jin.close();
        manifestTime = getFile().lastModified();
      } finally {
        in.close();
      }
    }
    return manifest;
  }
 /** Return true if the file is a valid jar plugin file */
 public static boolean isValidJarPlugin(final File file) {
   try {
     try (final JarInputStream jarInputStream = new JarInputStream(new FileInputStream(file))) {
       final Manifest manifest = jarInputStream.getManifest();
       if (null == manifest) {
         return false;
       }
       final Attributes mainAttributes = manifest.getMainAttributes();
       validateJarManifest(mainAttributes);
     }
     return true;
   } catch (IOException | InvalidManifestException e) {
     log.error(file.getAbsolutePath() + ": " + e.getMessage());
     return false;
   }
 }
Example #18
0
  /**
   * Reads the source JAR copying entries to the dest JAR. The web.xml and portlet.xml are cached
   * and after the entire archive is copied (minus the web.xml) a re-written web.xml is generated
   * and written to the destination JAR.
   */
  protected void assembleWar(File source, File dest, String dispatchServletClass)
      throws IOException {
    final JarInputStream jarIn = new JarInputStream(new FileInputStream(source));
    // Create the output JAR stream, copying the Manifest
    final Manifest manifest = jarIn.getManifest();
    // TODO add pluto notes to the Manifest?

    final JarOutputStream jarOut;
    if (manifest != null) {
      jarOut = new JarOutputStream(new FileOutputStream(dest), manifest);
    } else {
      jarOut = new JarOutputStream(new FileOutputStream(dest));
    }

    try {
      JarStreamingAssembly.assembleStream(jarIn, jarOut, dispatchServletClass);
    } finally {
      jarIn.close();
      jarOut.close();
    }
  }
Example #19
0
  /**
   * Processes the given {@code url} and adds all associated class files to the given {@code
   * classNames}.
   */
  private void processUrl(Set<String> classNames, URL url) {

    if (url.getPath().endsWith(".jar")) {
      try {
        InputStream urlInput = url.openStream();
        try {

          @SuppressWarnings("all")
          JarInputStream jarInput = new JarInputStream(urlInput);
          Manifest manifest = jarInput.getManifest();
          if (manifest != null) {
            Attributes attributes = manifest.getMainAttributes();
            if (attributes != null
                && Boolean.parseBoolean(attributes.getValue(INCLUDE_ATTRIBUTE))) {

              for (JarEntry entry; (entry = jarInput.getNextJarEntry()) != null; ) {
                String name = entry.getName();
                if (name.endsWith(CLASS_FILE_SUFFIX)) {
                  String className = name.substring(0, name.length() - CLASS_FILE_SUFFIX.length());
                  className = className.replace('/', '.');
                  classNames.add(className);
                }
              }
            }
          }

        } finally {
          urlInput.close();
        }

      } catch (IOException ex) {
      }

    } else {
      File file = IoUtils.toFile(url, StringUtils.UTF_8);
      if (file != null && file.isDirectory()) {
        processFile(classNames, file, "");
      }
    }
  }
Example #20
0
  /** Extract the MANIFEST from the give file. */
  private Manifest getManifest(File file) throws IOException {
    InputStream is = null;
    try {
      is = new BufferedInputStream(new FileInputStream(file));
    } catch (Exception e) {
      getLog().warn("Error while opening artifact", e);
      return null;
    }

    try {
      is.mark(256 * 1024);
      JarInputStream jar = new JarInputStream(is);
      Manifest m = jar.getManifest();
      if (m == null) {
        getLog().warn("Manifest not present in the first entry of the zip - " + file.getName());
      }
      jar.close();
      return m;
    } finally {
      if (is != null) { // just in case when we did not open bundle
        is.close();
      }
    }
  }
Example #21
0
  Map<String, Result> install(
      final Collection<Patch> patches, boolean simulate, boolean synchronous) {
    try {
      // Compute individual patch results
      final Map<String, Result> results = new LinkedHashMap<String, Result>();
      final Map<Bundle, String> toUpdate = new HashMap<Bundle, String>();
      Map<String, BundleUpdate> allUpdates = new HashMap<String, BundleUpdate>();
      for (Patch patch : patches) {
        String startup =
            readFully(new File(System.getProperty("karaf.base"), "etc/startup.properties"));
        String overrides =
            readFully(new File(System.getProperty("karaf.base"), "etc/overrides.properties"));
        List<BundleUpdate> updates = new ArrayList<BundleUpdate>();
        Bundle[] allBundles = bundleContext.getBundles();
        for (String url : patch.getBundles()) {
          JarInputStream jis = new JarInputStream(new URL(url).openStream());
          jis.close();
          Manifest manifest = jis.getManifest();
          Attributes att = manifest != null ? manifest.getMainAttributes() : null;
          String sn = att != null ? att.getValue(Constants.BUNDLE_SYMBOLICNAME) : null;
          String vr = att != null ? att.getValue(Constants.BUNDLE_VERSION) : null;
          if (sn == null || vr == null) {
            continue;
          }
          Version v = VersionTable.getVersion(vr);

          VersionRange range = null;

          if (patch.getVersionRange(url) == null) {
            // default version range starts with x.y.0 as the lower bound
            Version lower = new Version(v.getMajor(), v.getMinor(), 0);

            // We can't really upgrade with versions such as 2.1.0
            if (v.compareTo(lower) > 0) {
              range = new VersionRange(false, lower, v, true);
            }
          } else {
            range = new VersionRange(patch.getVersionRange(url));
          }

          if (range != null) {
            for (Bundle bundle : allBundles) {
              Version oldV = bundle.getVersion();
              if (bundle.getBundleId() != 0
                  && stripSymbolicName(sn).equals(stripSymbolicName(bundle.getSymbolicName()))
                  && range.contains(oldV)) {
                String location = bundle.getLocation();
                BundleUpdate update =
                    new BundleUpdateImpl(sn, v.toString(), url, oldV.toString(), location);
                updates.add(update);
                // Merge result
                BundleUpdate oldUpdate = allUpdates.get(sn);
                if (oldUpdate != null) {
                  Version upv = VersionTable.getVersion(oldUpdate.getNewVersion());
                  if (upv.compareTo(v) < 0) {
                    allUpdates.put(sn, update);
                    toUpdate.put(bundle, url);
                  }
                } else {
                  toUpdate.put(bundle, url);
                }
              }
            }
          } else {
            System.err.printf(
                "Skipping bundle %s - unable to process bundle without a version range configuration%n",
                url);
          }
        }
        if (!simulate) {
          new Offline(new File(System.getProperty("karaf.base")))
              .applyConfigChanges(((PatchImpl) patch).getPatch());
        }
        Result result =
            new ResultImpl(
                patch, simulate, System.currentTimeMillis(), updates, startup, overrides);
        results.put(patch.getId(), result);
      }
      // Apply results
      System.out.println("Bundles to update:");
      for (Map.Entry<Bundle, String> e : toUpdate.entrySet()) {
        System.out.println(
            "    "
                + e.getKey().getSymbolicName()
                + "/"
                + e.getKey().getVersion().toString()
                + " with "
                + e.getValue());
      }
      if (simulate) {
        System.out.println("Running simulation only - no bundles are being updated at this time");
      } else {
        System.out.println(
            "Installation will begin.  The connection may be lost or the console restarted.");
      }
      System.out.flush();
      if (!simulate) {
        Thread thread =
            new Thread() {
              public void run() {
                try {
                  applyChanges(toUpdate);
                  for (Patch patch : patches) {
                    Result result = results.get(patch.getId());
                    ((PatchImpl) patch).setResult(result);
                    saveResult(result);
                  }
                } catch (Exception e) {
                  e.printStackTrace(System.err);
                  System.err.flush();
                }
              }
            };
        if (synchronous) {
          thread.run();
        } else {
          thread.start();
        }
      }
      return results;
    } catch (Exception e) {
      throw new PatchException(e);
    }
  }
Example #22
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 #23
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) {
            }
        }
      }
Example #24
0
  public static void run(String args[]) throws Exception {

    args = processArgs(args);

    initializeLogging();

    // Is the main class specified on the command line?  If so, boot it.
    // Otherwise, read the main class out of the manifest.
    String mainClass = null;

    initializeProperties();
    // Reinitialze Logging (property file could have other loglevel set)
    initializeLogging();

    if (Boolean.valueOf(System.getProperty(P_SHOW_PROPERTIES, "false")).booleanValue()) {
      // What are the system properties.
      Properties props = System.getProperties();
      String keys[] = props.keySet().toArray(new String[0]);
      Arrays.sort(keys);

      for (int i = 0; i < keys.length; i++) {
        String key = keys[i];
        System.out.println(key + "=" + props.get(key));
      }
    }

    // Process developer properties:
    if (mainClass == null) {
      mainClass = System.getProperty(P_MAIN_CLASS);
    }

    if (mainJar == null) {
      String app = System.getProperty(P_MAIN_APP);
      if (app != null) {
        mainJar = "main/" + app + ".jar";
      } else {
        mainJar = System.getProperty(P_MAIN_JAR, MAIN_JAR);
      }
    }

    // Pick some things out of the top-level JAR file.
    String jar = getMyJarPath();
    JarFile jarFile = new JarFile(jar);
    Manifest manifest = jarFile.getManifest();
    Attributes attributes = manifest.getMainAttributes();
    String bootLoaderName = attributes.getValue(ONE_JAR_CLASSLOADER);

    if (mainJar == null) {
      mainJar = attributes.getValue(ONE_JAR_DEFAULT_MAIN_JAR);
    }

    String mainargs = attributes.getValue(ONE_JAR_MAIN_ARGS);
    if (mainargs != null && args.length == 0) {
      // Replace the args with built-in.  Support escaped whitespace.
      args = mainargs.split("[^\\\\]\\s");
      for (int i = 0; i < args.length; i++) {
        args[i] = args[i].replaceAll("\\\\(\\s)", "$1");
      }
    }

    // If no main-class specified, check the manifest of the main jar for
    // a Boot-Class attribute.
    if (mainClass == null) {
      mainClass = attributes.getValue(ONE_JAR_MAIN_CLASS);
      if (mainClass == null) {
        mainClass = attributes.getValue(BOOT_CLASS);
        if (mainClass != null) {
          LOGGER.warning(
              "The manifest attribute "
                  + BOOT_CLASS
                  + " is deprecated in favor of the attribute "
                  + ONE_JAR_MAIN_CLASS);
        }
      }
    }

    if (mainClass == null) {
      // Still don't have one (default).  One final try: look for a jar file in a
      // main directory.  There should be only one, and it's manifest
      // Main-Class attribute is the main class.  The JarClassLoader will take
      // care of finding it.
      InputStream is = Boot.class.getResourceAsStream("/" + mainJar);
      if (is != null) {
        JarInputStream jis = new JarInputStream(is);
        Manifest mainmanifest = jis.getManifest();
        jis.close();
        mainClass = mainmanifest.getMainAttributes().getValue(Attributes.Name.MAIN_CLASS);
      } else {
        // There is no main jar. Info unless mainJar is empty string.
        // The load(mainClass) will scan for main jars anyway.
        if (mainJar != null && !mainJar.isEmpty()) {
          LOGGER.info(
              "Unable to locate main jar '" + mainJar + "' in the JAR file " + getMyJarPath());
        }
      }
    }

    // Do we need to create a wrapping classloader?  Check for the
    // presence of a "wrap" directory at the top of the jar file.
    URL url = Boot.class.getResource(WRAP_JAR);

    if (url != null) {
      // Wrap class loaders.
      final JarClassLoader bootLoader = getBootLoader(bootLoaderName);
      bootLoader.load(null);

      // Read the "Wrap-Class-Loader" property from the wraploader jar file.
      // This is the class to use as a wrapping class-loader.
      InputStream is = Boot.class.getResourceAsStream(WRAP_JAR);
      if (is != null) {
        JarInputStream jis = new JarInputStream(is);
        final String wrapLoader = jis.getManifest().getMainAttributes().getValue(WRAP_CLASS_LOADER);
        jis.close();
        if (wrapLoader == null) {
          LOGGER.warning(
              url
                  + " did not contain a "
                  + WRAP_CLASS_LOADER
                  + " attribute, unable to load wrapping classloader");
        } else {
          LOGGER.info("using " + wrapLoader);
          JarClassLoader wrapped = getWrapLoader(bootLoader, wrapLoader);
          if (wrapped == null) {
            LOGGER.warning(
                "Unable to instantiate "
                    + wrapLoader
                    + " from "
                    + WRAP_DIR
                    + ": using default JarClassLoader");
            wrapped = getBootLoader(null);
          }
          setClassLoader(wrapped);
        }
      }
    } else {
      setClassLoader(getBootLoader(bootLoaderName, Boot.class.getClassLoader()));
      LOGGER.info("using JarClassLoader: " + getClassLoader().getClass().getName());
    }

    // Allow injection of the URL factory.
    String urlfactory = attributes.getValue(ONE_JAR_URL_FACTORY);
    if (urlfactory != null) {
      loader.setURLFactory(urlfactory);
    }

    mainClass = loader.load(mainClass);

    if (mainClass == null && !loader.isExpanded())
      throw new Exception(
          getMyJarName()
              + " main class was not found (fix: add main/main.jar with a Main-Class manifest attribute, or specify -D"
              + P_MAIN_CLASS
              + "=<your.class.name>), or use "
              + ONE_JAR_MAIN_CLASS
              + " in the manifest");

    if (mainClass != null) {
      // Guard against the main.jar pointing back to this
      // class, and causing an infinite recursion.
      String bootClass = Boot.class.getName();
      if (bootClass.equals(mainClass))
        throw new Exception(
            getMyJarName()
                + " main class ("
                + mainClass
                + ") would cause infinite recursion: check main.jar/META-INF/MANIFEST.MF/Main-Class attribute: "
                + mainClass);

      Class cls = loader.loadClass(mainClass);

      endTime = System.currentTimeMillis();
      showTime();

      Method main = cls.getMethod("main", new Class[] {String[].class});
      main.invoke(null, new Object[] {args});
    }
  }
  private File writeIndexes(
      File jar, String entryName, List<LameSubDeploymentIndex> subDeploymentIndices)
      throws IOException {
    int dotIndex = entryName.lastIndexOf('.');
    if (dotIndex == -1) {
      throw new AssertionError("missing extension from: " + entryName);
    }
    String suffix = entryName.substring(dotIndex);
    int slashIndex = entryName.lastIndexOf('/');
    String prefix;
    if (slashIndex == -1) {
      prefix = entryName.substring(0, dotIndex);
    } else {
      prefix = entryName.substring(slashIndex + 1, dotIndex);
    }
    File indexedJar = File.createTempFile(prefix, suffix);

    try (JarInputStream inputStream = new JarInputStream(new FileInputStream(jar))) {
      Manifest manifest = inputStream.getManifest();
      Map<String, File> replacementMap = this.buildReplacementMap(subDeploymentIndices);
      try (FileOutputStream fileOutputStream = new FileOutputStream(indexedJar);
          JarOutputStream outputStream =
              manifest != null
                  ? new JarOutputStream(fileOutputStream, manifest)
                  : new JarOutputStream(fileOutputStream)) {
        JarEntry entry = inputStream.getNextJarEntry();
        byte[] buffer = new byte[8192];
        ByteArrayOutputStream bos = null;
        while (entry != null) {
          // TODO should we keep META-INF/INDEX.LIST or drop it? should be first entry
          boolean isFuckedUpIbm = isFuckedUpIbmMqSeriesEntry(entryName, entry);
          if (!isFuckedUpIbm) {
            File replacement = replacementMap.get(entryName);
            if (replacement == null) {
              outputStream.putNextEntry(entry);
              if (entry.getSize() != 0L) {
                int read;
                while ((read = inputStream.read(buffer)) != -1) {
                  outputStream.write(buffer, 0, read);
                }
              }

            } else {
              // some subdeployments (eg WAR in EAR) have changed and we need to replace them
              JarEntry replaced = safeCopy(entry);
              replaced.setSize(replacement.length());
              outputStream.putNextEntry(replaced);
              try (InputStream input = new FileInputStream(replacement)) {
                int read;
                while ((read = inputStream.read(buffer)) != -1) {
                  outputStream.write(buffer, 0, read);
                }
              }
            }

          } else {
            // some JARs in the IBM RAR are f****d up
            // the size of certain file in the central directory index is wrong
            if (bos == null) {
              bos = new ByteArrayOutputStream(1024);
            } else {
              bos.reset();
            }

            long actualSize = 0L;
            int read;
            while ((read = inputStream.read(buffer)) != -1) {
              bos.write(buffer, 0, read);
              actualSize += read;
            }

            System.out.println(
                "encountered f****d up entry: "
                    + entry.getName()
                    + " in: "
                    + entryName
                    + " reported size: "
                    + entry.getSize()
                    + " actual size: "
                    + actualSize);

            JarEntry unfucked = safeCopy(entry);
            unfucked.setSize(actualSize);
            outputStream.putNextEntry(unfucked);
            bos.writeTo(outputStream);
          }
          entry = inputStream.getNextJarEntry();
        }

        // REVIEW: more or less reuse?
        IndexWriter indexWriter = new IndexWriter(outputStream);
        for (LameSubDeploymentIndex subDeploymentIndex : subDeploymentIndices) {
          String indexFile = subDeploymentIndex.name + ".index";
          JarEntry indexEntry = new JarEntry(indexFile);
          indexEntry.setMethod(ZipEntry.DEFLATED);
          outputStream.putNextEntry(indexEntry);
          // IndexWriter does buffering
          indexWriter.write(subDeploymentIndex.index);
        }
      }
    }
    return indexedJar;
  }