Copies resources from the jar file of the current thread and extract it
to the destination path.

@param jarConnection
@param destPath destination file or directory
427402
static void copyJarResourceToPath(JarURLConnection jarConnection, File destPath) {
        try (JarFile jarFile = jarConnection.getJarFile()) {
            String jarConnectionEntryName = jarConnection.getEntryName();
            if (!jarConnectionEntryName.endsWith("/")) {
                jarConnectionEntryName += "/";
            }

            /**
             * Iterate all entries in the jar file.
             */
            for (Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) {
                JarEntry jarEntry = e.nextElement();
                String jarEntryName = jarEntry.getName();

                /**
                 * Extract files only if they match the path.
                 */
                if (jarEntryName.startsWith(jarConnectionEntryName)) {
                    String filename = jarEntryName.substring(jarConnectionEntryName.length());
                    File targetFile = new File(destPath, filename);

                    if (jarEntry.isDirectory()) {
                        targetFile.mkdirs();
                    } else {
                        if (!targetFile.exists() || targetFile.length() != jarEntry.getSize()) {
                            try (InputStream is = jarFile.getInputStream(jarEntry);
                                    OutputStream out = FileUtils.openOutputStream(targetFile)) {
                                IOUtils.copy(is, out);
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            logger.warn(e.getMessage(), e);
        }
    }
1284909
public int submitFilePathOrClasspath(
            String filePathOrResourceClasspath) {
        return submitStream(JMOptional
                .getOptional(JMFiles.readLines(filePathOrResourceClasspath))
                .orElseGet(() -> JMResources
                        .readLines(filePathOrResourceClasspath)).stream());
    }
307054
protected void copyJarsToStageDirectory() throws IOException {
        final String stagingDirectory = getDeploymentStagingDirectoryPath();
        info("");
        info(COPY_JARS + stagingDirectory);
        Utils.copyResources(
                getProject(),
                getSession(),
                getMavenResourcesFiltering(),
                getResources(),
                stagingDirectory);
        info(COPY_SUCCESS);
    }
925163
@Override
    public void moveObject(final FedoraSession session, final String source, final String destination) {
        final Session jcrSession = getJcrSession(session);
        try {
            final FedoraResource srcResource = find(session, source);
            final Node sourceNode = getJcrNode(srcResource);
            final String name = sourceNode.getName();
            final Node parent = sourceNode.getDepth() > 0 ? sourceNode.getParent() : null;

            jcrSession.getWorkspace().move(source, destination);

            if (parent != null) {
                createTombstone(parent, name);
            }

            touchLdpMembershipResource(getJcrNode(find(session, source)));
            touchLdpMembershipResource(getJcrNode(find(session, destination)));

        } catch (final RepositoryException e) {
            throw new RepositoryRuntimeException(e);
        }
    }
399425
public static void copyRecursively(Path source, Path destination) throws IOException {
        if (Files.isDirectory(source))
        {
            Files.createDirectories(destination);
            final Set<Path> sources = listFiles(source);

            for (Path srcFile : sources)
            {
                Path destFile = destination.resolve(srcFile.getFileName());
                copyRecursively(srcFile, destFile);
            }
        }
        else
        {
            Files.copy(source, destination, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING);
        }
    }
684518
private void copyResources(File outputDirectory) throws IOException
    {
        copyClasspathResource(outputDirectory, "reportng.css", "reportng.css");
        copyClasspathResource(outputDirectory, "reportng.js", "reportng.js");
        // If there is a custom stylesheet, copy that.
        File customStylesheet = META.getStylesheetPath();

        if (customStylesheet != null)
        {
            if (customStylesheet.exists())
            {
                copyFile(outputDirectory, customStylesheet, CUSTOM_STYLE_FILE);
            }
            else
            {
                // If not found, try to read the file as a resource on the classpath
                // useful when reportng is called by a jarred up library
                InputStream stream = ClassLoader.getSystemClassLoader().getResourceAsStream(customStylesheet.getPath());
                if (stream != null)
                {
                    copyStream(outputDirectory, stream, CUSTOM_STYLE_FILE);
                }
            }
        }
    }
1312338
@COPY
    @Timed
    public void copyResource(@Suspended final AsyncResponse response, @Context final Request request,
            @Context final UriInfo uriInfo, @Context final HttpHeaders headers,
            @Context final SecurityContext security) {
        final TrellisRequest req = new TrellisRequest(request, uriInfo, headers, security);
        final Session session = getSession(req.getPrincipalName());
        final IRI destination = getDestination(headers, getBaseUrl(req));
        final IRI identifier = rdf.createIRI(TRELLIS_DATA_PREFIX + req.getPath());
        // Default is recursive copy as per RFC-4918
        final Depth.DEPTH depth = getDepth(headers.getHeaderString("Depth"));
        getParent(destination).thenCombine(services.getResourceService().get(destination), this::checkResources)
            .thenCompose(parent -> services.getResourceService().touch(parent.getIdentifier()))
            .thenCompose(future -> services.getResourceService().get(identifier))
            .thenApply(this::checkResource)
            .thenCompose(res -> copyTo(res, session, depth, destination, getBaseUrl(req)))
            .thenApply(future -> status(NO_CONTENT).build())
            .exceptionally(this::handleException).thenApply(response::resume);
    }
368695
public static void removeEntries(File zip, String[] paths, File destZip) {
    if (log.isDebugEnabled()) {
      log.debug("Copying '" + zip + "' to '" + destZip + "' and removing paths " + Arrays.asList(paths) + ".");
    }

    ZipOutputStream out = null;
    try {
      out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(destZip)));
      copyEntries(zip, out, new HashSet<String>(Arrays.asList(paths)));
    }
    catch (IOException e) {
      throw ZipExceptionUtil.rethrow(e);
    }
    finally {
      IOUtils.closeQuietly(out);
    }
  }
857239
public static void extract(Resource resource, File directory, boolean deleteOnExit)
        throws IOException
    {
        if(log.isDebugEnabled())log.debug("Extract "+resource+" to "+directory);
        JarInputStream jin = new JarInputStream(resource.getInputStream());
        JarEntry entry=null;
        while((entry=jin.getNextJarEntry())!=null)
        {
            File file=new File(directory,entry.getName());
            if (entry.isDirectory())
            {
                // Make directory
                if (!file.exists())
                    file.mkdirs();
            }
            else
            {
                // make directory (some jars don't list dirs)
                File dir = new File(file.getParent());
                if (!dir.exists())
                    dir.mkdirs();

                // Make file
                FileOutputStream fout = null;
                try
                {
                    fout = new FileOutputStream(file);
                    IO.copy(jin,fout);
                }
                finally
                {
                    IO.close(fout);
                }

                // touch the file.
                if (entry.getTime()>=0)
                    file.setLastModified(entry.getTime());
            }
            if (deleteOnExit)
                file.deleteOnExit();
        }
    }
68899
@ConfigArg(0)
  public void setPath(PathImpl path)
  {
    if (path.getPath().endsWith(".jar")
        || path.getPath().endsWith(".zip")) {
      path = JarPath.create(path);
    }

    _path = path;
  }
796545
public static Action moveFileToEmptyPath(final String srcPath, final String destPath) {
        if (srcPath == null)
            throw new IllegalArgumentException("The srcPath variable cannot be null");
        if (destPath == null)
            throw new IllegalArgumentException("The destPath variable cannot be null");

        return new Action(
            // Perform:
            new ActionBlock() {
                @Override
                public void execute() throws ActionException {
                    File destFile = new File(destPath);
                    if (destFile.exists())
                        throw new ActionException("Cannot move file. " +
                                "The Destination file " + destPath + " already exists.");
                    boolean success = new File(srcPath).renameTo(destFile);
                    if (!success)
                        throw new ActionException("Cannot move file " + srcPath +
                                " to " + destPath);
                }
            },
            // Backout:
            new ActionBlock() {
                @Override
                public void execute() throws ActionException {
                    boolean success = new File(destPath).renameTo(new File(srcPath));
                    if (!success)
                        throw new ActionException("Cannot move file " + destPath +
                                " to " + srcPath);
                }
            },
            // Cleanup:
            null);
    }
1143694
private Set<String> getResourceNamesFromJar(String path, URL resourceURL) {

		URLConnection con = null;

		try {
			if (resourceURL.toString().startsWith(JawrConstant.JAR_URL_PREFIX)) {
				con = resourceURL.openConnection();
			}
		} catch (IOException e) {

			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug("Unable to find resources name for path '" + path + "'", e);
			}
			return Collections.emptySet();
		}

		JarFile jarFile;
		String jarFileUrl;
		String rootEntryPath;
		boolean newJarFile = false;

		try {
			if (con instanceof JarURLConnection) {
				// Should usually be the case for traditional JAR files.
				JarURLConnection jarCon = (JarURLConnection) con;
				jarCon.setUseCaches(true);
				jarFile = jarCon.getJarFile();
				JarEntry jarEntry = jarCon.getJarEntry();
				rootEntryPath = (jarEntry != null ? jarEntry.getName() : "");
			} else {
				// No JarURLConnection -> need to resort to URL file parsing.
				// We'll assume URLs of the format "jar:path!/entry", with the
				// protocol
				// being arbitrary as long as following the entry format.
				// We'll also handle paths with and without leading "file:"
				// prefix.
				String urlFile = resourceURL.getFile();
				int separatorIndex = urlFile.indexOf(JAR_URL_SEPARATOR);
				if (separatorIndex != -1) {
					jarFileUrl = urlFile.substring(0, separatorIndex);
					rootEntryPath = urlFile.substring(separatorIndex + JAR_URL_SEPARATOR.length());
					jarFile = getJarFile(jarFileUrl);
				} else {
					jarFile = new JarFile(urlFile);
					rootEntryPath = "";
				}
				newJarFile = true;
			}
		} catch (IOException e) {
			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug("Unable to find resources name for path '" + path + "'", e);
			}
			return Collections.emptySet();
		}
		try {
			if (!"".equals(rootEntryPath) && !rootEntryPath.endsWith("/")) {
				// Root entry path must end with slash to allow for proper
				// matching.
				// The Sun JRE does not return a slash here, but BEA JRockit
				// does.
				rootEntryPath = rootEntryPath + "/";
			}
			Set<String> result = new LinkedHashSet<>(8);
			for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
				JarEntry entry = entries.nextElement();
				String entryPath = entry.getName();
				if (isDirectChildPath(rootEntryPath, entryPath)) {
					String relativePath = entryPath.substring(rootEntryPath.length());
					result.add(relativePath);
				}
			}
			return result;
		} finally {
			// Close jar file, but only if freshly obtained -
			// not from JarURLConnection, which might cache the file reference.
			if (newJarFile) {
				try {
					jarFile.close();
				} catch (IOException e) {
					// Nothing to do
				}
			}
		}
	}
1215582
public static void copy(File source, File dest) throws IOException {
        if (dest.isDirectory()) {
            dest = new File(dest + File.separator + source.getName());
        }

        FileChannel in = null, out = null;
        try {
            in = new FileInputStream(source).getChannel();
            out = new FileOutputStream(dest).getChannel();

            long size = in.size();
            MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size);

            out.write(buf);
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }
1330170
private void processClasspath(String classpathElement) throws ResourceNotFoundException, ParseErrorException, Exception {
//        getLog().info("Classpath is " + classpathElement);
        if (classpathElement.endsWith(".jar")) {
            // TODO: implement JAR scanning
        } else {
            final File dir = new File(classpathElement);

            processPackage(dir, dir);
        }
    }
434160
@Deprecated
  public void copyFromLocalFile(Path src, Path dst)
    throws IOException {
    copyFromLocalFile(false, true, false, src, dst);
  }
631669
public void moveToLocalFile(Path src, Path dst) throws IOException {
    copyToLocalFile(true, false, src, dst);
  }
148286
private static Collection<? extends URL> doFindPathMatchingJarResources(final URL rootDirResource, final String subPattern) {

        final Set<URL> result = new LinkedHashSet<URL>();

        JarFile jarFile = null;
        String jarFileUrl;
        String rootEntryPath = null;
        URLConnection con;
        boolean newJarFile = false;

        try {
            con = rootDirResource.openConnection();

            if (con instanceof JarURLConnection) {
                final JarURLConnection jarCon = (JarURLConnection) con;

                jarCon.setUseCaches(false);
                jarFile = jarCon.getJarFile();
                jarFileUrl = jarCon.getJarFileURL().toExternalForm();
                final JarEntry jarEntry = jarCon.getJarEntry();

                rootEntryPath = jarEntry != null ? jarEntry.getName() : "";
            } else {
                // No JarURLConnection -> need to resort to URL file parsing.
                // We'll assume URLs of the format "jar:path!/entry", with the
                // protocol
                // being arbitrary as long as following the entry format.
                // We'll also handle paths with and without leading "file:"
                // prefix.
                final String urlFile = rootDirResource.getFile();
                final int separatorIndex = urlFile.indexOf(JAR_URL_SEPARATOR);

                if (separatorIndex != -1) {
                    jarFileUrl = urlFile.substring(0, separatorIndex);
                    rootEntryPath = urlFile.substring(separatorIndex + JAR_URL_SEPARATOR.length());
                    jarFile = getJarFile(jarFileUrl);
                } else {
                    jarFile = new JarFile(urlFile);
                    jarFileUrl = urlFile;
                    rootEntryPath = "";
                }
                newJarFile = true;

            }

        } catch (final IOException e) {
            LOGGER.log(Level.ERROR, "reslove jar File error", e);
            return result;
        }
        try {
            if (!"".equals(rootEntryPath) && !rootEntryPath.endsWith("/")) {
                // Root entry path must end with slash to allow for proper
                // matching.
                // The Sun JRE does not return a slash here, but BEA JRockit
                // does.
                rootEntryPath = rootEntryPath + "/";
            }
            for (final Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements(); ) {
                final JarEntry entry = (JarEntry) entries.nextElement();
                final String entryPath = entry.getName();

                String relativePath = null;

                if (entryPath.startsWith(rootEntryPath)) {
                    relativePath = entryPath.substring(rootEntryPath.length());

                    if (AntPathMatcher.match(subPattern, relativePath)) {
                        if (relativePath.startsWith("/")) {
                            relativePath = relativePath.substring(1);
                        }
                        result.add(new URL(rootDirResource, relativePath));
                    }
                }
            }
            return result;
        } catch (final IOException e) {
            LOGGER.log(Level.ERROR, "parse the JarFile error", e);
        } finally {
            // Close jar file, but only if freshly obtained -
            // not from JarURLConnection, which might cache the file reference.
            if (newJarFile) {
                try {
                    jarFile.close();
                } catch (final IOException e) {
                    LOGGER.log(Level.WARN, " occur error when closing jarFile", e);
                }
            }
        }
        return result;
    }