copy source file to destination file or path

@throws PageException
549047
public static void actionCopy(PageContext pageContext, lucee.runtime.security.SecurityManager securityManager, Resource source, String strDestination, int nameconflict,
	    String serverPassword, Object acl, int mode, String attributes) throws PageException {
	if (nameconflict == NAMECONFLICT_UNDEFINED) nameconflict = NAMECONFLICT_OVERWRITE;

	if (source == null) throw new ApplicationException("attribute source is not defined for tag file");
	if (StringUtil.isEmpty(strDestination)) throw new ApplicationException("attribute destination is not defined for tag file");

	Resource destination = toDestination(pageContext, strDestination, source);

	securityManager.checkFileLocation(pageContext.getConfig(), source, serverPassword);
	securityManager.checkFileLocation(pageContext.getConfig(), destination, serverPassword);

	// source
	if (!source.exists()) throw new ApplicationException("source file [" + source.toString() + "] doesn't exist");
	else if (!source.isFile()) throw new ApplicationException("source file [" + source.toString() + "] is not a file");
	else if (!source.canRead()) throw new ApplicationException("no access to source file [" + source.toString() + "]");

	// destination
	if (destination.isDirectory()) destination = destination.getRealResource(source.getName());
	if (destination.exists()) {
	    // SKIP
	    if (nameconflict == NAMECONFLICT_SKIP) return;
	    // SKIP
	    else if (nameconflict == NAMECONFLICT_OVERWRITE) destination.delete();
	    // MAKEUNIQUE
	    else if (nameconflict == NAMECONFLICT_MAKEUNIQUE) destination = makeUnique(destination);
	    // ERROR
	    else throw new ApplicationException("destiniation file [" + destination.toString() + "] already exist");
	}

	setACL(pageContext, destination, acl);
	try {
	    IOUtil.copy(source, destination);
	}
	catch (IOException e) {

	    ApplicationException ae = new ApplicationException("can't copy file [" + source + "] to [" + destination + "]", e.getMessage());
	    ae.setStackTrace(e.getStackTrace());
	    throw ae;
	}

	setMode(destination, mode);
	setAttributes(destination, attributes);
    }
567760
public static void updateFileFromUrl(final String sourceUrl, final String destinationFilePath,
                                         final String username, final String password) throws
        UpdateException {
        updateFileFromUrl(sourceUrl, destinationFilePath, username, password, URLFileUpdater.factory());
    }
1365617
private void actionWrite() throws PageException {
	if (output == null) throw new ApplicationException("attribute output is not defined for tag file");
	checkFile(pageContext, securityManager, file, serverPassword, createPath, true, false, true);
	if (file.exists()) {
	    // Error
	    if (nameconflict == NAMECONFLICT_ERROR) throw new ApplicationException("destination file [" + file + "] already exist");
	    // SKIP
	    else if (nameconflict == NAMECONFLICT_SKIP) return;
	    // OVERWRITE
	    else if (nameconflict == NAMECONFLICT_OVERWRITE) file.delete();
	}

	setACL(pageContext, file, acl);
	try {
	    if (output instanceof InputStream) {
		IOUtil.copy((InputStream) output, file, false);
	    }
	    else if (Decision.isCastableToBinary(output, false)) {
		IOUtil.copy(new ByteArrayInputStream(Caster.toBinary(output)), file, true);
	    }
	    else {
		String content = Caster.toString(output);
		if (fixnewline) content = doFixNewLine(content);
		if (addnewline) content += SystemUtil.getOSSpecificLineSeparator();

		IOUtil.write(file, content, CharsetUtil.toCharset(charset), false);

	    }
	}
	catch (UnsupportedEncodingException e) {
	    throw new ApplicationException("Unsupported Charset Definition [" + charset + "]", e.getMessage());
	}
	catch (IOException e) {

	    throw new ApplicationException("can't write file " + file.getAbsolutePath(), e.getMessage());
	}
	setMode(file, mode);
	setAttributes(file, attributes);
    }
48705
private void doDelete() throws PageException, SearchException {
	required("index", action, "collection", collection);
	if (type != SearchIndex.TYPE_CUSTOM) required("index", action, "key", key);

	// no type defined
	if (type == -1) {
	    if (query != null) {
		type = SearchIndex.TYPE_CUSTOM;
	    }
	    else {
		Resource file = null;
		try {
		    file = ResourceUtil.toResourceExisting(pageContext, key);
		    pageContext.getConfig().getSecurityManager().checkFileLocation(file);
		}
		catch (ExpressionException e) {}

		if (file != null && file.exists() && file.isFile()) type = SearchIndex.TYPE_FILE;
		else if (file != null && file.exists() && file.isDirectory()) type = SearchIndex.TYPE_PATH;
		else {
		    try {
			new URL(key);
			type = SearchIndex.TYPE_URL;
		    }
		    catch (MalformedURLException e) {}
		}
	    }
	}

	collection.deleteIndex(pageContext, key, type, query);
    }
1218688
public void setPath(String strPath) throws PageException {
	if (strPath == null) return;
	this.path = ResourceUtil.toResourceNotExisting(pageContext, strPath.trim());
	// this.path=new File(path.toLowerCase().trim());

	pageContext.getConfig().getSecurityManager().checkFileLocation(this.path);

	if (!this.path.exists()) {
	    Resource parent = this.path.getParentResource();
	    if (parent != null && parent.exists()) this.path.mkdirs();
	    else {
		throw new ApplicationException("attribute path of the tag collection must be a existing directory");
	    }
	}
	else if (!this.path.isDirectory()) throw new ApplicationException("attribute path of the tag collection must be a existing directory");
    }
1267439
public static void copy(File source, File target) throws IOException {
        if (!source.exists()) {
            throw new FileNotFoundException("Source file not found:" + source.getAbsolutePath());
        }

        if (!target.exists() && !target.getParentFile().exists() && !target.getParentFile().mkdirs()) {
            throw new IOException("Can't create target directory:" + target.getParentFile().getAbsolutePath());
        }
        FileInputStream is = new FileInputStream(source);
        FileOutputStream os = new FileOutputStream(target);
        IOHelper.copy(is, os);
    }
1083396
void copyTo(final File destinationFolder) throws IOException {
    for (final File f : this.theFiles) {
      final File destinationFile = new File(destinationFolder, f.getName());
      Files.copy(f.toPath(), destinationFile.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING);
    }
  }
438111
public static void copyFile(File sourceFile, File destinationFile) throws FileNotFoundException, IOException {
		Streams.copyStream(new FileInputStream(sourceFile), new FileOutputStream(destinationFile), true);
	}
225721
private void copyResources( List fileSets )
        throws MojoExecutionException
    {
        final String[] emptyStrArray = {};
        
        for ( Iterator it = fileSets.iterator(); it.hasNext(); )
        {
            FileSet fileSet = (FileSet) it.next();

            File resourceDirectory = new File( fileSet.getDirectory() );
            if ( !resourceDirectory.isAbsolute() )
            {
                resourceDirectory = new File( project.getBasedir(), resourceDirectory.getPath() );
            }

            if ( !resourceDirectory.exists() )
            {
                getLog().info( "Additional resource directory does not exist: " + resourceDirectory );
                continue;
            }

            DirectoryScanner scanner = new DirectoryScanner();

            scanner.setBasedir( resourceDirectory );
            if ( fileSet.getIncludes() != null && !fileSet.getIncludes().isEmpty() )
            {
                scanner.setIncludes( (String[]) fileSet.getIncludes().toArray( emptyStrArray ) );
            }
            else
            {
                scanner.setIncludes( DEFAULT_INCLUDES );
            }

            if ( fileSet.getExcludes() != null && !fileSet.getExcludes().isEmpty() )
            {
                scanner.setExcludes( (String[]) fileSet.getExcludes().toArray( emptyStrArray ) );
            }

            if (fileSet.isUseDefaultExcludes())
            {
                scanner.addDefaultExcludes();
            }

            scanner.scan();

            List includedFiles = Arrays.asList( scanner.getIncludedFiles() );

            getLog().info( "Copying " + includedFiles.size() + " additional resource"
                           + ( includedFiles.size() > 1 ? "s" : "" ) );

            for ( Iterator j = includedFiles.iterator(); j.hasNext(); )
            {
                String destination = (String) j.next();
                File source = new File( resourceDirectory, destination );
                File destinationFile = new File( buildDirectory, destination );

                if ( !destinationFile.getParentFile().exists() )
                {
                    destinationFile.getParentFile().mkdirs();
                }

                try
                {
                    FileUtils.copyFile(source, destinationFile);
                }
                catch ( IOException e )
                {
                    throw new MojoExecutionException( "Error copying additional resource " + source, e );
                }
            }
        }
    }
1058705
public void copyFromPagesToView(
			AbstractPagedInputView source, DataOutputView target) throws IOException {
		checkSkipReadForFixLengthPart(source);
		int length = source.readInt();
		target.writeInt(length);
		target.write(source, length);
	}
293337
function copyFile(srcPath, destPath) {
        let srcFileInfo = path.parse(srcPath) || {};
        if (!path.extname(destPath) && srcFileInfo.ext) {
            // destination is a directory!
            return copyFileIntoDirectory(srcPath, destPath);
        } else {
            return new Promise(function (resolve, reject) {
                fs.copy(srcPath, destPath, function (err) {
                    if (!err) {
                        resolve();
                    } else {
                        reject(err);
                    }
                });
            });
        }
    }
811440
public void actionCopy() throws JspException {

        // save initialized instance of this class in request attribute for included sub-elements
        getJsp().getRequest().setAttribute(SESSION_WORKPLACE_CLASS, this);
        CmsResource resource = null;
        try {
            boolean isFolder = false;
            String source = getResourceList().get(0);
            String target = CmsLinkManager.getAbsoluteUri(getParamTarget(), CmsResource.getParentFolder(source));
            if (!isMultiOperation()) {
                resource = getCms().readResource(source, CmsResourceFilter.ALL);
                isFolder = resource.isFolder();
            } else {
                String siteRootFolder = null;
                try {
                    // check if a site root was added to the target name
                    if (OpenCms.getSiteManager().getSiteRoot(target) != null) {
                        siteRootFolder = getCms().getRequestContext().getSiteRoot();
                        if (siteRootFolder.endsWith("/")) {
                            siteRootFolder = siteRootFolder.substring(0, siteRootFolder.length() - 1);
                        }
                        getCms().getRequestContext().setSiteRoot("/");
                    }
                    resource = getCms().readResource(target, CmsResourceFilter.ALL);
                } finally {
                    if (siteRootFolder != null) {
                        getCms().getRequestContext().setSiteRoot(siteRootFolder);
                    }
                }
                if (!resource.isFolder()) {
                    // no folder selected for multi operation, throw exception
                    throw new CmsVfsException(
                        Messages.get().container(Messages.ERR_COPY_MULTI_TARGET_NOFOLDER_1, target));
                }
            }
            if (performDialogOperation()) {
                // if no exception is caused and "true" is returned copy operation was successful
                if (isMultiOperation() || isFolder) {
                    // set request attribute to reload the explorer tree view
                    List<String> folderList = new ArrayList<String>(1);
                    String targetParent = CmsResource.getParentFolder(target);
                    folderList.add(targetParent);
                    getJsp().getRequest().setAttribute(REQUEST_ATTRIBUTE_RELOADTREE, folderList);
                }
                actionCloseDialog();
            } else {
                // "false" returned, display "please wait" screen
                getJsp().include(FILE_DIALOG_SCREEN_WAIT);
            }
        } catch (Throwable e) {
            // check if this exception requires a confirmation or error screen for single resource operations
            if (!isMultiOperation()
                && ((e instanceof CmsVfsResourceAlreadyExistsException) || (e instanceof CmsLockException))
                && (resource != null)
                && !(resource.isFolder())) {
                // file copy but file already exists, now check target file type
                int targetType = -1;
                String storedSiteRoot = null;
                try {
                    if (OpenCms.getSiteManager().getSiteRoot(getParamTarget()) != null) {
                        storedSiteRoot = getCms().getRequestContext().getSiteRoot();
                        getCms().getRequestContext().setSiteRoot("/");
                    }
                    CmsResource targetRes = getCms().readResource(getParamTarget());
                    targetType = targetRes.getTypeId();
                } catch (CmsException e2) {
                    // can usually be ignored
                    if (LOG.isInfoEnabled()) {
                        LOG.info(e2.getLocalizedMessage());
                    }
                } finally {
                    if (storedSiteRoot != null) {
                        getCms().getRequestContext().setSiteRoot(storedSiteRoot);
                    }
                }
                if (resource.getTypeId() == targetType) {
                    // file type of target is the same as source, show confirmation dialog
                    setParamMessage(
                        CmsStringUtil.escapeHtml(key(
                            Messages.GUI_COPY_CONFIRM_OVERWRITE_2,
                            new Object[] {getParamResource(), getParamTarget()})));
                    getJsp().include(FILE_DIALOG_SCREEN_CONFIRM);
                } else {
                    // file type is different, create error message
                    includeErrorpage(this, e);
                }
            } else {
                // error during copy, show error dialog
                includeErrorpage(this, e);
            }
        }
    }
1253909
public static void copy(FileObject source, FileObject target) throws IOException {
        InputStream in = source.openInputStream();
        OutputStream out = target.openOutputStream();
        try {
            byte[] buffer = new byte[1024];
            int len = in.read(buffer);
            while (len != -1) {
                out.write(buffer, 0, len);
                len = in.read(buffer);
            }
        } finally {
            in.close();
            out.close();
        }
    }
511500
private function copyAllWebsiteFiles()
    {
        // routes

        // VIEWS
        $source = "{$this->basePath}resources{$this->ds}views{$this->ds}website";
        $destination = resource_path("views{$this->ds}website");
        $this->copyFilesFromSource($source, $destination);

        // WEBSITE master layout
        $source = "{$this->basePath}resources{$this->ds}views{$this->ds}layouts{$this->ds}website.blade.php";
        $destination = resource_path("views{$this->ds}layouts");
        $this->copyFilesFromSource($source, $destination);

        // PARTIALS
        $source = "{$this->basePath}resources{$this->ds}views{$this->ds}partials";
        $destination = resource_path("views{$this->ds}partials");
        $this->copyFilesFromSource($source, $destination);

        // CONTROLLERS
        $source = "{$this->appPath}Controllers{$this->ds}Website";
        $destination = app_path("Http{$this->ds}Controllers{$this->ds}Website");

        // copy files and replace namespace and views only
        $this->copyFilesFromSource($source, $destination, 'namespace_views');

        // SEEDS
        $search = "{$this->baseNamespace}\Seeds;";
        $source = "{$this->basePath}database{$this->ds}seeds{$this->ds}UsersTableSeeder.php";
        $destination = database_path("seeds");
        $this->copyFilesFromSource($source, $destination, $search, "");

        // EVENTS (todo, admin for now)
        // MAILS (todo, admin for now)
        // NOTIFICATIONS (todo, admin for now)

        // webpack.js, packages.json root files
        $base = $source = $this->basePath . "resources" . $this->ds . "assets_setup" . $this->ds;
        $source = [
            $base . "webpack.mix.js",
            $base . "package.json",
            $base . "package-lock.json",
        ];
        $this->copyFilesFromSource($source, base_path(), false);

        // ASSETS
        $source = "{$this->basePath}resources{$this->ds}assets{$this->ds}";
        $destination = resource_path("assets{$this->ds}");
        // css
        $this->copyFilesFromSource("{$source}css", "{$destination}css", false);
        // fonts
        $this->copyFilesFromSource("{$source}fonts", "{$destination}fonts", false);
        // images
        $this->copyFilesFromSource("{$source}images", "{$destination}images", false);
        // js
        $this->copyFilesFromSource("{$source}js", "{$destination}js", false);
        // sass
        $this->copyFilesFromSource("{$source}sass", "{$destination}sass", false);

        // public/assets
        $this->copyFilesFromSource($this->basePath . 'public', base_path('public'));
    }
1333563
public static void copyFile(@Nonnull File src, @Nonnull File dst) throws BuildException {
        Copy cp = new Copy();
        cp.setProject(new org.apache.tools.ant.Project());
        cp.setTofile(dst);
        cp.setFile(src);
        cp.setOverwrite(true);
        cp.execute();
    }
942341
static void copyDirectory(File sourceDirectory, File targetDirectory) throws IOException {

		final Path sourcePath = Paths.get(sourceDirectory.toURI()).toRealPath();
		final Path targetPath = Paths.get(targetDirectory.toURI());

		Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() {
			@Override
			public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
				Path relative = sourcePath.relativize(dir);
				Path target = targetPath.resolve(relative);
				File folder = target.toFile();
				if (!folder.exists()) {
					mkdirs(folder);
				}
				return FileVisitResult.CONTINUE;
			}

			@Override
			public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
				Path relative = sourcePath.relativize(file);
				Path target = targetPath.resolve(relative);
				Files.copy(file, target, StandardCopyOption.COPY_ATTRIBUTES);
				return FileVisitResult.CONTINUE;
			}
		});
	}
738826
public void copyToLocalFile(Path src, Path dst, boolean copyCrc)
    throws IOException {
    if (!fs.isDirectory(src)) { // source is a file
      fs.copyToLocalFile(src, dst);
      FileSystem localFs = getLocal(getConf()).getRawFileSystem();
      if (localFs.isDirectory(dst)) {
        dst = new Path(dst, src.getName());
      }
      dst = getChecksumFile(dst);
      if (localFs.exists(dst)) { //remove old local checksum file
        localFs.delete(dst, true);
      }
      Path checksumFile = getChecksumFile(src);
      if (copyCrc && fs.exists(checksumFile)) { //copy checksum file
        fs.copyToLocalFile(checksumFile, dst);
      }
    } else {
      FileStatus[] srcs = listStatus(src);
      for (FileStatus srcFile : srcs) {
        copyToLocalFile(srcFile.getPath(), 
                        new Path(dst, srcFile.getPath().getName()), copyCrc);
      }
    }
  }