List of usage examples for org.apache.commons.io FileUtils forceDelete
public static void forceDelete(File file) throws IOException
From source file:fr.logfiletoes.ElasticSearchTest.java
@Test public void wildfly() throws IOException, InterruptedException { File data = Files.createTempDirectory("it_es_data-").toFile(); Settings settings = ImmutableSettings.settingsBuilder().put("path.data", data.toString()) .put("cluster.name", "IT-0001").build(); Node node = NodeBuilder.nodeBuilder().local(true).settings(settings).build(); Client client = node.client();/*w ww. ja v a 2 s. c om*/ node.start(); Config config = new Config("./src/test/resources/config-wildfly-one.json"); List<Unit> units = config.getUnits(); assertEquals(1, units.size()); units.get(0).start(); // Wait store log Thread.sleep(3000); // Search log SearchResponse response = client.prepareSearch("logdetest").setSearchType(SearchType.DEFAULT) .setQuery(QueryBuilders.matchQuery("message", "Configured system properties")).setSize(1000) .addSort("@timestamp", SortOrder.ASC).execute().actionGet(); if (LOG.isLoggable(Level.FINEST)) { for (SearchHit hit : response.getHits().getHits()) { LOG.finest("-----------------"); hit.getSource().forEach((key, value) -> { LOG.log(Level.FINEST, "{0} = {1}", new Object[] { key, value }); }); } } // Get information need to test String expected = response.getHits().getHits()[0].getSource().get("message").toString(); assertEquals(stacktrace, expected); // wait request Thread.sleep(10000); // Close tailer units.get(0).stop(); // Close ElasticSearch node.close(); // Clean data directory FileUtils.forceDelete(data); }
From source file:com.jhash.oimadmin.ui.UIJavaCompile.java
@Override public void destroyComponent() { if (outputDirectory != null) { try {/*from w ww .ja v a 2 s .co m*/ File outputDirectoryFile = new File(outputDirectory); if (outputDirectoryFile.exists()) { FileUtils.forceDelete(outputDirectoryFile); } } catch (Exception exception) { logger.warn("Failed to delete directory " + outputDirectory + ". Ignoring error", exception); } outputDirectory = null; } if (javaCompileUI != null) { javaCompileUI = null; } }
From source file:fi.jumi.test.AppRunner.java
private void tearDown() { if (launcher != null) { try {/* ww w . j a va 2s.com*/ launcher.close(); } catch (IOException e) { e.printStackTrace(); } } if (processStarter.lastProcess.isDone()) { try { Process process = processStarter.lastProcess.get(); kill(process); } catch (Exception e) { e.printStackTrace(); } } try { FileUtils.forceDelete(sandboxDir.toFile()); } catch (IOException e) { System.err.println("WARNING: " + e.getMessage()); } }
From source file:eu.optimis.ics.core.image.Image.java
/** * Deletes the actual image file associated with this VM image. * //from w w w . ja v a 2 s . c o m * @throws IOException Could not delete file error */ public synchronized void deleteImageFile() { LOGGER.info("ics.core.Image.deleteImageFile(): Deleting image file " + imageFile); try { FileUtils.forceDelete(imageFile); } catch (IOException ioException) { LOGGER.warn("ics.core.Image.deleteImageFile(): Could not delete file '" + imageFile + "'", ioException); } //LOGGER.info("ics.core.Image.deleteImageFile(): File " + imageFile + " is deleted"); imageFile = null; }
From source file:com.orange.mmp.file.helpers.DefaultFileManager.java
/** * Remove a module fileset from MMP//from ww w. ja va2 s.c o m * * @param module The module containing the fileset * @throws MMPFileException */ protected void removeModuleFileset(Module module) throws MMPFileException { try { MMPConfig moduleConfiguration = ModuleContainerFactory.getInstance().getModuleContainer() .getModuleConfiguration(module); if (moduleConfiguration != null && moduleConfiguration.getFileset() != null) { for (MMPConfig.Fileset filesetConfig : moduleConfiguration.getFileset()) { String filesetName = filesetConfig.getName(); File dstFiles[] = this.filesetCache.get(filesetName); this.filesetCache.remove(filesetName); if (dstFiles != null) { for (File currentFile : dstFiles) { FileUtils.forceDelete(currentFile); } } } } } catch (IOException ioe) { throw new MMPFileException(ioe); } catch (MMPModuleException me) { throw new MMPFileException(me); } }
From source file:hd3gtv.mydmam.useraction.fileoperation.CopyMove.java
private void copyFile(File source_file, File destination_file) throws IOException { if (destination_file.exists()) { Log2Dump dump = new Log2Dump(); dump.add("source_file", source_file); dump.add("destination_file", destination_file); dump.add("delete_after_copy", delete_after_copy); if (fileexistspolicy == FileExistsPolicy.IGNORE) { Log2.log.debug("Destination file exists, ignore copy/move", dump); return; } else if (fileexistspolicy == FileExistsPolicy.OVERWRITE) { Log2.log.debug("Destination file exists, overwrite it", dump); FileUtils.forceDelete(destination_file); } else if (fileexistspolicy == FileExistsPolicy.RENAME) { // destination_file int cursor = 1; int dot_pos; StringBuilder sb;/* w w w . j a v a 2 s . c om*/ while (destination_file.exists()) { sb = new StringBuilder(); sb.append(destination_file.getParent()); sb.append(File.separator); dot_pos = destination_file.getName().lastIndexOf("."); if (dot_pos > 0) { sb.append(destination_file.getName().substring(0, dot_pos)); sb.append(" ("); sb.append(cursor); sb.append(")"); sb.append( destination_file.getName().substring(dot_pos, destination_file.getName().length())); } else { sb.append(destination_file.getName()); sb.append(" ("); sb.append(cursor); sb.append(")"); } destination_file = new File(sb.toString()); cursor++; } dump.add("new destination file name", destination_file); Log2.log.debug("Destination file exists, change destionation name", dump); } } /** * Imported from org.apache.commons.io.FileUtils * Licensed to the Apache Software Foundation, * http://www.apache.org/licenses/LICENSE-2.0 */ FileInputStream fis = null; FileOutputStream fos = null; FileChannel input = null; FileChannel output = null; try { fis = new FileInputStream(source_file); fos = new FileOutputStream(destination_file); input = fis.getChannel(); output = fos.getChannel(); long size = input.size(); long pos = 0; long count = 0; while (pos < size) { count = (size - pos) > FIFTY_MB ? FIFTY_MB : (size - pos); pos += output.transferFrom(input, pos, count); if (progression != null) { actual_progress_value = (int) ((pos + progress_copy) / (1024 * 1024)); if (actual_progress_value > last_progress_value) { last_progress_value = actual_progress_value; progression.updateProgress(actual_progress_value, progress_size); } } } } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(fos); IOUtils.closeQuietly(input); IOUtils.closeQuietly(fis); } if (source_file.length() != destination_file.length()) { throw new IOException( "Failed to copy full contents from '" + source_file + "' to '" + destination_file + "'"); } if (destination_file.setExecutable(source_file.canExecute()) == false) { Log2.log.error("Can't set Executable status to dest file", new IOException(destination_file.getPath())); } if (destination_file.setLastModified(source_file.lastModified()) == false) { Log2.log.error("Can't set LastModified status to dest file", new IOException(destination_file.getPath())); } }
From source file:com.liferay.arquillian.maven.internal.LiferayWarPackagingProcessor.java
/** * (non-Javadoc)//ww w.j a v a2 s . co m * @see * org.jboss.shrinkwrap.resolver.spi.maven.archive.packaging.PackagingProcessor * #importBuildOutput(org.jboss.shrinkwrap.resolver.api.maven.strategy. * MavenResolutionStrategy) */ @Override public LiferayWarPackagingProcessor importBuildOutput(MavenResolutionStrategy strategy) { log.debug("Building Liferay Plugin Archive"); ParsedPomFile pomFile = session.getParsedPomFile(); // Compile and add Java classes if (Validate.isReadable(pomFile.getSourceDirectory())) { compile(pomFile.getSourceDirectory(), pomFile.getBuildOutputDirectory(), ScopeType.COMPILE, ScopeType.RUNTIME, ScopeType.SYSTEM, ScopeType.IMPORT, ScopeType.PROVIDED); JavaArchive classes = ShrinkWrap.create(ExplodedImporter.class, "webinf_clases.jar") .importDirectory(pomFile.getBuildOutputDirectory()).as(JavaArchive.class); archive = archive.merge(classes, ArchivePaths.create("WEB-INF/classes")); // Raise bug with shrink wrap ?Since configure creates the base war // in target classes, we need to delete from the archive log.trace("Removing temp file: " + pomFile.getFinalName() + " form archive"); archive.delete(ArchivePaths.create("WEB-INF/classes", pomFile.getFinalName())); } // Add Resources for (Resource resource : pomFile.getResources()) { archive.addAsResource(resource.getSource(), resource.getTargetPath()); } // Webapp build WarPluginConfiguration warPluginConfiguration = new WarPluginConfiguration(pomFile); if (Validate.isReadable(warPluginConfiguration.getWarSourceDirectory())) { WebArchive webapp = ShrinkWrap.create(ExplodedImporter.class, "webapp.war") .importDirectory(warPluginConfiguration.getWarSourceDirectory(), applyFilter(warPluginConfiguration)) .as(WebArchive.class); archive.merge(webapp); } // Add manifest try { Manifest manifest = warPluginConfiguration.getArchiveConfiguration().asManifest(); ByteArrayOutputStream bout = new ByteArrayOutputStream(); manifest.write(bout); archive.setManifest(new StringAsset(bout.toString())); } catch (MavenImporterException e) { log.error("Error adding manifest", e); } catch (IOException e) { log.error("Error adding manifest", e); } // add dependencies this.session = AddAllDeclaredDependenciesTask.INSTANCE.execute(session); final Collection<MavenResolvedArtifact> artifacts = session.resolveDependencies(strategy); for (MavenResolvedArtifact artifact : artifacts) { archive.addAsLibrary(artifact.asFile()); } // Archive Filtering archive = ArchiveFilteringUtils.filterArchiveContent(archive, WebArchive.class, warPluginConfiguration.getIncludes(), warPluginConfiguration.getExcludes()); // Liferay Plugin Deployer LiferayPluginConfiguration liferayPluginConfiguration = new LiferayPluginConfiguration(pomFile); // Temp Archive for processing by Liferay deployers String baseDirPath = liferayPluginConfiguration.getBaseDir(); File tempDestFile = new File(baseDirPath, pomFile.getFinalName()); File baseDir = new File(baseDirPath); if (!baseDir.exists()) { baseDir.mkdirs(); log.info("Created dir " + baseDir); } log.trace("Temp Archive:" + tempDestFile.getName()); archive.as(ZipExporter.class).exportTo(tempDestFile, true); FileUtils.deleteQuietly(new File(pomFile.getFinalName())); if ("hook".equals(liferayPluginConfiguration.getPluginType())) { // perform hook deployer task HookDeployerTask.INSTANCE.execute(session); } else { // default is always portletdeployer PortletDeployerTask.INSTANCE.execute(session); } // Call Liferay Deployer LiferayPluginConfiguration configuration = new LiferayPluginConfiguration(pomFile); File ddPluginArchiveFile = new File(configuration.getDestDir(), pomFile.getArtifactId() + ".war"); archive = ShrinkWrap.create(ZipImporter.class, pomFile.getFinalName()).importFrom(ddPluginArchiveFile) .as(WebArchive.class); try { FileUtils.forceDelete(ddPluginArchiveFile); FileUtils.forceDelete(new File(configuration.getBaseDir(), pomFile.getFinalName())); } catch (IOException e) { // nothing to do } return this; }
From source file:com.hs.mail.imap.mailbox.DefaultMailboxManager.java
private void deletePhysicalMessage(PhysMessage pm) { MessageDao dao = DaoFactory.getMessageDao(); dao.deletePhysicalMessage(pm.getPhysMessageID()); if (hdCache != null) { hdCache.remove(pm.getPhysMessageID()); }/*from ww w .j a va2 s . c om*/ try { File dataFile = Config.getDataFile(pm.getInternalDate(), pm.getPhysMessageID()); FileUtils.forceDelete(dataFile); File descriptorFile = Config.getMimeDescriptorFile(pm.getInternalDate(), pm.getPhysMessageID()); if (descriptorFile.exists()) { FileUtils.forceDelete(descriptorFile); } } catch (IOException ex) { logger.warn(ex.getMessage(), ex); // Ignore - What we can do? } }
From source file:hoot.services.controllers.info.ReportsResource.java
protected boolean _deleteReport(String id) throws Exception { boolean deleted = false; String repDataPath = _homeFolder + "/" + _rptStorePath + "/" + id; File f = new File(repDataPath); if (f.exists()) { FileUtils.forceDelete(f); deleted = true;/*from ww w . j a va 2 s . c om*/ } return deleted; }
From source file:com.kegare.caveworld.world.WorldProviderCaveworld.java
public static void regenerate(final boolean backup) { final File dir = getDimDir(); final String name = dir.getName().substring(4); final MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); Set<EntityPlayerMP> target = Sets.newHashSet(); for (Object obj : server.getConfigurationManager().playerEntityList.toArray()) { if (obj != null && ((EntityPlayerMP) obj).dimension == CaveworldAPI.getDimension()) { target.add(CaveUtils.respawnPlayer((EntityPlayerMP) obj, 0)); }//from w w w. j a v a2 s. c o m } boolean result = new ForkJoinPool().invoke(new RecursiveTask<Boolean>() { @Override protected Boolean compute() { IChatComponent component; try { component = new ChatComponentText( StatCollector.translateToLocalFormatted("caveworld.regenerate.regenerating", name)); component.getChatStyle().setColor(EnumChatFormatting.GRAY).setItalic(true); server.getConfigurationManager().sendChatMsg(component); if (server.isSinglePlayer()) { Caveworld.network.sendToAll(new RegenerateMessage(backup)); } Caveworld.network.sendToAll(new RegenerateMessage.ProgressNotify(0)); CaveBlocks.caveworld_portal.portalDisabled = true; int dim = CaveworldAPI.getDimension(); WorldServer world = DimensionManager.getWorld(dim); if (world != null) { world.saveAllChunks(true, null); world.flush(); MinecraftForge.EVENT_BUS.post(new WorldEvent.Unload(world)); DimensionManager.setWorld(dim, null); } if (dir != null) { if (backup) { File parent = dir.getParentFile(); final Pattern pattern = Pattern.compile("^" + dir.getName() + "_bak-..*\\.zip$"); File[] files = parent.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return pattern.matcher(name).matches(); } }); if (files != null && files.length >= 5) { Arrays.sort(files, new Comparator<File>() { @Override public int compare(File o1, File o2) { int i = CaveUtils.compareWithNull(o1, o2); if (i == 0 && o1 != null && o2 != null) { try { i = Files.getLastModifiedTime(o1.toPath()) .compareTo(Files.getLastModifiedTime(o2.toPath())); } catch (IOException e) { } } return i; } }); FileUtils.forceDelete(files[0]); } Calendar calendar = Calendar.getInstance(); String year = Integer.toString(calendar.get(Calendar.YEAR)); String month = String.format("%02d", calendar.get(Calendar.MONTH) + 1); String day = String.format("%02d", calendar.get(Calendar.DATE)); String hour = String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)); String minute = String.format("%02d", calendar.get(Calendar.MINUTE)); String second = String.format("%02d", calendar.get(Calendar.SECOND)); File bak = new File(parent, dir.getName() + "_bak-" + Joiner.on("").join(year, month, day) + "-" + Joiner.on("").join(hour, minute, second) + ".zip"); if (bak.exists()) { FileUtils.deleteQuietly(bak); } component = new ChatComponentText(StatCollector .translateToLocalFormatted("caveworld.regenerate.backingup", name)); component.getChatStyle().setColor(EnumChatFormatting.GRAY).setItalic(true); server.getConfigurationManager().sendChatMsg(component); Caveworld.network.sendToAll(new RegenerateMessage.ProgressNotify(1)); if (CaveUtils.archiveDirZip(dir, bak)) { ClickEvent click = new ClickEvent(ClickEvent.Action.OPEN_FILE, FilenameUtils.normalize(bak.getParentFile().getPath())); component = new ChatComponentText(StatCollector .translateToLocalFormatted("caveworld.regenerate.backedup", name)); component.getChatStyle().setColor(EnumChatFormatting.GRAY).setItalic(true) .setChatClickEvent(click); server.getConfigurationManager().sendChatMsg(component); } else { component = new ChatComponentText(StatCollector .translateToLocalFormatted("caveworld.regenerate.backup.failed", name)); component.getChatStyle().setColor(EnumChatFormatting.RED).setItalic(true); server.getConfigurationManager().sendChatMsg(component); } } FileUtils.deleteDirectory(dir); } if (DimensionManager.shouldLoadSpawn(dim)) { DimensionManager.initDimension(dim); world = DimensionManager.getWorld(dim); if (world != null) { world.saveAllChunks(true, null); world.flush(); } } CaveBlocks.caveworld_portal.portalDisabled = false; component = new ChatComponentText( StatCollector.translateToLocalFormatted("caveworld.regenerate.regenerated", name)); component.getChatStyle().setColor(EnumChatFormatting.GRAY).setItalic(true); server.getConfigurationManager().sendChatMsg(component); Caveworld.network.sendToAll(new RegenerateMessage.ProgressNotify(2)); return true; } catch (Exception e) { component = new ChatComponentText( StatCollector.translateToLocalFormatted("caveworld.regenerate.failed", name)); component.getChatStyle().setColor(EnumChatFormatting.RED).setItalic(true); server.getConfigurationManager().sendChatMsg(component); Caveworld.network.sendToAll(new RegenerateMessage.ProgressNotify(3)); CaveLog.log(Level.ERROR, e, component.getUnformattedText()); } return false; } }); if (result && (Config.hardcore || Config.caveborn)) { for (EntityPlayerMP player : target) { if (!CaveworldAPI.isEntityInCaveworld(player)) { CaveUtils.forceTeleport(player, CaveworldAPI.getDimension()); } } } }