private static void migrateSession( File sessionFile, File sessionsDirectory, long canonicalAddress) { File canonicalSessionFile = new File(sessionsDirectory.getAbsolutePath() + File.separatorChar + canonicalAddress); sessionFile.renameTo(canonicalSessionFile); Log.w( "CanonicalSessionMigrator", "Moving: " + sessionFile.toString() + " to " + canonicalSessionFile.toString()); File canonicalSessionFileLocal = new File( sessionsDirectory.getAbsolutePath() + File.separatorChar + canonicalAddress + "-local"); File localFile = new File(sessionFile.getAbsolutePath() + "-local"); if (localFile.exists()) localFile.renameTo(canonicalSessionFileLocal); Log.w("CanonicalSessionMigrator", "Moving " + localFile + " to " + canonicalSessionFileLocal); File canonicalSessionFileRemote = new File( sessionsDirectory.getAbsolutePath() + File.separatorChar + canonicalAddress + "-remote"); File remoteFile = new File(sessionFile.getAbsolutePath() + "-remote"); if (remoteFile.exists()) remoteFile.renameTo(canonicalSessionFileRemote); Log.w("CanonicalSessionMigrator", "Moving " + remoteFile + " to " + canonicalSessionFileRemote); }
public static boolean renameTo(File orig, File dest) { // Try an atomic rename // Shall we prevent symlink-race-conditions here ? if (orig.equals(dest)) throw new IllegalArgumentException("Huh? the two file descriptors are the same!"); if (!orig.exists()) { throw new IllegalArgumentException("Original doesn't exist!"); } if (!orig.renameTo(dest)) { // Not supported on some systems (Windows) if (!dest.delete()) { if (dest.exists()) { Logger.error("FileUtil", "Could not delete " + dest + " - check permissions"); System.err.println("Could not delete " + dest + " - check permissions"); } } if (!orig.renameTo(dest)) { String err = "Could not rename " + orig + " to " + dest + (dest.exists() ? " (target exists)" : "") + (orig.exists() ? " (source exists)" : "") + " - check permissions"; Logger.error(FileUtil.class, err); System.err.println(err); return false; } } return true; }
public synchronized void save() throws IOException { OutputStream os = null; try { File newSaved = new File(saved.getParentFile(), saved.getName() + ".new"); File backupSaved = new File(saved.getParentFile(), saved.getName() + ".bak"); os = new FileOutputStream(newSaved); marshaller.marshall(os, session); os.close(); os = null; if (backupSaved.exists()) { if (!backupSaved.delete()) { throw new IOException("could not remove backup " + backupSaved.getAbsolutePath()); } } if (saved.exists()) { if (!saved.renameTo(backupSaved)) { throw new IOException("could not backup " + saved.getAbsolutePath()); } } if (!newSaved.renameTo(saved)) { backupSaved.renameTo(saved); throw new IOException("could not rename " + saved.getAbsolutePath()); } } finally { if (os != null) os.close(); } }
public FileOutputStream startWrite() throws IOException { // Rename the current file so it may be used as a backup during the next read if (mBaseName.exists()) { if (!mBaseName.renameTo(mBackupName)) { mBackupName.delete(); if (!mBaseName.renameTo(mBackupName)) { Log.w( "AtomicFile", "Couldn't rename file " + mBaseName + " to backup file " + mBackupName); } } } FileOutputStream str = null; try { str = new FileOutputStream(mBaseName); } catch (FileNotFoundException e) { File parent = mBaseName.getParentFile(); if (!parent.mkdir()) { throw new IOException("Couldn't create directory " + mBaseName); } FileUtils.setPermissions( parent.getPath(), FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IXOTH, -1, -1); try { str = new FileOutputStream(mBaseName); } catch (FileNotFoundException e2) { throw new IOException("Couldn't create " + mBaseName); } } return str; }
@Test public void testRename() throws IOException { File bla = new MockFile("bla"); File doh = new MockFile("doh"); Assert.assertFalse(bla.exists()); Assert.assertFalse(doh.exists()); boolean created = bla.createNewFile(); Assert.assertTrue(created); Assert.assertTrue(bla.exists()); Assert.assertFalse(doh.exists()); boolean renamed = bla.renameTo(doh); Assert.assertTrue(renamed); Assert.assertFalse(bla.exists()); Assert.assertTrue(doh.exists()); File inAnotherFolder = new MockFile("foo/hei/hello.tmp"); Assert.assertFalse(inAnotherFolder.exists()); renamed = doh.renameTo(inAnotherFolder); Assert.assertFalse(renamed); Assert.assertFalse(inAnotherFolder.exists()); Assert.assertTrue(doh.exists()); File de = new MockFile("deeee"); File blup = new MockFile("blup"); Assert.assertFalse(de.exists()); Assert.assertFalse(blup.exists()); renamed = de.renameTo(blup); Assert.assertFalse(renamed); Assert.assertFalse(de.exists()); Assert.assertFalse(blup.exists()); }
/** Saves the given World Info with the given NBTTagCompound as the Player. */ public void saveWorldInfoWithPlayer(WorldInfo par1WorldInfo, NBTTagCompound par2NBTTagCompound) { NBTTagCompound var3 = par1WorldInfo.cloneNBTCompound(par2NBTTagCompound); NBTTagCompound var4 = new NBTTagCompound(); var4.setTag("Data", var3); FMLCommonHandler.instance().handleWorldDataSave(this, par1WorldInfo, var4); try { File var5 = new File(this.worldDirectory, "level.dat_new"); File var6 = new File(this.worldDirectory, "level.dat_old"); File var7 = new File(this.worldDirectory, "level.dat"); CompressedStreamTools.writeCompressed(var4, new FileOutputStream(var5)); if (var6.exists()) { var6.delete(); } var7.renameTo(var6); if (var7.exists()) { var7.delete(); } var5.renameTo(var7); if (var5.exists()) { var5.delete(); } } catch (Exception var8) { var8.printStackTrace(); } }
public static void start(String fName) { // fileName must be the complete path and filename to the file // If fileName exists - rename to back and start new log, // if back exists delete it fileName = fName; // make usre that the directory exists and that the file is rw try { File f = new File(fileName); if (f.exists()) { File fBak = new File(fileName + ".bak"); if (fBak.exists()) { if (fBak.delete()) { f.renameTo(fBak); } else { f.delete(); } } else { f.renameTo(fBak); } } fStream = new DataOutputStream(new FileOutputStream(f)); } catch (IOException e) { System.out.println("LogFile:" + e); System.exit(1); } started = true; writeHeader(); }
/** * Move config file, keys, and index files to "official" folder * * <p>Intended to bring the file locations in older installs in line with newer versions. */ private void moveConfigFiles() { FilenameFilter idxFilter = new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".idx.gz"); } }; if (new File(getApplicationInfo().dataDir, PUBLIC_KEY_FILE).exists()) { try { File publicKey = new File(getApplicationInfo().dataDir, PUBLIC_KEY_FILE); publicKey.renameTo(new File(getFilesDir(), PUBLIC_KEY_FILE)); File privateKey = new File(getApplicationInfo().dataDir, PRIVATE_KEY_FILE); privateKey.renameTo(new File(getFilesDir(), PRIVATE_KEY_FILE)); File config = new File(getApplicationInfo().dataDir, CONFIG_FILE); config.renameTo(new File(getFilesDir(), CONFIG_FILE)); File oldStorageDir = new File(getApplicationInfo().dataDir); File[] files = oldStorageDir.listFiles(idxFilter); for (File file : files) { if (file.isFile()) { file.renameTo(new File(getFilesDir(), file.getName())); } } } catch (Exception e) { Log.e(TAG, "Failed to move config files", e); } } }
/** * Persists the list of {@link AwaitedJob} to file * * @throws FileNotFoundException */ protected synchronized void saveAwaitedJobsToFile() throws FileNotFoundException { File statusFileBK = new File(statusFilename + ".BAK"); if (statusFileBK.isFile()) { statusFileBK.delete(); } if (statusFile != null && statusFile.isFile()) statusFile.renameTo(statusFileBK); try { statusFile = new File(statusFilename); XMLEncoder encoder = new XMLEncoder(new FileOutputStream(statusFile)); for (AwaitedJob aj : awaitedJobs.values()) { encoder.writeObject(aj); } encoder.flush(); encoder.close(); } catch (Throwable t) { logger.error( "Could not persist the list of awaited jobs. Some jobs output data might not be transfered after application restart ", t); // recover the status file from the backup file statusFile.delete(); statusFileBK.renameTo(statusFile); } }
private void caregaArquivoDeDefinicoes(String filename, JTextArea textArea, String desc) { File file = new File(filename); File fileBackup = new File(filename + ".bkp"); if (file.exists()) { file.renameTo(fileBackup); try { BufferedWriter writter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset)); BufferedReader reader = new BufferedReader(new StringReader(textArea.getText())); String linha = null; while ((linha = reader.readLine()) != null) { writter.write(linha + System.getProperty("line.separator")); } writter.close(); } catch (IOException e) { warn(e); fileBackup.renameTo(file); textArea.setText(carregaText(filename)); } } else { error( "O arquivo de configurações de " + desc + " não foi encontrado. Crie o arquivo com o nome " + filename); } }
@Override public boolean rename(Path src, Path dst) throws IOException { // Attempt rename using Java API. File srcFile = pathToFile(src); File dstFile = pathToFile(dst); if (srcFile.renameTo(dstFile)) { return true; } // Enforce POSIX rename behavior that a source directory replaces an existing // destination if the destination is an empty directory. On most platforms, // this is already handled by the Java API call above. Some platforms // (notably Windows) do not provide this behavior, so the Java API call above // fails. Delete destination and attempt rename again. if (this.exists(dst)) { FileStatus sdst = this.getFileStatus(dst); if (sdst.isDirectory() && dstFile.list().length == 0) { if (LOG.isDebugEnabled()) { LOG.debug("Deleting empty destination and renaming " + src + " to " + dst); } if (this.delete(dst, false) && srcFile.renameTo(dstFile)) { return true; } } } // The fallback behavior accomplishes the rename by a full copy. if (LOG.isDebugEnabled()) { LOG.debug("Falling through to a copy of " + src + " to " + dst); } return FileUtil.copy(this, src, this, dst, true, getConf()); }
@Test public void test() throws Exception { // To ensure our custom plugin is NOT included in the log4j plugin metadata file, // we make sure the class does not exist until after the build is finished. // So we don't create the custom plugin class until this test is run. final File orig = new File("target/test-classes/customplugin/FixedStringLayout.java.source"); final File f = new File(orig.getParentFile(), "FixedStringLayout.java"); assertTrue("renamed source file OK", orig.renameTo(f)); compile(f); assertTrue("reverted source file OK", f.renameTo(orig)); // load the compiled class Class.forName("customplugin.FixedStringLayout"); // now that the custom plugin class exists, we load the config // with the packages element pointing to our custom plugin ctx = Configurator.initialize("Test1", "customplugin/log4j2-741.xml"); config = ctx.getConfiguration(); listAppender = (ListAppender) config.getAppender("List"); final Logger logger = LogManager.getLogger(PluginManagerPackagesTest.class); logger.info("this message is ignored"); final List<String> messages = listAppender.getMessages(); assertEquals(messages.toString(), 1, messages.size()); assertEquals("abc123XYZ", messages.get(0)); }
@Override public void a(WorldInfo worldinfo) { NBTTagCompound nbttagcompound = worldinfo.a(); NBTTagCompound nbttagcompound1 = new NBTTagCompound(); nbttagcompound1.a("Data", (NBTBase) nbttagcompound); try { File file1 = new File(this.worldDir, "level.dat_new"); File file2 = new File(this.worldDir, "level.dat_old"); File file3 = new File(this.worldDir, "level.dat"); CompressedStreamTools.a(nbttagcompound1, (OutputStream) (new FileOutputStream(file1))); if (file2.exists()) { file2.delete(); } file3.renameTo(file2); if (file3.exists()) { file3.delete(); } file1.renameTo(file3); if (file1.exists()) { file1.delete(); } } catch (Exception exception) { exception.printStackTrace(); } }
private static boolean rename(File src, File dst) { if (src.renameTo(dst)) return true; File dir = dst.getParentFile(); if ((dir.exists() || !dir.mkdirs()) && !dir.isDirectory()) return false; return src.renameTo(dst); }
public static boolean renameTo(File file1, File file2) throws IOException { if (!file1.exists()) { throw new IOException(file1.getAbsolutePath() + " does not exist"); } /// That's right, I can't just rename the file, i need to move and delete if (isWindows()) { File temp = new File(file2.getAbsoluteFile() + "." + new Random().nextInt() + ".backup"); if (temp.exists()) { temp.delete(); } if (file2.exists()) { file2.renameTo(temp); file2.delete(); } if (!file1.renameTo(file2)) { throw new IOException( temp.getAbsolutePath() + " could not be renamed to " + file2.getAbsolutePath()); } else { temp.delete(); } } else { if (!file1.renameTo(file2)) { throw new IOException( file1.getAbsolutePath() + " could not be renamed to " + file2.getAbsolutePath()); } } return true; }
private static void renameDownloadedFiles(String directory) { File dirFile = new File(directory); String[] members = dirFile.list(); String memberName; for (int i = 0; i < members.length; i++) { memberName = members[i]; if (memberName.endsWith("~~") && !memberName.endsWith("~~~")) { String realName = memberName.substring(0, memberName.length() - 2); File realFile = new File(dirFile, realName); File newFile = new File(dirFile, memberName); if (filesAreEqual(realFile, newFile)) { writeLog("skipping " + directory + "/" + realName); realFile.setLastModified(newFile.lastModified()); } else { writeLog("installing " + directory + "/" + realName); boolean result = realFile.renameTo(new File(directory, realName + "~")); if (!result) { writeLog( "(OK) failed renaming " + directory + "/" + realName + " to " + realName + "~"); } result = newFile.renameTo(realFile); if (!result) { errorCount++; writeLog("failed renaming " + directory + "/" + memberName + " to " + realName); } } } } for (int i = 0; i < members.length; i++) { memberName = members[i]; if ((new File(directory, memberName)).isDirectory()) { renameDownloadedFiles(directory + '/' + memberName); } } }
/** Save the contents of the FS image */ void saveFSImage(File fullimage, File edits) throws IOException { File curFile = new File(fullimage, FS_IMAGE); File newFile = new File(fullimage, NEW_FS_IMAGE); File oldFile = new File(fullimage, OLD_FS_IMAGE); // // Write out data // DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(newFile))); try { out.writeInt(rootDir.numItemsInTree() - 1); rootDir.saveImage("", out); } finally { out.close(); } // // Atomic move sequence // // 1. Move cur to old curFile.renameTo(oldFile); // 2. Move new to cur newFile.renameTo(curFile); // 3. Remove pending-edits file (it's been integrated with newFile) edits.delete(); // 4. Delete old oldFile.delete(); }
synchronized void migrateData(DataStore targetStore) { ForceLoadAllClaims(this); targetStore.ClearInventoryOnJoinPlayers = ClearInventoryOnJoinPlayers; // migrate claims for (Claim c : this.claims) { GriefPrevention.AddLogEntry("Migrating Claim #" + c.getID()); targetStore.addClaim(c); } // migrate groups Iterator<String> groupNamesEnumerator = this.permissionToBonusBlocksMap.keySet().iterator(); while (groupNamesEnumerator.hasNext()) { String groupName = groupNamesEnumerator.next(); targetStore.saveGroupBonusBlocks(groupName, this.permissionToBonusBlocksMap.get(groupName)); } // migrate players for (PlayerData pdata : getAllPlayerData()) { targetStore.playerNameToPlayerDataMap.put(pdata.playerName, pdata); targetStore.savePlayerData(pdata.playerName, pdata); } // migrate next claim ID if (this.nextClaimID > targetStore.nextClaimID) { targetStore.setNextClaimID(this.nextClaimID); } // rename player and claim data folders so the migration won't run again int i = 0; File claimsBackupFolder; File playersBackupFolder; do { String claimsFolderBackupPath = claimDataFolderPath; if (i > 0) claimsFolderBackupPath += String.valueOf(i); claimsBackupFolder = new File(claimsFolderBackupPath); String playersFolderBackupPath = playerDataFolderPath; if (i > 0) playersFolderBackupPath += String.valueOf(i); playersBackupFolder = new File(playersFolderBackupPath); i++; } while (claimsBackupFolder.exists() || playersBackupFolder.exists()); File claimsFolder = new File(claimDataFolderPath); File playersFolder = new File(playerDataFolderPath); claimsFolder.renameTo(claimsBackupFolder); playersFolder.renameTo(playersBackupFolder); GriefPrevention.AddLogEntry( "Backed your file system data up to " + claimsBackupFolder.getName() + " and " + playersBackupFolder.getName() + "."); GriefPrevention.AddLogEntry( "If your migration encountered any problems, you can restore those data with a quick copy/paste."); GriefPrevention.AddLogEntry( "When you're satisfied that all your data have been safely migrated, consider deleting those folders."); }
/** Saves the passed in world info. */ public void saveWorldInfo(WorldInfo par1WorldInfo) { NBTTagCompound var2 = par1WorldInfo.getNBTTagCompound(); NBTTagCompound var3 = new NBTTagCompound(); var3.setTag("Data", var2); FMLCommonHandler.instance().handleWorldDataSave(this, par1WorldInfo, var3); try { File var4 = new File(this.worldDirectory, "level.dat_new"); File var5 = new File(this.worldDirectory, "level.dat_old"); File var6 = new File(this.worldDirectory, "level.dat"); CompressedStreamTools.writeCompressed(var3, new FileOutputStream(var4)); if (var5.exists()) { var5.delete(); } var6.renameTo(var5); if (var6.exists()) { var6.delete(); } var4.renameTo(var6); if (var4.exists()) { var4.delete(); } } catch (Exception var7) { var7.printStackTrace(); } }
/** * Helper for unzipping downloaded zips * * @param environment * @throws IOException */ private void unzip(Environment environment, ZipFile zipFile, File targetFile, String targetPath) throws IOException { String baseDirSuffix = null; try { Enumeration<? extends ZipEntry> zipEntries = zipFile.entries(); if (!zipEntries.hasMoreElements()) { logger.error("the zip archive has no entries"); } ZipEntry firstEntry = zipEntries.nextElement(); if (firstEntry.isDirectory()) { baseDirSuffix = firstEntry.getName(); } else { zipEntries = zipFile.entries(); } while (zipEntries.hasMoreElements()) { ZipEntry zipEntry = zipEntries.nextElement(); if (zipEntry.isDirectory()) { continue; } String zipEntryName = zipEntry.getName(); zipEntryName = zipEntryName.replace('\\', '/'); if (baseDirSuffix != null && zipEntryName.startsWith(baseDirSuffix)) { zipEntryName = zipEntryName.substring(baseDirSuffix.length()); } File target = new File(targetFile, zipEntryName); FileSystemUtils.mkdirs(target.getParentFile()); Streams.copy(zipFile.getInputStream(zipEntry), new FileOutputStream(target)); } } catch (IOException e) { logger.error( "failed to extract zip [" + zipFile.getName() + "]: " + ExceptionsHelper.detailedMessage(e)); return; } finally { try { zipFile.close(); } catch (IOException e) { // ignore } } File binFile = new File(targetFile, "bin"); if (binFile.exists() && binFile.isDirectory()) { File toLocation = new File(new File(environment.homeFile(), "bin"), targetPath); logger.info("found bin, moving to " + toLocation.getAbsolutePath()); FileSystemUtils.deleteRecursively(toLocation); binFile.renameTo(toLocation); } if (!new File(targetFile, "_site").exists()) { if (!FileSystemUtils.hasExtensions(targetFile, ".class", ".jar")) { logger.info("identified as a _site plugin, moving to _site structure ..."); File site = new File(targetFile, "_site"); File tmpLocation = new File(environment.pluginsFile(), targetPath + ".tmp"); targetFile.renameTo(tmpLocation); FileSystemUtils.mkdirs(targetFile); tmpLocation.renameTo(site); } } }
public void write() throws IOException, SAXException, TransformerConfigurationException { final File out = prefix(UpdaterUtil.XML_COMPRESSED); final File tmp = prefix(UpdaterUtil.XML_COMPRESSED + ".tmp"); new XMLFileWriter(this).write(new GZIPOutputStream(new FileOutputStream(tmp)), true); if (out.exists() && !out.delete()) out.renameTo(prefix(UpdaterUtil.XML_COMPRESSED + ".backup")); tmp.renameTo(out); setUpdateSitesChanged(false); }
/** * Moves the chunk group file to the folder for deleted factions. * * @param groupId */ public static void deleteChunkGroup(String groupId) { // Create folders: File deletedDirectory = new File(WriteReadType.SETTLEMENT_DELETED.getDirectory()); File factionDirectory = new File(WriteReadType.SETTLEMENT_NORMAL.getDirectory()); File deletedFile = new File( WriteReadType.SETTLEMENT_DELETED.getDirectory() + groupId + IOConstants.FILE_EXTENTENSION); File factionFile = new File( WriteReadType.SETTLEMENT_NORMAL.getDirectory() + groupId + IOConstants.FILE_EXTENTENSION); if (!deletedDirectory.exists()) { deletedDirectory.mkdirs(); Saga.info("Creating " + deletedDirectory + " directory."); } if (!factionDirectory.exists()) { factionDirectory.mkdirs(); Saga.info("Creating " + factionDirectory + " directory."); } // Check if exists. if (!factionFile.exists()) { Saga.severe("Cant move " + factionFile + ", because it doesent exist."); } // Rename if target exists: for (int i = 1; i < 1000; i++) { if (deletedFile.exists()) { deletedFile.renameTo( new File( WriteReadType.SETTLEMENT_DELETED.getDirectory() + groupId + "(" + i + ")" + IOConstants.FILE_EXTENTENSION)); } else { break; } } // Move file to deleted folder: boolean success = factionFile.renameTo(deletedFile); // Notify on failure: if (success) { Saga.info("Moved " + factionFile + " file to deleted factions folder."); } else { Saga.severe("Failed to move " + factionFile + " to deleted factions folder."); } }
private static PackageBufINf upLoadConfigFile( ManagerConnection c, ByteBuffer buffer, byte packetId, String fileName, String content) { logger.info("Upload Daas Config file " + fileName + " ,content:" + content); String tempFileName = System.currentTimeMillis() + "_" + fileName; File tempFile = new File(SystemConfig.getHomePath(), "conf" + File.separator + tempFileName); BufferedOutputStream buff = null; boolean suc = false; try { byte[] fileData = content.getBytes("UTF-8"); if (fileName.endsWith(".xml")) { checkXMLFile(fileName, fileData); } buff = new BufferedOutputStream(new FileOutputStream(tempFile)); buff.write(fileData); buff.flush(); } catch (Exception e) { logger.warn("write file err " + e); e.printStackTrace(); return showInfo(c, buffer, packetId, "write file err " + e); } finally { if (buff != null) { try { buff.close(); suc = true; } catch (IOException e) { logger.warn("save config file err " + e); } } } if (suc) { // if succcess File oldFile = new File(SystemConfig.getHomePath(), "conf" + File.separator + fileName); if (oldFile.exists()) { File backUP = new File( SystemConfig.getHomePath(), "conf" + File.separator + fileName + "_" + System.currentTimeMillis() + "_auto"); if (!oldFile.renameTo(backUP)) { String msg = "rename old file failed"; logger.warn(msg + " for upload file " + oldFile.getAbsolutePath()); return showInfo(c, buffer, packetId, msg); } } File dest = new File(SystemConfig.getHomePath(), "conf" + File.separator + fileName); if (!tempFile.renameTo(dest)) { String msg = "rename file failed"; logger.warn(msg + " for upload file " + tempFile.getAbsolutePath()); return showInfo(c, buffer, packetId, msg); } return showInfo(c, buffer, packetId, "SUCCESS SAVED FILE:" + fileName); } else { return showInfo(c, buffer, packetId, "UPLOAD ERROR OCCURD:" + fileName); } }
public static Result create_save() { Form<CustomerForm> filledForm = customerForm.bindFromRequest(); if (filledForm.hasErrors()) { System.out.println("in error"); return badRequest(create.render(filledForm)); } CustomerForm customerForm = filledForm.get(); if (customerForm == null) { System.out.println("in form"); return badRequest(create.render(filledForm)); } Customer customer = new Customer(); formToModel(customer, customerForm); MultipartFormData body = request().body().asMultipartFormData(); FilePart picture1 = body.getFile("signatureOne"); FilePart picture2 = body.getFile("signatureTwo"); if (picture1 != null && picture2 != null) { File file1 = picture1.getFile(); File file2 = picture2.getFile(); String path = "public/signatureimages/" + customer.accountNumber; File f = new File(path); f.mkdir(); file1.renameTo(new File(path, customer.signatureOne)); file2.renameTo(new File(path, customer.signatureTwo)); System.out.println("File uploaded successfully..."); } else { filledForm.reject("file", "Please select the image to uplaod"); } String inputFile = "public/signatureimages/" + customer.accountNumber + "/" + customer.signatureOne; String smoothfilename = "public/signatureimages/" + customer.accountNumber + "/signatureOne_smooth.jpg"; String binaryfilename = "public/signatureimages/" + customer.accountNumber + "/signatureOne_binary.jpg"; String sizeNormalizeFileName = "public/signatureimages/" + customer.accountNumber + "/signatureOne_normalize.jpg"; SigImgProcessingController.smoothing(inputFile, smoothfilename); SigImgProcessingController.binarization(smoothfilename, binaryfilename); SigImgProcessingController.sizeNormalization(binaryfilename, sizeNormalizeFileName); float[] sig1 = SigImgProcessingController.calculateAngles(sizeNormalizeFileName); StringBuffer angels = new StringBuffer(); for (int i = 0; i < sig1.length; i++) { angels.append(sig1[i] + "|"); } System.out.println("Angles: " + angels); customer.signOneAngles = angels.toString(); customer.save(); return redirect(controllers.routes.CustomerController.index()); }
public void testUpdate() throws IOException, InvalidRangeException, InterruptedException { String dir = TestAll.cdmUnitTestDir + "agg/updating"; File dirFile = new File(dir); assert dirFile != null; assert dirFile.exists(); assert dirFile.isDirectory(); // make sure that the extra file is not in the agg for (File f : dirFile.listFiles()) { if (f.getName().equals("extra.nc")) { if (!f.renameTo(new File(dirFile, "extra.wait"))) { System.out.printf("Rename fails on %s.extra.nc %n", dirFile); } break; } } String ncml = "<?xml version='1.0' encoding='UTF-8'?>\n" + "<netcdf xmlns='http://www.unidata.ucar.edu/namespaces/netcdf/ncml-2.2'>\n" + " <aggregation dimName='time' type='joinExisting' recheckEvery='1 nsec'>\n" + " <scan location='" + dir + "' suffix='*.nc' />\n" + " <variable name='depth'>\n" + " <attribute name='coordinates' value='lon lat'/>\n" + " </variable>\n" + " <variable name='wvh'>\n" + " <attribute name='coordinates' value='lon lat'/>\n" + " </variable>\n" + " </aggregation>\n" + " <attribute name='Conventions' type='String' value='CF-1.0'/>\n" + "</netcdf>"; String location = dir + "agg/updating.ncml"; System.out.println(" TestOffAggExistingTimeUnitsChange.testNarrGrib=\n" + ncml); NetcdfFile ncfile = NcMLReader.readNcML(new StringReader(ncml), location, null); check(ncfile, 12); // make sure that the extra file is in the agg for (File f : dirFile.listFiles()) { if (f.getName().equals("extra.wait")) { if (!f.renameTo(new File(dirFile, "extra.nc"))) System.out.println(" rename fails on " + f.getPath()); break; } } ncfile.sync(); check(ncfile, 18); ncfile.close(); }
public void resultsFileName( String tool, String benchmarkVersion, String times, String toolVersion) { String name = "results/Benchmark_" + benchmarkVersion + "-" + tool + "-v" + toolVersion + "-" + times + ".xml"; File file = null; File targetDir = new File("results/"); if (!targetDir.exists()) { targetDir.mkdir(); } // System.out.println("inside results file: "+tool); switch (tool) { case "findbugs": case "findsecbugs": file = new File(FINDBUGS_FILE); if (file.exists()) { file.renameTo(new File(name)); } break; case "pmd": file = new File(PMD_FILE); if (file.exists()) { file.renameTo(new File(name)); } else { System.out.println("PMD results file not found."); } break; case "sonar": file = new File(SONAR_FILE); if (file.exists()) { file.renameTo(new File(name)); } break; case "crawler": file = new File( "results/" + getFindFile("results", CONTRAST_FILE + benchmarkVersion + "-Contrast")); if (file.exists()) { file.renameTo( new File("results/" + file.getName().replace(".zip", "-" + times + ".zip"))); } break; } }
private void fixFilePaths() { File oldFlatfilePath = new File(mainDirectory + "FlatFileStuff" + File.separator); File oldModPath = new File(mainDirectory + "ModConfigs" + File.separator); if (oldFlatfilePath.exists()) { oldFlatfilePath.renameTo(new File(flatFileDirectory)); } if (oldModPath.exists()) { oldModPath.renameTo(new File(modDirectory)); } }
private void copy(File source, File target, boolean replaceFragments, boolean web) throws IOException { if (source.isDirectory()) { target.mkdirs(); for (File f : source.listFiles()) { copy(f, new File(target, f.getName()), replaceFragments, web); } } else { String name = source.getName(); if (name.endsWith("onePage.html") || name.startsWith("fragments")) { return; } if (web) { if (name.endsWith("main.html") || name.endsWith("main_ja.html")) { return; } } else { if (name.endsWith("mainWeb.html") || name.endsWith("mainWeb_ja.html")) { return; } } FileInputStream in = new FileInputStream(source); byte[] bytes = IOUtils.readBytesAndClose(in, 0); if (name.endsWith(".html")) { String page = new String(bytes, "UTF-8"); if (web) { page = StringUtils.replaceAll(page, ANALYTICS_TAG, ANALYTICS_SCRIPT); } if (replaceFragments) { page = replaceFragments(name, page); page = StringUtils.replaceAll(page, "<a href=\"frame", "<a href=\"main"); page = StringUtils.replaceAll(page, "html/frame.html", "html/main.html"); } if (web) { page = StringUtils.replaceAll(page, TRANSLATE_START, ""); page = StringUtils.replaceAll(page, TRANSLATE_END, ""); page = StringUtils.replaceAll(page, "<pre>", "<pre class=\"notranslate\">"); page = StringUtils.replaceAll(page, "<code>", "<code class=\"notranslate\">"); } bytes = page.getBytes("UTF-8"); } FileOutputStream out = new FileOutputStream(target); out.write(bytes); out.close(); if (web) { if (name.endsWith("mainWeb.html")) { target.renameTo(new File(target.getParentFile(), "main.html")); } else if (name.endsWith("mainWeb_ja.html")) { target.renameTo(new File(target.getParentFile(), "main_ja.html")); } } } }
private File addBlock(Block b, File src, boolean createOk, boolean resetIdx) throws IOException { if (numBlocks < maxBlocksPerDir) { File dest = new File(dir, b.getBlockName()); File metaData = getMetaFile(src, b); File newmeta = getMetaFile(dest, b); if (!metaData.renameTo(newmeta) || !src.renameTo(dest)) { throw new IOException( "could not move files for " + b + " from tmp to " + dest.getAbsolutePath()); } if (DataNode.LOG.isDebugEnabled()) { DataNode.LOG.debug("addBlock: Moved " + metaData + " to " + newmeta); DataNode.LOG.debug("addBlock: Moved " + src + " to " + dest); } numBlocks += 1; return dest; } if (lastChildIdx < 0 && resetIdx) { // reset so that all children will be checked lastChildIdx = random.nextInt(children.length); } if (lastChildIdx >= 0 && children != null) { // Check if any child-tree has room for a block. for (int i = 0; i < children.length; i++) { int idx = (lastChildIdx + i) % children.length; File file = children[idx].addBlock(b, src, false, resetIdx); if (file != null) { lastChildIdx = idx; return file; } } lastChildIdx = -1; } if (!createOk) { return null; } if (children == null || children.length == 0) { children = new FSDir[maxBlocksPerDir]; for (int idx = 0; idx < maxBlocksPerDir; idx++) { children[idx] = new FSDir(new File(dir, DataStorage.BLOCK_SUBDIR_PREFIX + idx)); } } // now pick a child randomly for creating a new set of subdirs. lastChildIdx = random.nextInt(children.length); return children[lastChildIdx].addBlock(b, src, true, false); }
/** * Rename this quest. * * @param newName the new name to set */ public void rename(final String newName) { File newpath = new File(ForgeConstants.QUEST_SAVE_DIR, newName + ".dat"); File oldpath = new File(ForgeConstants.QUEST_SAVE_DIR, this.name + ".dat"); oldpath.renameTo(newpath); newpath = new File(ForgeConstants.QUEST_SAVE_DIR, newName + ".dat.bak"); oldpath = new File(ForgeConstants.QUEST_SAVE_DIR, this.name + ".dat.bak"); oldpath.renameTo(newpath); this.name = newName; QuestDataIO.saveData(this); }