Create JAR from given entries.
    :param jar_file: filename of the created JAR
    :type jar_file: str
    :param entries: files to put into the JAR
    :type entries: list[str]
    :return: None
961487
def create_jar(jar_file, entries):
    

    # 'jar' adds separate entries for directories, also for empty ones.
    with ZipFile(jar_file, "w") as jar:
        jar.writestr("META-INF/", "")
        jar.writestr("META-INF/MANIFEST.MF", Manifest().get_data())
        for entry in entries:
            jar.write(entry)
            if os.path.isdir(entry):
                for root, dirs, files in os.walk(entry):
                    for filename in dirs + files:
                        jar.write(os.path.join(root, filename))
99973
public Enumeration<JarEntry> entries() {
        final Enumeration enum_ = super.entries();
        return new Enumeration<JarEntry>() {
            public boolean hasMoreElements() {
                return enum_.hasMoreElements();
            }
            public JarFileEntry nextElement() {
                ZipEntry ze = (ZipEntry)enum_.nextElement();
                return new JarFileEntry(ze);
            }
        };
    }
189132
@SuppressWarnings("deprecation")
  private void addJars(Path jarFileDir, String jarFileList, Configuration conf) throws IOException {
    LocalFileSystem lfs = FileSystem.getLocal(conf);
    for (String jarFile : SPLITTER.split(jarFileList)) {
      Path srcJarFile = new Path(jarFile);
      FileStatus[] fileStatusList = lfs.globStatus(srcJarFile);

      for (FileStatus status : fileStatusList) {
        // For each FileStatus there are chances it could fail in copying at the first attempt, due to file-existence
        // or file-copy is ongoing by other job instance since all Gobblin jobs share the same jar file directory.
        // the retryCount is to avoid cases (if any) where retry is going too far and causes job hanging.
        int retryCount = 0;
        boolean shouldFileBeAddedIntoDC = true;
        Path destJarFile = calculateDestJarFile(status, jarFileDir);
        // Adding destJarFile into HDFS until it exists and the size of file on targetPath matches the one on local path.
        while (!this.fs.exists(destJarFile) || fs.getFileStatus(destJarFile).getLen() != status.getLen()) {
          try {
            if (this.fs.exists(destJarFile) && fs.getFileStatus(destJarFile).getLen() != status.getLen()) {
              Thread.sleep(WAITING_TIME_ON_IMCOMPLETE_UPLOAD);
              throw new IOException("Waiting for file to complete on uploading ... ");
            }
            // Set the first parameter as false for not deleting sourceFile
            // Set the second parameter as false for not overwriting existing file on the target, by default it is true.
            // If the file is preExisted but overwrite flag set to false, then an IOException if thrown.
            this.fs.copyFromLocalFile(false, false, status.getPath(), destJarFile);
          } catch (IOException | InterruptedException e) {
            LOG.warn("Path:" + destJarFile + " is not copied successfully. Will require retry.");
            retryCount += 1;
            if (retryCount >= this.jarFileMaximumRetry) {
              LOG.error("The jar file:" + destJarFile + "failed in being copied into hdfs", e);
              // If retry reaches upper limit, skip copying this file.
              shouldFileBeAddedIntoDC = false;
              break;
            }
          }
        }
        if (shouldFileBeAddedIntoDC) {
          // Then add the jar file on HDFS to the classpath
          LOG.info(String.format("Adding %s to classpath", destJarFile));
          DistributedCache.addFileToClassPath(destJarFile, conf, this.fs);
        }
      }
    }
  }
763248
public void writeEntries(JarFile jarFile) throws IOException {
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            ZipHeaderPeekInputStream inputStream = new ZipHeaderPeekInputStream(
                    jarFile.getInputStream(entry));
            try {
                if (inputStream.hasZipHeader() && entry.getMethod() != ZipEntry.STORED) {
                    new CrcAndSize(inputStream).setupStoredEntry(entry);
                    inputStream.close();
                    inputStream = new ZipHeaderPeekInputStream(
                            jarFile.getInputStream(entry));
                }
                EntryWriter entryWriter = new InputStreamEntryWriter(inputStream, true);
                writeEntry(entry, entryWriter);
            } finally {
                inputStream.close();
            }
        }
    }
427218
def install_jarfile(*args)
      root_path ||= Pathname.new(File.expand_path('../../..', __FILE__))
      jarfile_path = root_path.join('Jarfile')
      File.open(jarfile_path.to_s, 'w') do |f|
        f.puts args.last
      end
    end
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) {}
			}
		}
	}
156367
@Override
    public synchronized void onFileCreate(File file) {
        final Set<DetectedWebJar> listOfDetectedWebJarLib = isWebJar(file);
        if (listOfDetectedWebJarLib != null) {
            JarFile jar = null;
            try {
                jar = new JarFile(file);
                List<FileWebJarLib> installed = new ArrayList<>();
                for (DetectedWebJar detected : listOfDetectedWebJarLib) {
                    FileWebJarLib lib = expand(detected, jar);
                    if (lib != null) {
                        libs.add(lib);
                        installed.add(lib);
                        LOGGER.info("{} unpacked to {}", lib.name, lib.root.getAbsolutePath());
                    }
                }
                controller.addWebJarLibs(installed);
            } catch (IOException e) {
                LOGGER.error("Cannot open the jar file {}", file.getAbsolutePath(), e);
            } finally {
                IOUtils.closeQuietly(jar);
            }

        }
    }
670204
private String parseManifestForAppliesTo(File file) throws RepositoryArchiveIOException {

        Manifest mf = null;
        try (JarFile jar = new JarFile(file)) {
            try {
                mf = jar.getManifest();
            } catch (IOException ioe) {
                throw new RepositoryArchiveIOException("Error getting manifest from jar " + jar.getName(), new File(jar.getName()), ioe);
            }
        } catch (IOException ioe) {
            throw new RepositoryArchiveIOException("Unable to create JarFile from path " +
                                                   file, new File(file.getName()), ioe);
        }

        String appliesTo = null;

        Attributes mainattrs = mf.getMainAttributes();
        // Iterate over the main attributes in the manifest and look for the ones we
        // are interested in.
        for (Object at : mainattrs.keySet()) {
            String attribName = ((Attributes.Name) at).toString();
            String attribValue = (String) mainattrs.get(at);

            if (APPLIES_TO.equals(attribName)) {
                appliesTo = attribValue;
            }
        }

        return appliesTo;
    }
682339
public Enumeration<JarEntry> entries2(final JarFile jar, Enumeration e) {
        final Map map = new HashMap();
        map.putAll(signerMap());
        final Enumeration enum_ = e;
        return new Enumeration<JarEntry>() {

            Enumeration signers = null;
            JarEntry entry;

            public boolean hasMoreElements() {
                if (entry != null) {
                    return true;
                }
                while (enum_.hasMoreElements()) {
                    ZipEntry ze = (ZipEntry) enum_.nextElement();
                    if (JarVerifier.isSigningRelated(ze.getName())) {
                        continue;
                    }
                    entry = jar.newEntry(ze);
                    return true;
                }
                if (signers == null) {
                    signers = Collections.enumeration(map.keySet());
                }
                while (signers.hasMoreElements()) {
                    String name = (String) signers.nextElement();
                    entry = jar.newEntry(new ZipEntry(name));
                    return true;
                }

                // Any map entries left?
                return false;
            }

            public JarEntry nextElement() {
                if (hasMoreElements()) {
                    JarEntry je = entry;
                    map.remove(je.getName());
                    entry = null;
                    return je;
                }
                throw new NoSuchElementException();
            }
        };
    }
482662
private void readRequiredJarFiles(final DataInput in) throws IOException {

		// Do jar files follow;
		final int numJars = in.readInt();

		if (numJars > 0) {

			for (int i = 0; i < numJars; i++) {

				final Path p = new Path();
				p.read(in);
				this.userJars.add(p);

				// Read the size of the jar file
				final long sizeOfJar = in.readLong();

				// Add the jar to the library manager
				LibraryCacheManager.addLibrary(this.jobID, p, sizeOfJar, in);
			}

		}

		// Register this job with the library cache manager
		LibraryCacheManager.register(this.jobID, this.userJars.toArray(new Path[0]));
	}
186243
public static void addEntries(File zip, ZipEntrySource[] entries, File destZip) {
    if (log.isDebugEnabled()) {
      log.debug("Copying '" + zip + "' to '" + destZip + "' and adding " + Arrays.asList(entries) + ".");
    }

    OutputStream destOut = null;
    try {
      destOut = new BufferedOutputStream(new FileOutputStream(destZip));
      addEntries(zip, entries, destOut);
    }
    catch (IOException e) {
      ZipExceptionUtil.rethrow(e);
    }
    finally {
      IOUtils.closeQuietly(destOut);
    }
  }
507243
def write(write_entry: FILE_WRITE_ENTRY):
    
    output_path = environ.paths.clean(write_entry.path)
    make_output_directory(output_path)
    writer.write_file(output_path, write_entry.contents)
95294
public static void pack(ZipEntrySource[] entries, File zip) {
    if (log.isDebugEnabled()) {
      log.debug("Creating '{}' from {}.", zip, Arrays.asList(entries));
    }

    OutputStream out = null;
    try {
      out = new BufferedOutputStream(new FileOutputStream(zip));
      pack(entries, out, true);
    }
    catch (IOException e) {
      throw ZipExceptionUtil.rethrow(e);
    }
    finally {
      IOUtils.closeQuietly(out);
    }
  }
1010374
public static final List<JarEntry> findJarEntrysByJar(JarFile jarFile)
	{
		List<JarEntry> list=new ArrayList<JarEntry>();
		if(jarFile==null)
		{
			throw new RuntimeException("jarFile is Null");
		}
		Enumeration<JarEntry> jarEntries = jarFile.entries();
		while (jarEntries.hasMoreElements()) 
		{//遍历jar的实体对象
			JarEntry jarEntry = jarEntries.nextElement();
			list.add(jarEntry);
		}
		return list;
	}
1161975
def writejar(self, jar):
    
    if not jar or not isinstance(jar, string_types):
      raise ValueError('The jar path must be a non-empty string')

    self._jars.append(jar)
714118
private void jarDir(File dirOrFile2jar, JarOutputStream jos, String path)
		throws IOException {
		if (mVerbose) {
			System.out.println("checking " + dirOrFile2jar);
		}
		if (dirOrFile2jar.isDirectory()) {
			String[] dirList = dirOrFile2jar.list();
			String subPath = (path == null) ? "" : (path + dirOrFile2jar.getName() + SEP);
			if (path != null) {
				JarEntry je = new JarEntry(subPath);
				je.setTime(dirOrFile2jar.lastModified());
				jos.putNextEntry(je);
				jos.flush();
				jos.closeEntry();
			}
			for (int i = 0; i < dirList.length; i++) {
				File f = new File(dirOrFile2jar, dirList[i]);
				jarDir(f, jos, subPath);
			}
		} else if (dirOrFile2jar.exists()) {
			if (dirOrFile2jar.getCanonicalPath().equals(mDestJarName)) {
				if (mVerbose) {
					System.out.println("skipping " + dirOrFile2jar.getPath());
				}
				return;
			}

			if (mVerbose) {
				System.out.println("adding " + dirOrFile2jar.getPath());
			}
			FileInputStream fis = new FileInputStream(dirOrFile2jar);
			try {
				JarEntry entry = new JarEntry(path + dirOrFile2jar.getName());
				entry.setTime(dirOrFile2jar.lastModified());
				jos.putNextEntry(entry);
				while ((mByteCount = fis.read(mBuffer)) != -1) {
					jos.write(mBuffer, 0, mByteCount);
					if (mVerbose) {
						System.out.println("wrote " + mByteCount + " bytes");
					}
				}
				jos.flush();
				jos.closeEntry();
			} catch (IOException ioe) {
				throw ioe;
			} finally {
				fis.close();
			}
		}
	}
1180388
def add(self, entry, local_file):
        """"""
        row = self.rowClass()

        for key, val in entry.items():
            if key in self.columns:
                setattr(row, key, val)

        row.local_filename = os.path.join('.', os.path.relpath(local_file))

        self.rows.append(row)