Extract a jar entry to a temp file.

@param name  Name prefix for temp file.
@param is    Jar entry input stream.

@return A temporary file.

@throws IOException when an IO error occurs.
18854
private static File extract(String name, InputStream is) throws IOException {
        byte[] buf = new byte[4096];
        int len;

        File lib = File.createTempFile(name, "lib");
        FileOutputStream os = new FileOutputStream(lib);

        try {
            while ((len = is.read(buf)) > 0) {
                os.write(buf, 0, len);
            }
        } catch (IOException e) {
            lib.delete();
            throw e;
        } finally {
            os.close();
            is.close();
        }

        return lib;
    }
1044454
public void writeEntry(String entryName, InputStream inputStream) throws IOException {
        JarEntry entry = new JarEntry(entryName);
        writeEntry(entry, new InputStreamEntryWriter(inputStream, true));
    }
607964
private File downloadTempFile(final String jarURL, final LogNode log) {
        final LogNode subLog = log == null ? null : log.log(jarURL, "Downloading URL " + jarURL);
        File tempFile;
        try {
            tempFile = makeTempFile(jarURL, /* onlyUseLeafname = */ true);
            final URL url = new URL(jarURL);
            try (InputStream inputStream = url.openStream()) {
                Files.copy(inputStream, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            }
            if (subLog != null) {
                subLog.addElapsedTime();
            }
        } catch (final IOException | SecurityException e) {
            if (subLog != null) {
                subLog.log("Could not download " + jarURL, e);
            }
            return null;
        }
        if (subLog != null) {
            subLog.log("Downloaded to temporary file " + tempFile);
            subLog.log("***** Note that it is time-consuming to scan jars at http(s) addresses, "
                    + "they must be downloaded for every scan, and the same jars must also be "
                    + "separately downloaded by the ClassLoader *****");
        }
        return tempFile;
    }
43007
public static final void fileHexDump(String fileName, InputStream is)
   {
      try
      {
         byte[] data = new byte[is.available()];
         is.read(data);
         fileHexDump(fileName, data);
      }

      catch (IOException ex)
      {
         ex.printStackTrace();
      }
   }
343878
private Program copyProgramJar(final Program program, File programDir) throws IOException {
    File tempJar = File.createTempFile(program.getName(), ".jar");
    Files.copy(new InputSupplier<InputStream>() {
      @Override
      public InputStream getInput() throws IOException {
        return program.getJarLocation().getInputStream();
      }
    }, tempJar);

    final Location jarLocation = new LocalLocationFactory().create(tempJar.toURI());
    return Programs.createWithUnpack(jarLocation, programDir);
  }
463564
public static boolean transformEntry(InputStream is, ZipEntryTransformerEntry entry, OutputStream os) {
    return transformEntries(is, new ZipEntryTransformerEntry[] { entry }, os);
  }
649647
public synchronized File getTempDirectory() throws IOException {
        if (tempDirectory == null) {
            final File baseTemp = new File(getString(Settings.KEYS.TEMP_DIRECTORY, System.getProperty("java.io.tmpdir")));
            tempDirectory = FileUtils.createTempDirectory(baseTemp);
        }
        return tempDirectory;
    }
944322
private void extractEntry(File destDir, TarEntry entry) throws IOException {
        if (this.verbose) {
            if (this.progressDisplay != null) {
                this.progressDisplay.showTarProgressMessage(entry.getName());
            }
        }

        String name = entry.getName();
        name = name.replace('/', File.separatorChar);

        File destFile = new File(destDir, name);

        if (entry.isDirectory()) {
            if (!destFile.exists()) {
                if (!destFile.mkdirs()) {
                    throw new IOException("error making directory path '" + destFile.getPath() + "'");
                }
            }
        } else {
            File subDir = new File(destFile.getParent());

            if (!subDir.exists()) {
                if (!subDir.mkdirs()) {
                    throw new IOException("error making directory path '" + subDir.getPath() + "'");
                }
            }

            if (this.keepOldFiles && destFile.exists()) {
                if (this.verbose) {
                    if (this.progressDisplay != null) {
                        this.progressDisplay.showTarProgressMessage("not overwriting " + entry.getName());
                    }
                }
            } else {
                boolean asciiTrans = false;

                FileOutputStream out = new FileOutputStream(destFile);

                if (this.asciiTranslate) {
                    MimeType mime = null;
                    String contentType = null;

                    try {
                        contentType = FileTypeMap.getDefaultFileTypeMap().getContentType(destFile);

                        mime = new MimeType(contentType);

                        if (mime.getPrimaryType().equalsIgnoreCase("text")) {
                            asciiTrans = true;
                        } else if (this.transTyper != null) {
                            if (this.transTyper.isAsciiFile(entry.getName())) {
                                asciiTrans = true;
                            }
                        }
                    } catch (MimeTypeParseException ex) {
                    }

                    if (this.debug) {
                        System.err.println("EXTRACT TRANS? '" + asciiTrans + "'  ContentType='" + contentType
                            + "'  PrimaryType='" + mime.getPrimaryType() + "'");
                    }
                }

                PrintWriter outw = null;
                if (asciiTrans) {
                    outw = new PrintWriter(out);
                }

                byte[] rdbuf = new byte[32 * 1024];

                for (;;) {
                    int numRead = this.tarIn.read(rdbuf);

                    if (numRead == -1) {
                        break;
                    }

                    if (asciiTrans) {
                        for (int off = 0, b = 0; b < numRead; ++b) {
                            if (rdbuf[b] == 10) {
                                String s = new String(rdbuf, off, (b - off));

                                outw.println(s);

                                off = b + 1;
                            }
                        }
                    } else {
                        out.write(rdbuf, 0, numRead);
                    }
                }

                if (asciiTrans) {
                    outw.close();
                } else {
                    out.close();
                }
            }
        }
    }
958301
static String getFile( String name )
        throws FileNotFoundException, IOException
    {
        StringBuilder sb = new StringBuilder();
        try ( BufferedReader bin = new BufferedReader( new FileReader( name ) ) ) {
            String line;
            while ( (line=bin.readLine()) != null )
                sb.append( line ).append( "\n" );
        }
        return sb.toString();
    }
1134475
public void setEntry(String name, JarEntry entry)
        throws IOException
    {
        digests.clear();
        manifestHashes.clear();
        this.name = name;
        this.entry = entry;

        skip = true;
        signers = null;

        if (man == null || name == null) {
            return;
        }

        /* get the headers from the manifest for this entry */
        /* if there aren't any, we can't verify any digests for this entry */

        Attributes attr = man.getAttributes(name);
        if (attr == null) {
            // ugh. we should be able to remove this at some point.
            // there are broken jars floating around with ./name and /name
            // in the manifest, and "name" in the zip/jar file.
            attr = man.getAttributes("./"+name);
            if (attr == null) {
                attr = man.getAttributes("/"+name);
                if (attr == null)
                    return;
            }
        }

        for (Map.Entry<Object,Object> se : attr.entrySet()) {
            String key = se.getKey().toString();

            if (key.toUpperCase(Locale.ENGLISH).endsWith("-DIGEST")) {
                // 7 is length of "-Digest"
                String algorithm = key.substring(0, key.length()-7);

                MessageDigest digest = createdDigests.get(algorithm);

                if (digest == null) {
                    try {

                        digest = MessageDigest.getInstance
                                        (algorithm, SunProviderHolder.instance);
                        createdDigests.put(algorithm, digest);
                    } catch (NoSuchAlgorithmException nsae) {
                        // ignore
                    }
                }

                if (digest != null) {
                    skip = false;
                    digest.reset();
                    digests.add(digest);
                    manifestHashes.add(
                                decoder.decodeBuffer((String)se.getValue()));
                }
            }
        }
    }
1367287
public static boolean transformEntries(InputStream is, ZipEntryTransformerEntry[] entries, OutputStream os) {
    if (log.isDebugEnabled())
      log.debug("Copying '" + is + "' to '" + os + "' and transforming entries " + Arrays.asList(entries) + ".");

    try {
      ZipOutputStream out = new ZipOutputStream(os);
      TransformerZipEntryCallback action = new TransformerZipEntryCallback(Arrays.asList(entries), out);
      iterate(is, action);
      // Finishes writing the contents of the ZIP output stream without closing
      // the underlying stream.
      out.finish();
      return action.found();
    }
    catch (IOException e) {
      throw ZipExceptionUtil.rethrow(e);
    }
  }
5723
private void getNextFile(final InputStream is) throws IOException {
    if (is instanceof  java.util.zip.ZipInputStream) {
      ZipEntry ze = ((ZipInputStream) is).getNextEntry();
      while (ze != null && ze.isDirectory())
        ze = ((ZipInputStream) is).getNextEntry();
    }
  }
1358010
public static File writeToTempFile(List<byte[]> bytesList, String prefix, String suffix) throws IOException {
        File tmpOutputFile = null;

        try (RandomAccessFile outputRaf = new RandomAccessFile(tmpOutputFile, "rw")) {
            // Create temporary file
            tmpOutputFile = File.createTempFile(prefix, "." + suffix);
            FileChannel outputChannel = outputRaf.getChannel();

            for (byte[] bytes : bytesList) {
                ByteArrayInputStream is = null;
                try {
                    is = new ByteArrayInputStream(bytes);
                    ReadableByteChannel inputChannel = Channels.newChannel(is);
                    fastChannelCopy(inputChannel, outputChannel);
                } catch (Exception e) {
                    String info = "Failed to write to temporary file: " + e.getMessage();
                    throw new IOException(info, e);
                } finally {
                    if (null != is) is.close();
                }
            }
        } catch (IOException ioe) {
            String info = "Failed to write to temporary file: " + ioe.getMessage();
            throw new IOException(info, ioe);
        }
        return tmpOutputFile;
    }
824950
public static byte[] unpackEntry(InputStream is, String name) {
    ByteArrayUnpacker action = new ByteArrayUnpacker();
    if (!handle(is, name, action))
      return null; // entry not found
    return action.getBytes();
  }
841377
private static File extractFromJar(String resource, String fileName, String suffix)
			throws IOException {
		final URL res = Main.class.getResource(resource);

		// put this jar in a file system so that we can load jars from there
		final File tmp;
		try {
			tmp = File.createTempFile(fileName, suffix);
		} catch (final IOException e) {
			final String tmpdir = System.getProperty("java.io.tmpdir");
			throw new IllegalStateException(
					"JavaMelody has failed to create a temporary file in " + tmpdir, e);
		}
		final InputStream is = res.openStream();
		try {
			final OutputStream os = new FileOutputStream(tmp);
			try {
				copyStream(is, os);
			} finally {
				os.close();
			}
		} finally {
			is.close();
		}
		tmp.deleteOnExit();
		return tmp;
	}
59563
public ClassFile getClassFile(String name) throws IOException {
        if (name.indexOf('.') > 0) {
            int i = name.lastIndexOf('.');
            String pathname = name.replace('.', File.separatorChar) + ".class";
            if (baseFileName.equals(pathname) ||
                    baseFileName.equals(pathname.substring(0, i) + "$" +
                                        pathname.substring(i+1, pathname.length()))) {
                return readClassFile(path);
            }
        } else {
            if (baseFileName.equals(name.replace('/', File.separatorChar) + ".class")) {
                return readClassFile(path);
            }
        }
        return null;
    }
49164
public static File writeZipStreamToTempDir(InputStream inputStream) throws IOException
   {
      File dir = FileHelper.createTempDir();

      try
      {
         processZipStream(dir, inputStream);
      }

      catch (ZipException ex)
      {
         // Java doesn't support zip files with zero byte entries.
         // We could use a different library which does handle these zip files, but
         // I'm reluctant to add new dependencies just for this. Rather than
         // propagating the error, we'll just stop at this point and see if we
         // can make sense of anything we have extracted from the zip file so far.
         // For what it's worth I haven't come across a valid compressed schedule file
         // which includes zero bytes files.
         if (!ex.getMessage().equals("only DEFLATED entries can have EXT descriptor"))
         {
            throw ex;
         }
      }

      return dir;
   }