@Override public void injectCorruptReplica(ExtendedBlock block) throws IOException { Preconditions.checkState(!dataset.contains(block), "Block " + block + " already exists on dataset."); try (FsVolumeReferences volRef = dataset.getFsVolumeReferences()) { FsVolumeImpl volume = (FsVolumeImpl) volRef.get(0); FinalizedReplica finalized = new FinalizedReplica( block.getLocalBlock(), volume, volume.getFinalizedDir(block.getBlockPoolId())); File blockFile = finalized.getBlockFile(); if (!blockFile.createNewFile()) { throw new FileExistsException( "Block file " + blockFile + " already exists."); } File metaFile = FsDatasetUtil.getMetaFile(blockFile, 1000); if (!metaFile.createNewFile()) { throw new FileExistsException( "Meta file " + metaFile + " already exists." ); } } }
/** * writes string to file * @param string string to write * @param file file to which the string shall be written * @throws FileExistsException is thrown if file already exists */ public static void writeStringToFile(String string, String file) throws FileExistsException { LOGGER.debug("file " + file); if(Files.exists(Paths.get(file))) throw new FileExistsException("File " + file + "already exists"); File f = new File(file); f.getParentFile().mkdirs(); try { PrintWriter out = new PrintWriter(f); out.write(string); out.close(); } catch (FileNotFoundException e) { LOGGER.error(e.getMessage()); assert false; } }
/** * write antlr artifacts to destination * @param dest directory to which the artifacts should be written */ public void writeAntlrAritfactsTo(String dest) { MemoryTupleSet ms = getAllCompiledObjects(); for(MemoryTuple tup : ms) { MemorySource src = tup.getSource(); try { FileUtils.writeStringToFile(src.getCharContent(false).toString(), Paths.get(dest, src.getClassName()).toString() + "" + ".java"); } catch (FileExistsException e) { LOGGER.error(e.getMessage()); } } }
public static File saveProfile(String name, boolean overrideExisting) throws IOException, FileExistsException, ConfigurationException { if (StringUtils.isEmpty(name)) throw new IOException("No name given!"); if (!name.matches(PROFILE_NAME_REGEX)) throw new IOException("Invalid profile name "+name+" - only alphanumeric characters and underscores are allowed!"); if (isPredefinedProfile(name)) throw new IOException("Cannot ovverride a predefined profile!"); if (getAvailableProfiles().contains(name) && !overrideExisting) { throw new FileExistsException("Profile "+name+" already exists!"); } File profileFile = new File(PROFILES_FOLDER+"/"+name+PROFILE_SUFFIX); logger.info("storing new profile: "+profileFile.getAbsolutePath()); config.save(profileFile); return profileFile; }
@Override public User changeUserAvatar(Long userId, MultipartFile avatarFile) throws IOException { User user = findUser(userId); File currentAvatarFile = new File(platformResourceConfigurationProperties.getImageLibraryDirectory() + "/user-avatar/" + user.getAvatarFileName()); if (currentAvatarFile.exists()) { if (!currentAvatarFile.delete()) { throw new FileExistsException(); } } PasswordEncoder encoder = new BCryptPasswordEncoder(); String newAvatarFileName = encoder.encode(avatarFile.getName() + new Date().getTime()).replaceAll("\"", "s").replaceAll("/", "a").replace(".", "sde"); File newAvatarFile = new File(platformResourceConfigurationProperties.getImageLibraryDirectory() + "/user-avatar/" + newAvatarFileName); FileOutputStream out = new FileOutputStream(newAvatarFile); out.write(avatarFile.getBytes()); out.close(); user.setAvatarFileName(newAvatarFileName); updateUser(user); return findUser(userId); }
@PreAuthorize("hasPermission(#id, '" + AclClassName.Values.LAYOUT + "', '" + PermissionName.Values.LAYOUT_EDIT + "')") @Override public Layout changeIcon(Long id, MultipartFile iconFile) throws IOException { Layout layout = findLayout(id); File currentAvatarFile = new File(platformResourceConfigurationProperties.getImageLibraryDirectory() + "/layout-miniature/" + layout.getIconFileName()); if (currentAvatarFile.exists()) { if (!currentAvatarFile.delete()) { throw new FileExistsException(); } } PasswordEncoder encoder = new BCryptPasswordEncoder(); String newIconFileName = encoder.encode(iconFile.getName() + new Date().getTime()).replaceAll("\"", "s").replaceAll("/", "a").replace(".", "sde"); File newIconFile = new File(platformResourceConfigurationProperties.getImageLibraryDirectory() + "/layout-miniature/" + newIconFileName); FileOutputStream out = new FileOutputStream(newIconFile); out.write(iconFile.getBytes()); out.close(); layout.setIconFileName(newIconFileName); updateLayout(layout); return findLayout(id); }
/** * Don't need synchronize, due to EventManager will execute serially * * @param conf * @param topologyId * @param masterCodeDir * @throws IOException * @throws TException */ private void downloadDistributeStormCode(Map conf, String topologyId, String masterCodeDir) throws IOException, TException { // STORM_LOCAL_DIR/supervisor/tmp/(UUID) String tmproot = StormConfig.supervisorTmpDir(conf) + File.separator + UUID.randomUUID().toString(); // STORM_LOCAL_DIR/supervisor/stormdist/topologyId String stormroot = StormConfig.supervisor_stormdist_root(conf, topologyId); JStormServerUtils.downloadCodeFromMaster(conf, tmproot, masterCodeDir, topologyId, true); // tmproot/stormjar.jar String localFileJarTmp = StormConfig.stormjar_path(tmproot); // extract dir from jar JStormUtils.extract_dir_from_jar(localFileJarTmp, StormConfig.RESOURCES_SUBDIR, tmproot); File srcDir = new File(tmproot); File destDir = new File(stormroot); try { FileUtils.moveDirectory(srcDir, destDir); } catch (FileExistsException e) { FileUtils.copyDirectory(srcDir, destDir); FileUtils.deleteQuietly(srcDir); } }
/** * Writes the created dataset to the given file * * @param file * The file to write the dataset to. * @throws IOException * If the file could not be written */ public void writeDataset(final File file) throws IOException { // Check if the file already exists if (file.exists()) throw new FileExistsException(file); // Ensure that the directory exists for the file if (!file.getParentFile().mkdirs()) throw new IOException("Cannot create directory " + file.getParent()); // Write all the annotated identifiers final FileWriter fw = new FileWriter(file); for (final AnnotatedIdentifiable ai : this.dataset) fw.append(ai.toString() + "\n"); fw.close(); }
private void moveFileToHiddenDirectory(File source) throws IOException { boolean exists = true; int i = 0; while (exists) { File backup = FileUtils.toFile(getHiddenDirectoryPathForFile(source, String.valueOf(i))); try { FileUtils.moveFile(source, backup); exists = false; } catch (FileExistsException ex) { LOG.error("Exception moving file to hidden folder because {}. Retrying...", ex.getMessage()); exists = true; } i++; if (i > maxFileExistRetrys) { throw new IOException(String.format("moveFileToHiddenDirectory has hit %s for %s" + maxFileExistRetrys, source.getName())); } } }
@Override public ProfileAttachment addProfileAttachment(final String profileId, final String attachmentName, final InputStream file) throws ProfileException { String storeName = "/" + profileId + "/" + FilenameUtils.removeExtension(attachmentName); try { ObjectId currentId = checkIfAttachmentExist(storeName); String mimeType = getAttachmentContentType(attachmentName); FileInfo fileInfo; if (currentId != null) { // Update !!! fileInfo = profileRepository.updateFile(currentId, file, storeName, mimeType, true); } else { fileInfo = profileRepository.saveFile(file, storeName, mimeType); } return fileInfoToProfileAttachment(fileInfo); } catch (MongoDataException | FileExistsException | FileNotFoundException e) { throw new ProfileException("Unable to attach file to profile '" + profileId + "'", e); } }
private void moveFile(String currentAbsolutePath, String newAbsolutePath) throws BuenOjoFileException{ try { FileUtils.moveFile(new File(currentAbsolutePath), new File(newAbsolutePath)); } catch (FileExistsException fe){ log.error(fe.getMessage()); throw new BuenOjoFileException("no se pudo mover el archivo: " +currentAbsolutePath+" al destino"+ newAbsolutePath + " porque ese archivo ya existe"); } catch (IOException e) { log.error(e.getMessage()); throw new BuenOjoFileException("no se pudo mover el archivo: " +currentAbsolutePath+" al destino: "+ newAbsolutePath + e.getMessage()); } }
/** * Create a keystore for the given path and store various keys in it which are needed for JWT. * * @param keystorePath * @param keystorePassword * @throws NoSuchAlgorithmException * Thrown if the HmacSHA256 algorithm could not be found * @throws KeyStoreException * @throws IOException * @throws CertificateException */ public static void gen(String keystorePath, String keystorePassword) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException { Objects.requireNonNull(keystorePassword, "The keystore password must be specified."); File keystoreFile = new File(keystorePath); if (keystoreFile.exists()) { throw new FileExistsException(keystoreFile); } KeyGenerator keygen = KeyGenerator.getInstance("HmacSHA256"); SecretKey key = keygen.generateKey(); KeyStore keystore = KeyStore.getInstance("jceks"); keystore.load(null, null); // This call throws an exception keystore.setKeyEntry("HS256", key, keystorePassword.toCharArray(), null); FileOutputStream fos = new FileOutputStream(keystoreFile); try { keystore.store(fos, keystorePassword.toCharArray()); fos.flush(); } finally { fos.close(); } // SecretKey keyRetrieved = (SecretKey) keystore.getKey("theKey", keystorePassword.toCharArray()); // System.out.println(keyRetrieved.getAlgorithm()); }
private void getConfigs() throws IOException { File configZip; File customConfig = new File(synchronizationData.cohereDir, "customConfig.zip"); File localConfig = new File(localhost, "config"); try { FileUtils.moveDirectory(new File("config"), localConfig); //Move config folder } catch (FileExistsException ignored) {} if (synchronizationData.updateConfigs || !customConfig.exists()) { //Download the new config if updateConfigs is true uiProgress.info("Downloading configs", 3); configZip = new File(synchronizationData.cohereDir, "config.zip"); if (configZip.exists()) configZip.delete(); configZip.createNewFile(); FileOutputStream fstream = new FileOutputStream(configZip); ByteArrayOutputStream stream = new ByteArrayOutputStream(); POSTGetter.get(synchronizationData.url + "/config", stream); stream.writeTo(fstream); fstream.close(); stream.close(); } else { //Otherwise, use the old configs. uiProgress.info("Using previous configs", 3); configZip = customConfig; } logger.info("Extracting configs", 2); UnzipUtility.unzip(configZip.getPath(), new File(".").getPath()); }
/** * Moves a directory. * <p> * When the destination directory is on another file system, do a "copy and delete". * * @param srcDir the directory to be moved * @param destDir the destination directory * @throws NullPointerException if source or destination is {@code null} * @throws FileExistsException if the destination directory exists * @throws IOException if source or destination is invalid * @throws IOException if an IO error occurs moving the file * @since 1.4 */ public static void moveDirectory(File srcDir, File destDir) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (!srcDir.exists()) { throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); } if (!srcDir.isDirectory()) { throw new IOException("Source '" + srcDir + "' is not a directory"); } if (destDir.exists()) { throw new FileExistsException("Destination '" + destDir + "' already exists"); } boolean rename = srcDir.renameTo(destDir); if (!rename) { if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { throw new IOException("Cannot move directory: "+srcDir+" to a subdirectory of itself: "+destDir); } copyDirectory( srcDir, destDir ); deleteDirectory( srcDir ); if (srcDir.exists()) { throw new IOException("Failed to delete original directory '" + srcDir + "' after copy to '" + destDir + "'"); } } }
/** * Moves a file. * <p> * When the destination file is on another file system, do a "copy and delete". * * @param srcFile the file to be moved * @param destFile the destination file * @throws NullPointerException if source or destination is {@code null} * @throws FileExistsException if the destination file exists * @throws IOException if source or destination is invalid * @throws IOException if an IO error occurs moving the file * @since 1.4 */ public static void moveFile(File srcFile, File destFile) throws IOException { if (srcFile == null) { throw new NullPointerException("Source must not be null"); } if (destFile == null) { throw new NullPointerException("Destination must not be null"); } if (!srcFile.exists()) { throw new FileNotFoundException("Source '" + srcFile + "' does not exist"); } if (srcFile.isDirectory()) { throw new IOException("Source '" + srcFile + "' is a directory"); } if (destFile.exists()) { throw new FileExistsException("Destination '" + destFile + "' already exists"); } if (destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' is a directory"); } boolean rename = srcFile.renameTo(destFile); if (!rename) { copyFile( srcFile, destFile ); if (!srcFile.delete()) { FileUtils.deleteQuietly(destFile); throw new IOException("Failed to delete original file '" + srcFile + "' after copy to '" + destFile + "'"); } } }
private void downloadArchive(String version) throws MalformedURLException, FileExistsException { URL zipURL = new URL(repository.getUrl()+"/archive/"+version+".zip"); Download dl; int counter = 0; do { dl = new Download(zipURL, version); while(dl.getStatus() == Download.DOWNLOADING) { notifyGithubPanelListener(Download.DOWNLOADING); System.out.println("downloading :" + dl.getProgress()); try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } counter++; } while (dl.getStatus() == Download.ERROR && counter < 3); if (dl.getStatus() == Download.COMPLETE) { String tmpFolder = KKMulticopterFlashTool.getTempFolder(); File zipFile = new File(tmpFolder, version+".zip" ); File toFolder = new File(tmpFolder, "github"); Zip.unzip2folder(zipFile, toFolder); updateTargets(); notifyGithubPanelListener(Download.COMPLETE); } }
/** * Removes and back duplicates up. * * @param duplicates * list of artifacts to remove * @param type * either {@link #PLUGINS} or {@link #FEATURES} */ private void removeAndBackupDuplicates(final Set<Artifact> duplicates, final String type) { File destinationTypeFolder = FileUtils.getFile(backupFolder, type); for (Artifact artifact : duplicates) { logger.info("Cleaning {}", artifact); try { FileUtils.moveToDirectory(artifact.getLocation(), destinationTypeFolder, true); logger.info(" OK"); } catch (FileExistsException e1) { // the bundle was already copied there from an other // location, so it means we have more duplicates in multiple // location(s) with the same version, simply just delete it! boolean wasDeleted = FileUtils.deleteQuietly(artifact.getLocation()); if (wasDeleted) { logger.warn( " --> The duplicate `{}` was deleted directly without creating a copy in the destination folder due to \n `{}`.", artifact, e1.getLocalizedMessage()); } else { logger.warn(" Unable to remove the duplicate '{}' from '{}'.", artifact, artifact.getLocation()); } } catch (Exception e) { logger.error("Unable to remove the duplicate '{}'.", artifact, e); } } }
@Override public String process() throws Exception { File file = getContext().getFileToProcess(FolderType.valueOf(from)); File destinationFolder = getContext().getFolder(FolderType.valueOf(to)); try { getLogger(this.getClass().getName()).log(Level.INFO, "Moving file " + file + " to " + destinationFolder); moveFileToDirectory(file, destinationFolder, false); } catch (FileExistsException e) { getLogger(this.getClass().getName()).log(Level.WARNING, "File " + file + " already exists at " + destinationFolder); } return "COMPLETED"; }
public static void moveFile(@NonNull final GenericFile source, @NonNull final GenericFile target, final boolean useCommandLine) throws IOException { if (useCommandLine) { if (target.exists()) { throw new FileExistsException("Target exists"); } final boolean result = CommandLine.execute(new CommandMove(source, target)); if (!result) { throw new IOException("Move failed"); } } else { FileUtils.moveFile(source.toFile(), target.toFile()); } }
public static void moveDirectory(@NonNull final GenericFile source, @NonNull final GenericFile target, final boolean useCommandLine) throws IOException { if (useCommandLine) { if (target.exists()) { throw new FileExistsException("Target exists"); } final boolean result = CommandLine.execute(new CommandMove(source, target)); if (!result) { throw new IOException("Move failed"); } } else { FileUtils.moveDirectory(source.toFile(), target.toFile()); } }
private void testMoveFileToFileInDifferentDir(final boolean useCommandLine) throws Throwable { final GenericFile fileToMove = new JavaFile(testDir, "fileToMove"); assertTrue(fileToMove.createNewFile()); final GenericFile targetDir = new JavaFile(testDir, "targetDir"); assertTrue(targetDir.mkdir()); final GenericFile targetFile = new JavaFile(targetDir.toFile(), "targetFile"); PFMFileUtils.moveFile(fileToMove, targetFile, useCommandLine); assertFalse(fileToMove.toFile().exists()); assertTrue(targetFile.toFile().exists()); assertTrue(targetFile.toFile().isFile()); //test if FileExistsException is thrown assertTrue(fileToMove.createNewFile()); try { PFMFileUtils.moveFile(fileToMove, targetFile, useCommandLine); throw new RuntimeException("FileExistsException is not thrown"); } catch (FileExistsException ignored) { } //cleanup assertTrue(fileToMove.delete()); assertTrue(targetFile.delete()); assertTrue(targetDir.delete()); }
protected void createLocalFileFromInputStream(InputStream is, File baseLocalFile) throws IOException { FileOutputStream tos = null; FileWorkArea workArea = null; try { if (!baseLocalFile.getParentFile().exists()) { boolean directoriesCreated = false; if (!baseLocalFile.getParentFile().exists()) { directoriesCreated = baseLocalFile.getParentFile().mkdirs(); if (!directoriesCreated) { // There is a chance that another VM created the directories. If not, we may not have // proper permissions and this is an error we need to report. if (!baseLocalFile.getParentFile().exists()) { throw new RuntimeException("Unable to create middle directories for file: " + baseLocalFile.getAbsolutePath()); } } } } workArea = broadleafFileService.initializeWorkArea(); File tmpFile = new File(FilenameUtils.concat(workArea.getFilePathLocation(), baseLocalFile.getName())); tos = new FileOutputStream(tmpFile); IOUtils.copy(is, tos); // close the input/output streams before trying to move files around is.close(); tos.close(); // Adding protection against this file already existing / being written by another thread. // Adding locks would be useless here since another VM could be executing the code. if (!baseLocalFile.exists()) { try { FileUtils.moveFile(tmpFile, baseLocalFile); } catch (FileExistsException e) { // No problem if (LOG.isDebugEnabled()) { LOG.debug("File exists error moving file " + tmpFile.getAbsolutePath(), e); } } } } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(tos); if (workArea != null) { broadleafFileService.closeWorkArea(workArea); } } }
protected void createLocalFileFromInputStream(InputStream is, File baseLocalFile) throws IOException { FileOutputStream tos = null; FileWorkArea workArea = null; try { if (!baseLocalFile.getParentFile().exists()) { boolean directoriesCreated = false; if (!baseLocalFile.getParentFile().exists()) { directoriesCreated = baseLocalFile.getParentFile().mkdirs(); if (!directoriesCreated) { // There is a chance that another VM created the directories. If not, we may not have // proper permissions and this is an error we need to report. if (!baseLocalFile.getParentFile().exists()) { throw new RuntimeException("Unable to create middle directories for file: " + baseLocalFile.getAbsolutePath()); } } } } workArea = sparkFileService.initializeWorkArea(); File tmpFile = new File(FilenameUtils.concat(workArea.getFilePathLocation(), baseLocalFile.getName())); tos = new FileOutputStream(tmpFile); IOUtils.copy(is, tos); // close the input/output streams before trying to move files around is.close(); tos.close(); // Adding protection against this file already existing / being written by another thread. // Adding locks would be useless here since another VM could be executing the code. if (!baseLocalFile.exists()) { try { FileUtils.moveFile(tmpFile, baseLocalFile); } catch (FileExistsException e) { // No problem if (LOG.isDebugEnabled()) { LOG.debug("File exists error moving file " + tmpFile.getAbsolutePath(), e); } } } } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(tos); if (workArea != null) { sparkFileService.closeWorkArea(workArea); } } }
private void moveFile (File src_file, File dest_file) throws IOException, NoSuchAlgorithmException { if (src_file == null) { throw new NullPointerException ("Source must not be null"); } if (dest_file == null) { throw new NullPointerException ("Destination must not be null"); } if ( !src_file.exists ()) { throw new FileNotFoundException ("Source '" + src_file + "' does not exist"); } if (src_file.isDirectory ()) { throw new IOException ("Source '" + src_file + "' is a directory"); } if (dest_file.exists ()) { throw new FileExistsException ("Destination '" + dest_file + "' already exists"); } if (dest_file.isDirectory ()) { throw new IOException ("Destination '" + dest_file + "' is a directory"); } boolean rename = src_file.renameTo (dest_file); if ( !rename) { copyFile (src_file, dest_file); if ( !src_file.delete ()) { FileUtils.deleteQuietly (dest_file); throw new IOException ("Failed to delete original file '" + src_file + "' after copy to '" + dest_file + "'"); } } }
public static void downloadLocalStormCode(Map conf, String topologyId, String masterCodeDir) throws IOException, TException { // STORM_LOCAL_DIR/supervisor/tmp/(UUID) String tmpRoot = StormConfig.supervisorTmpDir(conf) + File.separator + UUID.randomUUID().toString(); // STORM-LOCAL-DIR/supervisor/stormdist/storm-id String stormRoot = StormConfig.supervisor_stormdist_root(conf, topologyId); BlobStore blobStore = null; try { blobStore = BlobStoreUtils.getNimbusBlobStore(conf, masterCodeDir, null); FileUtils.forceMkdir(new File(tmpRoot)); blobStore.readBlobTo(StormConfig.master_stormcode_key(topologyId), new FileOutputStream(StormConfig.stormcode_path(tmpRoot))); blobStore.readBlobTo(StormConfig.master_stormconf_key(topologyId), new FileOutputStream(StormConfig.stormconf_path(tmpRoot))); } finally { if (blobStore != null) blobStore.shutdown(); } File srcDir = new File(tmpRoot); File destDir = new File(stormRoot); try { FileUtils.moveDirectory(srcDir, destDir); } catch (FileExistsException e) { FileUtils.copyDirectory(srcDir, destDir); FileUtils.deleteQuietly(srcDir); } ClassLoader classloader = Thread.currentThread().getContextClassLoader(); String resourcesJar = resourcesJar(); URL url = classloader.getResource(StormConfig.RESOURCES_SUBDIR); String targetDir = stormRoot + '/' + StormConfig.RESOURCES_SUBDIR; if (resourcesJar != null) { LOG.info("Extracting resources from jar at " + resourcesJar + " to " + targetDir); JStormUtils.extractDirFromJar(resourcesJar, StormConfig.RESOURCES_SUBDIR, stormRoot); } else if (url != null) { LOG.info("Copying resources at " + url.toString() + " to " + targetDir); FileUtils.copyDirectory(new File(url.getFile()), (new File(targetDir))); } }