Copies the program jar to a local temp file and return a {@link Program} instance
with {@link Program#getJarLocation()} points to the local temp file.
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);
  }
585922
private static void copyToLocal(Metadata src, Path dst) throws IOException {
    FileChannel dstCh = FileChannel.open(
        dst, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW);
    ReadableByteChannel srcCh = FileSystems.open(src.resourceId());
    long srcSize = src.sizeBytes();
    long copied = 0;
    do {
      copied += dstCh.transferFrom(srcCh, copied, srcSize - copied);
    } while (copied < srcSize);
    dstCh.close();
    srcCh.close();
    Preconditions.checkState(copied == srcSize);
  }
1344893
public URI generateShimJarFile() {

    try {
      Set<FileResource> globalFiles = new HashSet<>();

      final File globalFolder = new File(this.reefFileNames.getGlobalFolderPath());
      final File[] filesInGlobalFolder = globalFolder.listFiles();

      for (final File fileEntry : filesInGlobalFolder != null ? filesInGlobalFolder : new File[]{}) {
        globalFiles.add(getFileResourceFromFile(fileEntry, FileType.LIB));
      }

      File jarFile = this.jobJarMaker.newBuilder()
          .addGlobalFileSet(globalFiles)
          .build();

      return uploadFile(jarFile);
    } catch (IOException ex) {
      LOG.log(Level.SEVERE, "Failed to build JAR file", ex);
      throw new RuntimeException(ex);
    }
  }
768083
protected File createTempFile() throws IOException {

        final File tempFile = newFile();
        if (forceContent && contentUrl == null) {
            throw new AssertionError("ContentUrl is not set");
        } else if (contentUrl == null) {
            createEmptyFile(tempFile);
        } else {
            try (InputStream inputStream = contentUrl.openStream()) {
                Files.copy(inputStream, tempFile.toPath());
            }
        }
        return tempFile;
    }
1195895
private void copySoapuiJar(File sourceDirectory, File destinationDirectory) throws IOException {
        getLog().info("Copying soapui jar to " + destinationDirectory);
        File[] mainJars = sourceDirectory.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                if (name.toLowerCase().startsWith("soapui") && name.toLowerCase().endsWith(".jar"))
                    return true;
                return false;
            }
        });

        if (mainJars.length == 0) {
            throw new RuntimeException("Unable to found a soapui jar in " + sourceDirectory);
        }
        File soapuiSourceJar = mainJars[0];
        FileUtils.copyFileToDirectory(soapuiSourceJar, destinationDirectory);
        getLog().info("Copy done");
    }
936380
private void copyAgentJar(TaskListener listener, String workingDirectory) throws IOException, InterruptedException {
        String fileName = workingDirectory + SLASH_AGENT_JAR;

        listener.getLogger().println(Messages.SSHLauncher_StartingSFTPClient(getTimestamp()));
        SFTPClient sftpClient = null;
        try {
            sftpClient = new SFTPClient(connection);

            try {
                SFTPv3FileAttributes fileAttributes = sftpClient._stat(workingDirectory);
                if (fileAttributes==null) {
                    listener.getLogger().println(Messages.SSHLauncher_RemoteFSDoesNotExist(getTimestamp(),
                            workingDirectory));
                    sftpClient.mkdirs(workingDirectory, 0700);
                } else if (fileAttributes.isRegularFile()) {
                    throw new IOException(Messages.SSHLauncher_RemoteFSIsAFile(workingDirectory));
                }

                listener.getLogger().println(Messages.SSHLauncher_CopyingAgentJar(getTimestamp()));
                byte[] agentJar = new Slave.JnlpJar(AGENT_JAR).readFully();

                // If the agent jar already exists see if it needs to be updated
                boolean overwrite = true;
                if (sftpClient.exists(fileName)) {
                    String sourceAgentHash = getMd5Hash(agentJar);
                    String existingAgentHash = getMd5Hash(readInputStreamIntoByteArrayAndClose(sftpClient.read(fileName)));
                    listener.getLogger().println(MessageFormat.format( "Source agent hash is {0}. "
                      + "Installed agent hash is {1}", sourceAgentHash, existingAgentHash));

                    overwrite = !sourceAgentHash.equals(existingAgentHash);
                }

                if (overwrite) {
                    try {
                        // try to delete the file in case the agent we are copying is shorter than the agent
                        // that is already there
                        sftpClient.rm(fileName);
                    } catch (IOException e) {
                        // the file did not exist... so no need to delete it!
                    }

                    try (OutputStream os = sftpClient.writeToFile(fileName)) {
                        os.write(agentJar);
                        listener.getLogger()
                          .println(Messages.SSHLauncher_CopiedXXXBytes(getTimestamp(), agentJar.length));
                    } catch (Error error) {
                        throw error;
                    } catch (Throwable e) {
                        throw new IOException(Messages.SSHLauncher_ErrorCopyingAgentJarTo(fileName), e);
                    }
                }else{
                    listener.getLogger().println("Verified agent jar. No update is necessary.");
                }
            } catch (Error error) {
                throw error;
            } catch (Throwable e) {
                throw new IOException(Messages.SSHLauncher_ErrorCopyingAgentJarInto(workingDirectory), e);
            }
        } catch (IOException e) {
            if (sftpClient == null) {
                e.printStackTrace(listener.error(Messages.SSHLauncher_StartingSCPClient(getTimestamp())));
                // lets try to recover if the agent doesn't have an SFTP service
                copySlaveJarUsingSCP(listener, workingDirectory);
            } else {
                throw e;
            }
        } finally {
            if (sftpClient != null) {
                sftpClient.close();
            }
        }
    }
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();
    }
1249554
private void copyDependencyJarsToHdfs() throws IOException {
    if (!this.state.contains(ConfigurationKeys.JOB_JAR_FILES_KEY)) {
      return;
    }
    LocalFileSystem lfs = FileSystem.getLocal(this.conf);
    Path tmpJarFileDir = new Path(this.tmpOutputDir, "_gobblin_compaction_jars");
    this.state.setProp(COMPACTION_JARS, tmpJarFileDir.toString());
    this.fs.delete(tmpJarFileDir, true);
    for (String jarFile : this.state.getPropAsList(ConfigurationKeys.JOB_JAR_FILES_KEY)) {
      for (FileStatus status : lfs.globStatus(new Path(jarFile))) {
        Path tmpJarFile = new Path(this.fs.makeQualified(tmpJarFileDir), status.getPath().getName());
        this.fs.copyFromLocalFile(status.getPath(), tmpJarFile);
        LOG.info(String.format("%s will be added to classpath", tmpJarFile));
      }
    }
  }
610162
static Jar getJar(PathImpl backing)
  {
    if (_jarCache != null) {
      Jar jar = _jarCache.get(backing);

      return jar;
    }

    return null;
  }
1244157
protected JarFile getJarFile(String jarFileUrl) throws IOException {
        if (jarFileUrl.startsWith(ResourceUtils.FILE_URL_PREFIX)) {
            try {
                return new JarFile(ResourceUtils.toURI(jarFileUrl).getSchemeSpecificPart());
            } catch (URISyntaxException ex) {
                // Fallback for URLs that are not valid URIs (should hardly ever happen).
                return new JarFile(jarFileUrl.substring(ResourceUtils.FILE_URL_PREFIX.length()));
            }
        }
        return new JarFile(jarFileUrl);
    }
366621
private static File whoAmI() throws IOException {
		// JNLP returns the URL where the jar was originally placed (like http://...)
		// not the local cached file. So we need a rather round about approach to get to
		// the local file name.
		// There is no portable way to find where the locally cached copy
		// of war/jar is; JDK 6 is too smart. (See JENKINS-2326.)
		try {
			return whoAmIFromJnlp();
		} catch (final Exception x) {
			getSystemErrorStream().println(
					"INFO: ZipFile.name trick did not work (" + x.toString() + "), using fallback");
		}
		final File myself = File.createTempFile("javamelody", ".jar");
		myself.deleteOnExit();
		final InputStream is = Main.class.getProtectionDomain().getCodeSource().getLocation()
				.openStream();
		try {
			final OutputStream os = new FileOutputStream(myself);
			try {
				copyStream(is, os);
			} finally {
				os.close();
			}
		} finally {
			is.close();
		}
		return myself;
	}
839213
private String getRealPath( String path )
            throws IOException
    {

        URL fileURL = _servletContext.getResource( path );

        File tempDir = (File) _servletContext.getAttribute( "javax.servlet.context.tempdir" );

        // download file into temp dir
        if ( fileURL != null )
        {
            File newFile = File.createTempFile( "temp", ".jar", tempDir );
            if ( download( fileURL, newFile ) )
            {
                String filePath = newFile.getPath();
                return filePath;
            }
        }
        return null;
    }
572831
static void copyFileFromResources(String sourcePath, String destPath) throws IOException {
        LOGGER.entering(new Object[] { sourcePath, destPath });

        File downloadFile = new File(destPath);

        if (!downloadFile.exists()) {
            InputStream stream = JarSpawner.class.getResourceAsStream(sourcePath);
            FileUtils.copyInputStreamToFile(stream, downloadFile);
            LOGGER.fine("File copied to " + destPath);
        }
        LOGGER.exiting();
    }
489177
private File getTempFolder(String tempPath) {
        if (tempPath != null) {
            File folder = new File(tempPath);
            if (folder.exists()) {
                return folder;
            }
        }
        return null;
    }
557881
@SuppressWarnings("deprecation")
    @Override
    public File getFile(String path, boolean nativeCode) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            Tr.debug(tc, " asked to getFile for path " + path);

        path = preSlashify(path);
        if (path.equals("/")) {
            // return a file for "/" .. for normal bundles this would be the jar
            // or directory. For loose, we might have a dir mapped to root, or may not
            // if we do, we'll try using it.
            if (container.getPhysicalPath() != null)
                return new File(container.getPhysicalPath());
            else
                return null;
        }
        final Entry entry = container.getEntry(path);
        if (entry == null) {
            //no entry found for path, bundle has been asked for a file/path that doesn't exist.
            //can happen via bundle-classpath entries for paths that don't exist in the bundle.
            return null;
        }
        Container entryContainer = getContainer(entry);
        if (entryContainer == null) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                Tr.debug(tc, " returning file for entry at " + path + " @ " + entry.getPhysicalPath());

            // this is a 'normal entry' we are going to assume we can get a real file
            // we are allowed to use getPhysicalPath, as this layer has to see through the abstraction for
            // leaf nodes that are files.
            final String physical = entry.getPhysicalPath();
            if (physical != null) {
                return AccessController.doPrivileged(new PrivilegedAction<File>() {
                    @Override
                    public File run() {
                        return new File(physical);
                    }

                });
            }
            // TODO Going to have to extract the content out to a file on disk

            // This would be a case where an entry in a container has no physical path. 
            // If loose config allowed jars to be mapped as directories, this would occur there.

            // Jars mapped as files are already handled by equinox natively, so the lack of 
            // physical paths there will not cause issues.

            // The other common source of imaginary physical paths is intermediate directory 
            // creation..  
            // (eg, mapping /etc/fred.txt as /etc/fish/goat/horse/fred.txt and asking for physical path of 'goat')

            // Current artifact implementations always have a physical path, but this may not remain true 
            // forever, so this case DOES need to be handled, else we'll have some very entertaining 
            // bugs to handle for future deployment types. 
            return null;
        }

        if (nativeCode) {
            // native code is not supported as a container
            return null;
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            Tr.debug(tc, " entry was a container.. but was it root? " + entryContainer.isRoot());
        if (!entryContainer.isRoot()) {
            // If the container is not a root then it is 
            // a simple directory in an archive; just return null.
            // The framework will handle nested directories in archives
            return null;
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            Tr.debug(tc, " leaf node was a root container, so use marker file for equinox");

        // This is a root container and may be on the bundle classpath.
        // Need to create a temp file to return so we can find this container later when a bundle file is created
        final File tempBase = context.getDataFile("nestedTempFiles");
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            Tr.debug(tc, " creating a temp dir, request was for " + path + " the nested path");

        // create the temp dir, if needed.. not clear
        if (!AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
            @Override
            public Boolean run() {
                return tempBase.exists() || tempBase.mkdirs();
            }
        })) {
            //no chained exception will mean mkdirs failed.
            throw new IllegalStateException();
        }
        try {
            File t = null;
            try {
                t = AccessController.doPrivileged(new PrivilegedExceptionAction<File>() {
                    @Override
                    public File run() throws IOException {
                        return File.createTempFile(entry.getName(), null, tempBase);
                    }
                });
            } catch (PrivilegedActionException e) {
                Exception e2 = e.getException();
                if (e2 instanceof IOException)
                    throw (IOException) e2;
                if (e2 instanceof RuntimeException)
                    throw (RuntimeException) e2;
                throw new UndeclaredThrowableException(e);
            }
            final File tempKey = t;

            // Add it to the nestedFiles map so that the ModuleBundleFileFactory impl can
            // find the container if the framework attempts to create a bundle file from it.
            nestedFiles.put(tempKey, entryContainer);
            AccessController.doPrivileged(new PrivilegedAction<Object>() {
                @Override
                public Object run() {
                    tempKey.deleteOnExit();
                    return null;
                }
            });

            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                Tr.debug(tc, " returning a tempkey file.. " + tempKey.getAbsolutePath());
            return tempKey;
        } catch (IOException e) {
            //chained exception will mean the temp create failed.
            throw new IllegalStateException(e);
        }
    }
1129883
public static File lookupJarFile() {
        try {
            return new File(OptionsAndArgs.class
                                    .getProtectionDomain()
                                    .getCodeSource()
                                    .getLocation()
                                    .toURI());
        } catch (URISyntaxException e) {
            throw new IllegalStateException("Error: Cannot lookup jar for this class: " + e,e);
        }
    }
742004
public static File copyToTempFile(InputStream serialization)
            throws IOException, FileNotFoundException {
        File tempFile = createTempFile();
        StreamUtility.pipeStream(serialization,
                                 new FileOutputStream(tempFile),
                                 4096);
        return tempFile;
    }