/** * Copies the resources from the specified module that affects itself. Resources that affect dependencies of the * specified module are not copied. */ private void copyOwnResources(List<CarnotzetModule> processedModules, CarnotzetModule module) throws IOException { Path expandedJarPath = expandedJars.resolve(module.getName()); Path resolvedModulePath = resolved.resolve(module.getServiceId()); if (!resolvedModulePath.toFile().exists() && !resolvedModulePath.toFile().mkdirs()) { throw new CarnotzetDefinitionException("Could not create directory " + resolvedModulePath); } // copy all regular files at the root of the expanded jar (such as carnotzet.properties) // copy all directories that do not reconfigure another module from the expanded jar recursively Files.find(expandedJarPath, 1, isRegularFile().or(nameMatchesModule(processedModules).negate())) .forEach(source -> { try { if (Files.isRegularFile(source)) { Files.copy(source, resolvedModulePath.resolve(source.getFileName()), StandardCopyOption.REPLACE_EXISTING); } else if (Files.isDirectory(source)) { FileUtils.copyDirectory(source.toFile(), resolvedModulePath.resolve(source.getFileName()).toFile()); } } catch (IOException e) { throw new UncheckedIOException(e); } }); }
@Override public void add( String name ) { try { if ( name.matches( ".*\\.mine$|.*\\.r\\d+$" ) ) { // Resolve a conflict File conflicted = new File( directory + File.separator + FilenameUtils.separatorsToSystem( FilenameUtils.removeExtension( name ) ) ); FileUtils.rename( new File( directory, name ), conflicted, StandardCopyOption.REPLACE_EXISTING ); svnClient.resolved( conflicted ); } else { svnClient.addFile( new File( directory, name ) ); } } catch ( Exception e ) { showMessageBox( BaseMessages.getString( PKG, "Dialog.Error" ), e.getMessage() ); } }
public static final void copyFilesInDirectory(File from, File to) throws IOException { if (!to.exists()) { to.mkdirs(); } for (File file : from.listFiles()) { if (file.isDirectory()) { copyFilesInDirectory(file, new File(to.getAbsolutePath() + "/" + file.getName())); } else { File n = new File(to.getAbsolutePath() + "/" + file.getName()); Files.copy(file.toPath(), n.toPath(), StandardCopyOption.REPLACE_EXISTING); } } }
public boolean download(String siaPath, Path destination) { LOGGER.info("downloading {}", siaPath); // final String dest = destination.toAbsolutePath().toString(); final FileTime lastModified = SiaFileUtil.getFileTime(siaPath); final String tempFileName = destination.getFileName().toString() + ".tempdownload"; Path tempFile = destination.getParent().resolve(tempFileName); final HttpResponse<String> downloadResult = siaCommand(SiaCommand.DOWNLOAD, ImmutableMap.of("destination", tempFile.toAbsolutePath().toString()), siaPath); final boolean noHosts = checkErrorFragment(downloadResult, NO_HOSTS); if (noHosts) { LOGGER.warn("unable to download file {} due to NO_HOSTS ", siaPath); return false; } if (statusGood(downloadResult)) { try { Files.setLastModifiedTime(tempFile, lastModified); Files.move(tempFile, destination, StandardCopyOption.ATOMIC_MOVE); Files.setLastModifiedTime(destination, lastModified); } catch (IOException e) { throw new RuntimeException("unable to do atomic swap of file " + destination); } return true; } LOGGER.warn("unable to download siaPath {} for an unexpected reason: {} ", siaPath, downloadResult.getBody()); return false; }
/** * Copies YANG files to the current project's output directory. * * @param yangFileInfo list of YANG files * @param outputDir project's output directory * @param project maven project * @throws IOException when fails to copy files to destination resource directory */ public static void copyYangFilesToTarget(Set<YangFileInfo> yangFileInfo, String outputDir, MavenProject project) throws IOException { List<File> files = getListOfFile(yangFileInfo); String path = outputDir + TARGET_RESOURCE_PATH; File targetDir = new File(path); targetDir.mkdirs(); for (File file : files) { Files.copy(file.toPath(), new File(path + file.getName()).toPath(), StandardCopyOption.REPLACE_EXISTING); } addToProjectResource(outputDir + SLASH + TEMP + SLASH, project); }
/** * Prepare jars files for the tests */ private static void setup () throws IOException { Path classes = Paths.get(WORK_DIR); Path testSrc = Paths.get(System.getProperty("test.src"), "test1", "com", "foo", "TestClass.java"); Path targetDir = classes.resolve("test3"); Path testTarget = targetDir.resolve("TestClass.java"); Files.createDirectories(targetDir); Files.copy(testSrc, testTarget, StandardCopyOption.REPLACE_EXISTING); // Compile sources for corresponding test CompilerUtils.compile(targetDir, targetDir); // Prepare txt files Files.write(targetDir.resolve("hello.txt"), "Hello world".getBytes(), StandardOpenOption.CREATE); Files.write(targetDir.resolve("bye.txt"), "Bye world".getBytes(), StandardOpenOption.CREATE); // Create jar JarUtils.createJarFile(classes.resolve("foo.jar"), targetDir); }
/** * Moves the index folder found in <code>source</code> to <code>target</code> */ void upgrade(final Index index, final Path source, final Path target) throws IOException { boolean success = false; try { Files.move(source, target, StandardCopyOption.ATOMIC_MOVE); success = true; } catch (NoSuchFileException | FileNotFoundException exception) { // thrown when the source is non-existent because the folder was renamed // by another node (shared FS) after we checked if the target exists logger.error((Supplier<?>) () -> new ParameterizedMessage("multiple nodes trying to upgrade [{}] in parallel, retry " + "upgrading with single node", target), exception); throw exception; } finally { if (success) { logger.info("{} moved from [{}] to [{}]", index, source, target); logger.trace("{} syncing directory [{}]", index, target); IOUtils.fsync(target, true); } } }
private void validateAndClose(File tmpfile) throws IOException { if (ok && isMultiRelease) { try (JarFile jf = new JarFile(tmpfile)) { ok = Validator.validate(this, jf); if (!ok) { error(formatMsg("error.validator.jarfile.invalid", fname)); } } catch (IOException e) { error(formatMsg2("error.validator.jarfile.exception", fname, e.getMessage())); } } Path path = tmpfile.toPath(); try { if (ok) { if (fname != null) { Files.move(path, Paths.get(fname), StandardCopyOption.REPLACE_EXISTING); } else { Files.copy(path, new FileOutputStream(FileDescriptor.out)); } } } finally { Files.deleteIfExists(path); } }
private void initBundled() throws IOException { File tmpDir = new File(System.getProperty("java.io.tmpdir"), "solc"); tmpDir.mkdirs(); InputStream is = getClass().getResourceAsStream("/native/" + getOS() + "/solc/file.list"); Scanner scanner = new Scanner(is); while (scanner.hasNext()) { String s = scanner.next(); File targetFile = new File(tmpDir, s); InputStream fis = getClass().getResourceAsStream("/native/" + getOS() + "/solc/" + s); Files.copy(fis, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING); if (solc == null) { // first file in the list denotes executable solc = targetFile; solc.setExecutable(true); } targetFile.deleteOnExit(); } }
/** * Loads image from file system and sets it as avatar * @param f image which is needed to be set as avatar */ private void changeImage(File f){ if(f != null) { try{ Files.copy(f .toPath(), new File("data/avatars/"+p .getUsername()+"Avatar.png") .toPath(), StandardCopyOption.REPLACE_EXISTING ); p.setProfileImg(new Picture("file:data/avatars/"+p.getUsername()+"Avatar.png")); dc.save(); } catch (Exception e){ e.printStackTrace(); } } }
public void send_errors_report() throws MessagingException, IOException { String log_file = pManager.get_Log_File_Path(); Path logf = Paths.get(log_file); String attach = log_file + ".report"; Path report = Paths.get(attach); try { if (log_file != null && Files.exists(logf)) { if (transport == null || !transport.isConnected()) { senderConnect(); } Files.copy(logf, report, StandardCopyOption.REPLACE_EXISTING); String[] to = {pManager.getSupportEmail()}; sendMultipartMessage("Errors Report", to, "", attach); } } catch (Exception ex) { Files.deleteIfExists(report); throw ex; } Files.deleteIfExists(report); }
@GET @Path(DOWNLOAD_DOCUMENT_API) @Produces(MediaType.APPLICATION_OCTET_STREAM) public Response downloadDocument(@PathParam(PARAMETER_EVENT_ID) String eventId, @QueryParam(QUERY_PARAMETER_PATH) String path) { Response response = null; try { Document document = documentDao.findByPath(path); InputStream inputStream = document.getContentStream().getStream(); File file = new File(document.getName()); Files.copy(inputStream, file.toPath(), StandardCopyOption.REPLACE_EXISTING); response = Response.status(Response.Status.OK) .header(HEADER_CONTENT_DISPOSITION, "attachment; filename=" + file.getName()).entity(file).build(); } catch (IOException e) { logger.error(ERROR_PROBLEM_OCCURED_WHILE_DOWNLOADING_DOCUMENT, e); response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } return response; }
/** * Creates regular/modular jar files for TestClient and TestClassLoader. */ private static void setUp() throws Exception { // Generate regular jar files for TestClient and TestClassLoader JarUtils.createJarFile(CL_JAR, TEST_CLASSES, "cl/TestClassLoader.class"); JarUtils.createJarFile(C_JAR, TEST_CLASSES, "c/TestClient.class"); // Generate modular jar files for TestClient and TestClassLoader with // their corresponding ModuleDescriptor. Files.copy(CL_JAR, MCL_JAR, StandardCopyOption.REPLACE_EXISTING); updateModuleDescr(MCL_JAR, ModuleDescriptor.newModule("mcl") .exports("cl").requires("java.base").build()); Files.copy(C_JAR, MC_JAR, StandardCopyOption.REPLACE_EXISTING); updateModuleDescr(MC_JAR, ModuleDescriptor.newModule("mc") .exports("c").requires("java.base").requires("mcl").build()); Files.copy(C_JAR, AMC_JAR, StandardCopyOption.REPLACE_EXISTING); updateModuleDescr(AMC_JAR, ModuleDescriptor.newModule("mc") .exports("c").requires("java.base").requires("cl").build()); }
@Override public void update(Session session) { final String sessionId = ensureStringSessionId(session); final Path oldPath = sessionId2Path(sessionId); if (!Files.exists(oldPath)) { throw new UnknownSessionException(sessionId); } try { final Path newPath = Files.createTempFile(tmpDir, null, null); Files.write(newPath, serialize(session)); Files.move(newPath, oldPath, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { throw new SerializationException(e); } }
/** * @param byHistorySize 根据历史多少期推算下一期 */ public PredictNextNumberAndState(int byHistorySize) { this.byHistorySize = byHistorySize; StateParserStragegy stateParser = new StateParserStragegy(stateDefineStrategy, byHistorySize); try (InputStream inputStream = PredictNextNumberAndState.class.getClassLoader().getResourceAsStream("cp.txt")) { File tmpFile = File.createTempFile("cp-k3", "txt"); Files.copy(inputStream, tmpFile.toPath(), StandardCopyOption.REPLACE_EXISTING); List<String> lines = Files.readAllLines(tmpFile.toPath(), Charset.forName("utf-8")); List<int[]> numbers = new ArrayList<int[]>(); for (String line : lines) { int[] number = strToArrayAndSort(line.split("\t")[1]); numbers.add(number); } this.stateStructs = stateParser.parser(numbers); tmpFile.delete(); } catch (Exception e) { throw new RuntimeException("load data error!", e); } }
@Test(dataProvider = "badfactories", expectedExceptions = ServiceConfigurationError.class) public void testBadFactory(String testName, String ignore) throws Exception { Path mods = compileTest(TEST1_MODULE); // compile the bad factory Path source = BADFACTORIES_DIR.resolve(testName); Path output = Files.createTempDirectory(USER_DIR, "tmp"); boolean compiled = CompilerUtils.compile(source, output); assertTrue(compiled); // copy the compiled class into the module Path classFile = Paths.get("p", "ProviderFactory.class"); Files.copy(output.resolve(classFile), mods.resolve(TEST1_MODULE).resolve(classFile), StandardCopyOption.REPLACE_EXISTING); // load providers and instantiate each one loadProviders(mods, TEST1_MODULE).forEach(Provider::get); }
private void processSingleFile(Path inputFilePath) throws Exception { Path relative = inputPath.relativize(inputFilePath); Path toWrite = outputPath.resolve(relative); Files.createDirectories(toWrite.getParent()); String inputFilePathString = inputFilePath.toString().toLowerCase(Locale.US); if (Files.isDirectory(inputFilePath)) { Files.createDirectories(toWrite); } else if (inputFilePathString.endsWith(".xml")) { getLogger().debug("{} is probably an XML resource; replacing placeholders.", inputFilePath); Files.deleteIfExists(toWrite); processXmlResourceFile(inputFilePath, toWrite); } else { getLogger().debug("{} is probably not an XML resource; copying it verbatim.", inputFilePath); Files.deleteIfExists(toWrite); Files.copy(inputFilePath, toWrite, StandardCopyOption.COPY_ATTRIBUTES); } }
/** * @param args source and destination * @throws IOException if an I/O error occurs */ public static void main(String[] args) throws IOException { if (args.length != 2) { throw new IllegalArgumentException("Unexpected number of arguments for file copy"); } Path src = Paths.get(Utils.TEST_SRC, args[0]).toAbsolutePath(); Path dst = Paths.get(args[1]).toAbsolutePath(); if (src.toFile().exists()) { if (src.toFile().isDirectory()) { Files.walkFileTree(src, new CopyFileVisitor(src, dst)); } else { Path dstDir = dst.getParent(); if (!dstDir.toFile().exists()) { Files.createDirectories(dstDir); } Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING); } } else { throw new IOException("Can't find source " + src); } }
public static void main(String args[]) throws Exception { // bind to a random port ServerSocket ss = new ServerSocket(0); int port = ss.getLocalPort(); // Write the port number to the given file File partial = new File(args[0] + ".partial"); File portFile = new File(args[0]); try (FileOutputStream fos = new FileOutputStream(partial)) { fos.write( Integer.toString(port).getBytes("UTF-8") ); } Files.move(partial.toPath(), portFile.toPath(), StandardCopyOption.ATOMIC_MOVE); System.out.println("Debuggee bound to port: " + port); System.out.flush(); // wait for test harness to connect Socket s = ss.accept(); s.close(); ss.close(); System.out.println("Debuggee shutdown."); }
public static boolean CopyFilterFiles(List<File> files, Component parent) { int response = JOptionPane.showConfirmDialog(parent, "<html><body><p style='width: 200px;'>"+FilterLoader.getFilterWarning()+"</p></body></html>", "Warning", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); if(response != JOptionPane.OK_OPTION) return false; for(File f : files) { try { Files.copy(f.toPath(), new File(filterPath+"/"+f.getName()).toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { e.printStackTrace(); } } // GIFKR.restartApplication(); return true; }
private static void copyJobDependency(JobDependencyConfiguration jobDependencyConfiguration, Path workingDir) { final Path source = Paths.get(jobDependencyConfiguration.getSource()); final Path target = workingDir.resolve(Paths.get(jobDependencyConfiguration.getTarget())); try { if (source.toFile().isDirectory()) { log.debug("copy dependency: " + source.toString() + " -> " + target.toString()); FileUtils.copyDirectory(source.toFile(), target.toFile()); } else { log.debug("copy dependency: " + source.toString() + " -> " + target.toString()); Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING); } } catch (IOException ex) { log.error(source.toString() + ": cannot copy: " + ex.toString()); throw new RuntimeException(ex); } }
void run() throws Exception { Req r = reqs.get(req); acceptor.println("TEST"); acceptor.println(r.msg); String reply = acceptor.readData(); actual = Boolean.valueOf(reply); csize = csize(r.service); String label = String.format("%03d-client%d-%s%d-%s-%s", i, r.client, SERVICE, r.service, acceptor.debug(), actual); record(label, r); if (new File(cwd, dfl(r.service)).exists()) { Files.copy(Paths.get(cwd, dfl(r.service)), Paths.get(label), StandardCopyOption.COPY_ATTRIBUTES); } }
void renameTo(File f) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Moving file={0} to={1}", new Object[]{file, f}); } refList.remove(this); try { raf.close(); Path target = Files.move(file.toPath(), f.toPath(), StandardCopyOption.REPLACE_EXISTING); boolean renamed = f.toPath().equals(target); if (!renamed) { if (LOGGER.isLoggable(Level.INFO)) { throw new MIMEParsingException("File " + file.getAbsolutePath() + " was not moved to " + f.getAbsolutePath()); } } } catch(IOException ioe) { throw new MIMEParsingException(ioe); } }
@Override public void store(MultipartFile file) { String filename = StringUtils.cleanPath(file.getOriginalFilename()); try { if (file.isEmpty()) { throw new UploadException("Failed to store empty file " + filename); } if (filename.contains("..")) { // This is a security check throw new UploadException( "Cannot store file with relative path outside current directory " + filename); } Files.copy(file.getInputStream(), this.rootLocation.resolve(filename), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { throw new UploadException("Failed to store file " + filename, e); } }
public Configuration(String in, String out, Class<?> clazz) { this.properties = new Properties(); this.out = new File(Jrfl.FOLDER, out); this.formatter = Formatter.getInstance(); try { if(!exists()) Files.copy( clazz.getResourceAsStream(in), this.out.toPath(), StandardCopyOption.REPLACE_EXISTING ); properties.load(new FileInputStream(this.out)); } catch(IOException e) { e.printStackTrace(); } }
/** * Create the copy texture function. * * @param texturesFolder the textures folder. * @param overwriteTextures true if we can overwrite existing textures. * @return the new asset path. */ @FromAnyThread private @NotNull Function<String, String> makeCopyTextureFunction(@NotNull final Path texturesFolder, final boolean overwriteTextures) { return oldPath -> { final Path textureFile = Paths.get(oldPath); final Path fileName = textureFile.getFileName(); final Path newTextureFile = texturesFolder.resolve(fileName); final Path assetFile = notNull(getAssetFile(newTextureFile)); final String assetPath = toAssetPath(assetFile); if (Files.exists(newTextureFile) && !overwriteTextures) { return assetPath; } try { Files.copy(textureFile, newTextureFile, StandardCopyOption.REPLACE_EXISTING); } catch (final IOException e) { throw new RuntimeException(e); } return assetPath; }; }
private static void downloadFile(Path filePath, Path destinationDir) { final Path destinationFile = destinationDir.resolve(filePath.getFileName().toString()); try { // todo: retries Files.copy(filePath, destinationFile, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { throw new RuntimeException(e); } }
/** * Override files in processed modules by files in a given module <br> * In effect, it deletes a file from the resources of * the processed module if it is also present in the resources of the given module * * @param processedModules modules that have been processed so far * @param module new module to process */ private void overrideFiles(List<CarnotzetModule> processedModules, CarnotzetModule module) throws IOException { Path moduleExpandedJarPath = expandedJars.resolve(module.getName()); //going through all the files of the module in target/carnotzet folder find(moduleExpandedJarPath, FIND_MAX_DEPTH, isPotentialOverride()).forEach(overridingFilePath -> { Path relativePath = moduleExpandedJarPath.relativize(overridingFilePath); // ${overridenModule}/path/to/file Path overriddenModulePath = relativePath.subpath(0, 1).getFileName(); if (overriddenModulePath == null) { // should not happen return; } String overriddenModuleName = overriddenModulePath.toString(); // ${overridenModule} processedModules.stream() .filter(m -> m.getServiceId().equals(overriddenModuleName)) .findFirst() .ifPresent(overriddenModule -> { Path toOverrideFile = resolved.resolve(relativePath); // ${resolved}/${overrideModule}/path/to/file Path toOverrideParent = toOverrideFile.getParent(); if (toOverrideParent == null) { return; } try { if (!toOverrideParent.toFile().exists() && !toOverrideParent.toFile().mkdirs()) { throw new IOException("Unable to create directory " + toOverrideFile.getParent()); } Files.copy(overridingFilePath, toOverrideFile, StandardCopyOption.REPLACE_EXISTING); log.debug("Overridden [" + toOverrideFile.getFileName() + "] " + "in [" + overriddenModule.getServiceId() + "] " + "with file from [" + module.getName() + "]"); } catch (IOException e) { throw new UncheckedIOException(e); } }); }); }
private static String[] getLauncher() throws IOException { String platform = getPlatform(); if (platform == null) { return null; } String launcher = TEST_SRC + File.separator + platform + "-" + ARCH + File.separator + "launcher"; final FileSystem FS = FileSystems.getDefault(); Path launcherPath = FS.getPath(launcher); final boolean hasLauncher = Files.isRegularFile(launcherPath, LinkOption.NOFOLLOW_LINKS)&& Files.isReadable(launcherPath); if (!hasLauncher) { System.out.println("Launcher [" + launcher + "] does not exist. Skipping the test."); return null; } // It is impossible to store an executable file in the source control // We need to copy the launcher to the working directory // and set the executable flag Path localLauncherPath = FS.getPath(WORK_DIR, "launcher"); Files.copy(launcherPath, localLauncherPath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); if (!Files.isExecutable(localLauncherPath)) { Set<PosixFilePermission> perms = new HashSet<>( Files.getPosixFilePermissions( localLauncherPath, LinkOption.NOFOLLOW_LINKS ) ); perms.add(PosixFilePermission.OWNER_EXECUTE); Files.setPosixFilePermissions(localLauncherPath, perms); } return new String[] {launcher, localLauncherPath.toAbsolutePath().toString()}; }
private static Observable<Event> downloadResolvedDependency(final FileSystem fs, final ResolvedDependency resolvedDependency, final Path target) { Preconditions.checkNotNull(fs); Preconditions.checkNotNull(resolvedDependency); Preconditions.checkNotNull(target); final Observable<Event> downloadSourceCode = Single.fromCallable(() -> Files.exists(target)) .flatMapObservable(exists -> { if (exists) { return Observable.empty(); } return resolvedDependency.source.join( gitCommit -> CacheTasks.cloneAndCheckoutUsingCache(gitCommit, target), remoteArchive -> CacheTasks.downloadUsingCache(remoteArchive, target, StandardCopyOption.REPLACE_EXISTING)); }); final Path buckFilePath = fs.getPath(target.toString(), "BUCK"); final Observable<Event> downloadBuckFile = Files.exists(buckFilePath) ? Observable.empty() : resolvedDependency.buckResource .map(x -> CommonTasks.downloadRemoteFile(fs, x, buckFilePath)) .orElse(Observable.empty()); final Path buckarooDepsFilePath = fs.getPath(target.toString(), "BUCKAROO_DEPS"); final Observable<Event> writeBuckarooDeps = Single.fromCallable(() -> CommonTasks.generateBuckarooDeps(resolvedDependency.dependencies)) .flatMap(content -> CommonTasks.writeFile( content, buckarooDepsFilePath, true)) .cast(Event.class) .toObservable(); return Observable.concat( downloadSourceCode, downloadBuckFile, writeBuckarooDeps.cast(Event.class)); }
public static final void copyFileToDirectory(File file, File to) throws IOException { if (!to.exists()) { to.mkdirs(); } File n = new File(to.getAbsolutePath() + "/" + file.getName()); Files.copy(file.toPath(), n.toPath(), StandardCopyOption.REPLACE_EXISTING); }
private int copyCSVDebugFileAtDataViewerDebugFileLocation(String csvDebugFileLocation, String dataViewerFileAbsolutePath) { try { Files.copy(Paths.get(csvDebugFileLocation), Paths.get(dataViewerFileAbsolutePath), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { logger.error("unable to copy Debug csv file to data viewer file location",e); Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e); showDetailErrorMessage(Messages.UNABLE_TO_RELOAD_DEBUG_FILE+": Unable to copy Debug csv file to data viewer file location", status); return StatusConstants.ERROR; } return StatusConstants.SUCCESS; }
static Flags fromMoveOptions(CopyOption... options) { Flags flags = new Flags(); for (CopyOption option: options) { if (option == StandardCopyOption.ATOMIC_MOVE) { flags.atomicMove = true; continue; } if (option == StandardCopyOption.REPLACE_EXISTING) { flags.replaceExisting = true; continue; } if (option == LinkOption.NOFOLLOW_LINKS) { // ignore continue; } if (option == null) throw new NullPointerException(); throw new UnsupportedOperationException("Unsupported copy option"); } // a move requires that all attributes be copied but only fail if // the basic attributes cannot be copied flags.copyBasicAttributes = true; flags.copyPosixAttributes = true; flags.copyNonPosixAttributes = true; flags.failIfUnableToCopyBasic = true; return flags; }
public static void safeWrite(CompoundTag tag, File file) throws IOException { File tmpFile = new File(file.getAbsolutePath() + "_tmp"); if (tmpFile.exists()) { tmpFile.delete(); } write(tag, tmpFile); Files.move(tmpFile.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); }
public static void main(String[] args) throws IOException { Path testDir = Paths.get(System.getProperty("user.dir", ".")); Path bootDir = Paths.get(testDir.toString(), "boot"); Path classes = Paths.get(System.getProperty("test.classes", "build/classes")); Path thisClass = Paths.get(classes.toString(), AccessSystemLogger.class.getSimpleName()+".class"); if (Files.notExists(bootDir)) { Files.createDirectory(bootDir); } Path dest = Paths.get(bootDir.toString(), AccessSystemLogger.class.getSimpleName()+".class"); Files.copy(thisClass, dest, StandardCopyOption.REPLACE_EXISTING); }
public void savePNGHeatMap(File destination) { Path HeatMapPath = Paths.get(HeatMapUtils.getHeatMapPath()); Path dest = Paths.get(destination.getAbsolutePath()); try { Files.copy(HeatMapPath, dest, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { log.error("Exception", e); } }
public static void relocatePackageFile(PackageType pkg, File destination) throws IOException { String filename = getPackageFileName(pkg); File packageFile = packageFiles.get(filename); File target = new File(destination, filename + ".zip"); if (packageFile != null) { String tmpDir = System.getProperty("java.io.tmpdir"); if (packageFile.getAbsolutePath().contains(tmpDir)) { Files.move(packageFile.toPath(), target.toPath(), StandardCopyOption.ATOMIC_MOVE); packageFiles.put(filename, target); } else { Files.copy(packageFile.toPath(), target.toPath(), StandardCopyOption.ATOMIC_MOVE); } } }
@Override public Path move(final Path file, final Path renamed, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback) throws BackgroundException { try { Files.move(session.toPath(file), session.toPath(renamed), StandardCopyOption.REPLACE_EXISTING); // Copy attributes from original file return new Path(renamed.getParent(), renamed.getName(), renamed.getType(), new LocalAttributesFinderFeature(session).find(renamed)); } catch(IOException e) { throw new LocalExceptionMappingService().map("Cannot rename {0}", e, file); } }
@Before public void before() throws IOException { oldUserHome = System.getProperty(USER_HOME); // init temp folder testScriptDir = folder.newFolder("home", "xm-online", "config", "tenants", TENANT_KEY_VALUE.toUpperCase(), APP_NAME, "lep", "resource", "service"); // init system property File userHomeDir = Paths.get(folder.getRoot().toPath().toString(), "home").toFile(); System.setProperty(USER_HOME, userHomeDir.getAbsolutePath()); // copy script from classpath to file system tmp folder File scriptFile = Paths.get(testScriptDir.getAbsolutePath(), "Script$$before.groovy").toFile(); if (!scriptFile.createNewFile()) { throw new IllegalStateException("Can't create file: " + scriptFile.getAbsolutePath()); } InputStream scriptIn = resourceLoader.getResource(SCRIPT_CLASSPATH_URL).getInputStream(); Files.copy(scriptIn, scriptFile.toPath(), StandardCopyOption.REPLACE_EXISTING); scriptIn.close(); // init resource service Map<String, ResourceLoader> urlPrefixToResourceLoader = new HashMap<>(); urlPrefixToResourceLoader.put("file:", new FileSystemResourceLoader()); RouterResourceLoader routerResourceLoader = new RouterResourceLoader(urlPrefixToResourceLoader); resourceService = new XmLepResourceService(APP_NAME, FILE, routerResourceLoader); }