Takes all JAR files that are contained in this program's JAR file and extracts them
to the system's temp directory.

@return The file names of the extracted temporary files.
@throws ProgramInvocationException Thrown, if the extraction process failed.
979536
public static List<File> extractContainedLibraries(URL jarFile) throws ProgramInvocationException {

		Random rnd = new Random();

		JarFile jar = null;
		try {
			jar = new JarFile(new File(jarFile.toURI()));
			final List<JarEntry> containedJarFileEntries = new ArrayList<JarEntry>();

			Enumeration<JarEntry> entries = jar.entries();
			while (entries.hasMoreElements()) {
				JarEntry entry = entries.nextElement();
				String name = entry.getName();

				if (name.length() > 8 && name.startsWith("lib/") && name.endsWith(".jar")) {
					containedJarFileEntries.add(entry);
				}
			}

			if (containedJarFileEntries.isEmpty()) {
				return Collections.emptyList();
			}
			else {
				// go over all contained jar files
				final List<File> extractedTempLibraries = new ArrayList<File>(containedJarFileEntries.size());
				final byte[] buffer = new byte[4096];

				boolean incomplete = true;

				try {
					for (int i = 0; i < containedJarFileEntries.size(); i++) {
						final JarEntry entry = containedJarFileEntries.get(i);
						String name = entry.getName();
						// '/' as in case of zip, jar
						// java.util.zip.ZipEntry#isDirectory always looks only for '/' not for File.separator
						name = name.replace('/', '_');

						File tempFile;
						try {
							tempFile = File.createTempFile(rnd.nextInt(Integer.MAX_VALUE) + "_", name);
							tempFile.deleteOnExit();
						}
						catch (IOException e) {
							throw new ProgramInvocationException(
								"An I/O error occurred while creating temporary file to extract nested library '" +
										entry.getName() + "'.", e);
						}

						extractedTempLibraries.add(tempFile);

						// copy the temp file contents to a temporary File
						OutputStream out = null;
						InputStream in = null;
						try {

							out = new FileOutputStream(tempFile);
							in = new BufferedInputStream(jar.getInputStream(entry));

							int numRead = 0;
							while ((numRead = in.read(buffer)) != -1) {
								out.write(buffer, 0, numRead);
							}
						}
						catch (IOException e) {
							throw new ProgramInvocationException("An I/O error occurred while extracting nested library '"
									+ entry.getName() + "' to temporary file '" + tempFile.getAbsolutePath() + "'.");
						}
						finally {
							if (out != null) {
								out.close();
							}
							if (in != null) {
								in.close();
							}
						}
					}

					incomplete = false;
				}
				finally {
					if (incomplete) {
						deleteExtractedLibraries(extractedTempLibraries);
					}
				}

				return extractedTempLibraries;
			}
		}
		catch (Throwable t) {
			throw new ProgramInvocationException("Unknown I/O error while extracting contained jar files.", t);
		}
		finally {
			if (jar != null) {
				try {
					jar.close();
				} catch (Throwable t) {}
			}
		}
	}
834150
public static URL[] findClassPaths()
   {
      List<URL> list = new ArrayList<URL>();
      String classpath = System.getProperty("java.class.path");
      StringTokenizer tokenizer = new StringTokenizer(classpath, File.pathSeparator);

      while (tokenizer.hasMoreTokens())
      {
         String path = tokenizer.nextToken();
         File fp = new File(path);
         if (!fp.exists()) {
        	 throw new RuntimeException("File in java.class.path does not exist: " + fp);
         }
         try
         {
            list.add(fp.toURL());
         }
         catch (MalformedURLException e)
         {
            throw new RuntimeException(e);
         }
      }
      return list.toArray(new URL[list.size()]);
   }
1057657
public void importArtifacts(SessionProvider sp, InputStream in) throws RepositoryException, FileNotFoundException
   {
      LOG.info("Extract repository to temporary folder");
      String path = System.getProperty("java.io.tmpdir") + File.separator + "maven2";
      File temporaryFolder = new File(getUniqueFilename(path));
      if (!temporaryFolder.mkdir())
      {
         throw new FileNotFoundException("Cannot create temporary folder");
      }
      ZipEntry entry;
      ZipInputStream zipIn = new ZipInputStream(new BufferedInputStream(in));
      try
      {
         while ((entry = zipIn.getNextEntry()) != null)
         {

            if (!(entry.isDirectory() && new File(temporaryFolder + File.separator + entry.getName()).mkdir()))
            {
               int count;
               byte data[] = new byte[BUFFER];
               File file = new File(temporaryFolder + File.separator + entry.getName());

               FileUtils.touch(file);

               FileOutputStream fos = new FileOutputStream(file);
               BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
               while ((count = zipIn.read(data, 0, BUFFER)) != -1)
               {
                  dest.write(data, 0, count);
               }
               dest.flush();
               dest.close();
            }

         }
      }
      catch (IOException e)
      {
         LOG.error("Cannot get zip entry from stream", e);
      }
      finally
      {
         IOUtils.closeQuietly(zipIn);
         IOUtils.closeQuietly(in);
      }

      // main part - copy to JCR from temp folder
      // use uploading artifacts from local folder.

      importArtifacts(sp, temporaryFolder);
      try
      {
         FileUtils.deleteDirectory(temporaryFolder);
      }
      catch (IOException e)
      {
         LOG.error("Cannot remove temporary folder", e);
      }

   }
1170844
private static File[] classPath() {
        final String[] fileNames =
                System.getProperty("java.class.path").split(File.pathSeparator);
        final File[] files = new File[fileNames.length];
        for (int i = 0; i < files.length; ++i) {
            files[i] = new File(fileNames[i]);
        }
        return files;
    }
43745
@NonNull
    private File[] getCrashReportFiles() {
        final File dir = context.getFilesDir();
        if (dir == null) {
            ACRA.log.w(LOG_TAG, "Application files directory does not exist! The application may not be installed correctly. Please try reinstalling.");
            return new File[0];
        }

        if (ACRA.DEV_LOGGING) ACRA.log.d(LOG_TAG, "Looking for error files in " + dir.getAbsolutePath());

        // Filter for ".stacktrace" files
        final FilenameFilter filter = (dir1, name) -> name.endsWith(ACRAConstants.REPORTFILE_EXTENSION);
        final File[] result = dir.listFiles(filter);
        return (result == null) ? new File[0] : result;
    }
1173603
private static File extract(File file, File directory) throws IOException
   {
      if (file == null)
         throw new IllegalArgumentException("File is null");

      if (directory == null)
         throw new IllegalArgumentException("Directory is null");

      File target = new File(directory, file.getName());

      if (target.exists())
         recursiveDelete(target);

      if (!target.mkdirs())
         throw new IOException("Could not create " + target);

      JarFile jar = null;
      try
      {
         jar = new JarFile(file);
         Enumeration<JarEntry> entries = jar.entries();

         while (entries.hasMoreElements())
         {
            JarEntry je = entries.nextElement();
            File copy = new File(target, je.getName());

            if (!je.isDirectory())
            {
               InputStream in = null;
               OutputStream out = null;

               // Make sure that the directory is _really_ there
               if (copy.getParentFile() != null && !copy.getParentFile().exists())
               {
                  if (!copy.getParentFile().mkdirs())
                     throw new IOException("Could not create " + copy.getParentFile());
               }

               try
               {
                  in = new BufferedInputStream(jar.getInputStream(je));
                  out = new BufferedOutputStream(new FileOutputStream(copy));

                  byte[] buffer = new byte[4096];
                  for (;;)
                  {
                     int nBytes = in.read(buffer);
                     if (nBytes <= 0)
                        break;

                     out.write(buffer, 0, nBytes);
                  }
                  out.flush();
               }
               finally
               {
                  try
                  {
                     if (out != null)
                        out.close();
                  }
                  catch (IOException ignore)
                  {
                     // Ignore
                  }

                  try
                  {
                     if (in != null)
                        in.close();
                  }
                  catch (IOException ignore)
                  {
                     // Ignore
                  }
               }
            }
            else
            {
               if (!copy.exists())
               {
                  if (!copy.mkdirs())
                     throw new IOException("Could not create " + copy);
               }
               else
               {
                  if (!copy.isDirectory())
                     throw new IOException(copy + " isn't a directory");
               }
            }
         }
      }
      finally
      {
         try
         {
            if (jar != null)
               jar.close();
         }
         catch (IOException ignore)
         {
            // Ignore
         }
      }

      return target;
   }
1183768
public static List<String> getAllClasses() throws PackageManager.NameNotFoundException, IOException {
        List<String> classNames = new ArrayList<>();
        for (String path : getSourcePaths()) {
            try {
                DexFile dexfile;
                if (path.endsWith(EXTRACTED_SUFFIX)) {
                    //NOT use new DexFile(path), because it will throw "permission error in /data/dalvik-cache"
                    dexfile = DexFile.loadDex(path, path + ".tmp", 0);
                } else {
                    dexfile = new DexFile(path);
                }
                Enumeration<String> dexEntries = dexfile.entries();
                while (dexEntries.hasMoreElements()) {
                    classNames.add(dexEntries.nextElement());
                }
            } catch (IOException e) {
                throw new IOException("Error at loading dex file '" + path + "'");
            }
        }
        return classNames;
    }
223761
private static String getExtractDirectory() {
        createExtractor();
        String containerPath = extractor.container.getName();
        File containerFile = new File(containerPath);
        if (containerFile.isDirectory()) {
            extractor.allowNonEmptyInstallDirectory(true);
            return containerFile.getAbsolutePath();
        }
        // check if user specified explicit directory
        String extractDirVar = System.getenv("WLP_JAR_EXTRACT_DIR");

        // if so, return it and done
        if (extractDirVar != null && extractDirVar.length() > 0) {
            String retVal = createIfNeeded(extractDirVar.trim());
            return retVal;
        } else {

            String extractDirVarRoot = System.getenv("WLP_JAR_EXTRACT_ROOT");
            if (extractDirVarRoot == null || extractDirVarRoot.length() == 0) {
                extractDirVarRoot = getUserHome() + File.separator + "wlpExtract";
            }
            createIfNeeded(extractDirVarRoot);

            try {
                String basedir = (new File(extractDirVarRoot)).getAbsolutePath();
                return createTempDirectory(basedir, jarFileName() + "_");
            } catch (Exception e) {
                throw new RuntimeException("Could not create temp directory under: " + extractDirVarRoot);
            }
        }
    }
1308601
protected List<File> findJarFile(String scriptLibDir) {
		List<File> files = new ArrayList<File>();
		try {
			File file = new File(scriptLibDir);
			if (file.isDirectory()) {
				for (File f : file.listFiles()) {
					if (f.isFile() && f.getName().endsWith(".jar")) {
						files.add(f);
					}
				}
			}
		} catch (Exception e) {
			_log.error(e.getMessage(), e);
		}
		return files;
	}
391278
protected List<Entry<V>> loadEntryFiles() {
    File[] files = getDirectory().listFiles();
    String prefix = getEntryLogPrefix();
    String suffix = getEntryLogSuffix();
    
    List<Entry<V>> entryList = new ArrayList<Entry<V>>();
    if(files == null) return entryList;
    
    for (File file : files) {
      String fileName = file.getName();
      if (fileName.startsWith(prefix) && fileName.endsWith(suffix)) {
        try {
          Entry<V> entry = _entryPool.next();
          entry.load(file);
          entryList.add(entry);
        } catch(Exception e) {
          String filePath = file.getAbsolutePath();
          _log.warn(filePath + " corrupted: length=" + file.length(), e);
          if(file.delete()) {
            _log.warn(filePath + " deleted");
          }
        }
      }
    }
    
    return entryList;
  }
773530
protected String getExecutableJar() throws IOException {
        Manifest manifest = new Manifest();
        manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
        manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, MAIN);
        manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, getClasspath());

        Path jar = createTempDirectory("exec").resolve("generate.jar");
        try (JarOutputStream output = new JarOutputStream(Files.newOutputStream(jar), manifest)) {
            output.putNextEntry(new JarEntry("allure.properties"));
            Path allureConfig = PROPERTIES.getAllureConfig();
            if (Files.exists(allureConfig)) {
                byte[] bytes = Files.readAllBytes(allureConfig);
                output.write(bytes);
            }
            output.closeEntry();
        }

        return jar.toAbsolutePath().toString();
    }
173437
private Set<String> getResourcesToScan() {

		final String classPath    = System.getProperty("java.class.path");
		final Set<String> modules = new TreeSet<>();
		final Pattern pattern     = Pattern.compile(".*(structr).*(war|jar)");
		final Matcher matcher     = pattern.matcher("");

		for (final String jarPath : classPath.split("[".concat(pathSep).concat("]+"))) {

			final String lowerPath = jarPath.toLowerCase();

			if (lowerPath.endsWith(classesDir) || lowerPath.endsWith(testClassesDir)) {

				modules.add(jarPath);

			} else {

				final String moduleName = lowerPath.substring(lowerPath.lastIndexOf(pathSep) + 1);

				matcher.reset(moduleName);

				if (matcher.matches()) {

					modules.add(jarPath);
				}

			}

		}

		for (final String resource : Services.getInstance().getResources()) {

			final String lowerResource = resource.toLowerCase();

			if (lowerResource.endsWith(".jar") || lowerResource.endsWith(".war")) {

				modules.add(resource);
			}

		}

		return modules;
	}
123204
@Override
    public List<URL> getJarFileUrls()
    {
        return jarUrls != null ? new ArrayList<URL>(jarUrls) : null;
    }
931153
private List<Archive> getClassPathArchives(String cpaths, List<Path> initialArchives)
            throws IOException
    {
        List<Archive> result = new ArrayList<>();
        if (cpaths.isEmpty()) {
            return result;
        }

        List<Path> paths = new ArrayList<>();
        for (String p : cpaths.split(File.pathSeparator)) {
            if (p.length() > 0) {
                // wildcard to parse all JAR files e.g. -classpath dir/*
                int i = p.lastIndexOf(".*");
                if (i > 0) {
                    Path dir = Paths.get(p.substring(0, i));
                    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.jar")) {
                        for (Path entry : stream) {
                            paths.add(entry);
                        }
                    }
                } else {
                    paths.add(Paths.get(p));
                }
            }
        }
        for (Path p : paths) {
            if (Files.exists(p) && !hasSameFile(initialArchives, p)) {
                result.add(Archive.getInstance(p));
            }
        }
        return result;
    }
1086356
private void extractInternalFiles() throws IOException {
    Enumeration entries = _h2oJar.entries();
    while( entries.hasMoreElements() ) {
      ZipEntry e = (ZipEntry) entries.nextElement();
      String name = e.getName();
      if( e.isDirectory() ) continue; // mkdirs() will handle these
      if(! name.endsWith(".jar") ) continue;

      // extract the entry
      File out = internalFile(name);
      out.getParentFile().mkdirs();
      try {
        FileOutputStream fos = new FileOutputStream(out);
        BufferedInputStream  is = new BufferedInputStream (_h2oJar.getInputStream(e));
        BufferedOutputStream os = new BufferedOutputStream(fos);
        int read;
        byte[] buffer = new byte[4096];
        while( (read = is.read(buffer)) != -1 ) os.write(buffer,0,read);
        os.flush();
        fos.getFD().sync();     // Force the output; throws SyncFailedException if full
        os.close();
        is.close();
      } catch( FileNotFoundException ex ) {
        // Expected FNF if 2 H2O instances are attempting to unpack in the same directory
      } catch( IOException ex ) {
        Log.die("Unable to extract file "+name+" because of "+ex+". Make sure that directory " + _parentDir + " contains at least 50MB of free space to unpack H2O libraries.");
        throw ex; // dead code
      }
    }
  }
787351
static String[] getClasspathClassNames() throws ZipException, IOException {
        final String[] classes = getClasspathFileNamesWithExtension(".class");
        for (int i = 0; i < classes.length; i++) {
            classes[i] = classes[i].substring(0, classes[i].length() - 6).replace("/", ".");
        }
        return classes;
    }
335494
public static File getTempDirectory() {
	if (tempFile != null) return tempFile;

	final String tmpStr = System.getProperty("java.io.tmpdir");
	if (tmpStr != null) {
	    tempFile = new File(tmpStr);
	    if (tempFile.exists()) {
		tempFile = getCanonicalFileEL(tempFile);
		return tempFile;
	    }
	}
	try {
	    final File tmp = File.createTempFile("a", "a");
	    tempFile = tmp.getParentFile();
	    tempFile = getCanonicalFileEL(tempFile);
	    tmp.delete();
	}
	catch (final IOException ioe) {}

	return tempFile;
    }