Example usage for org.apache.commons.io FileUtils forceDelete

List of usage examples for org.apache.commons.io FileUtils forceDelete

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils forceDelete.

Prototype

public static void forceDelete(File file) throws IOException 

Source Link

Document

Deletes a file.

Usage

From source file:architecture.ee.web.community.profile.DefaultProfileManager.java

private void deleteImageFileCache(ProfileImage image) {

    Collection<File> files = FileUtils.listFiles(getImageCacheDir(),
            FileFilterUtils.prefixFileFilter(image.getProfileImageId().toString()),
            FileFilterUtils.suffixFileFilter(".profile"));
    for (File file : files) {
        log.debug(file.getPath() + ":" + file.isFile());
        try {/*from w w  w  .  j a  v  a 2 s  .  co  m*/
            FileUtils.forceDelete(file);
        } catch (IOException e) {
            log.error(e);
        }
    }

}

From source file:com.smartbear.readyapi.plugin.git.ReadyApiGitIntegrationTest.java

private void deleteFile(File path) throws IOException {
    File file = new File(path + "/settings.xml");
    FileUtils.forceDelete(file);
}

From source file:de.cosmocode.palava.store.FileSystemStore.java

/**
 * {@inheritDoc}/*  ww w  . j  av a  2s .  c o  m*/
 *
 * <p>
 *   Recursively deletes empty parent directories.
 * </p>
 */
@Override
public void delete(String identifier) throws IOException {
    Preconditions.checkNotNull(identifier, "Identifier");
    final File file = getFile(identifier);
    Preconditions.checkState(file.exists(), "%s does not exist", file);
    LOG.trace("Removing {} from store", file);
    FileUtils.forceDelete(file);
    deleteEmptyParent(file.getParentFile());
}

From source file:com.hpe.application.automation.tools.run.SvExportBuilder.java

/**
 * Cleans all sub-folders containing *.vproj file.
 *//*from www  .j a  v  a2  s.c  om*/
private void cleanTargetDirectory(PrintStream logger, String targetDirectory) throws IOException {
    File target = new File(targetDirectory);
    if (target.exists()) {
        File[] subfolders = target.listFiles((FilenameFilter) DirectoryFileFilter.INSTANCE);
        File[] files = target.listFiles((FilenameFilter) new SuffixFileFilter(".vproja"));
        if (subfolders.length > 0 || files.length > 0) {
            logger.println("  Cleaning target directory...");
        }
        for (File file : files) {
            FileUtils.forceDelete(file);
        }
        for (File subfolder : subfolders) {
            if (subfolder.listFiles((FilenameFilter) new SuffixFileFilter(".vproj")).length > 0) {
                logger.println("    Deleting subfolder of target directory: " + subfolder.getAbsolutePath());
                FileUtils.deleteDirectory(subfolder);
            } else {
                logger.println("    Skipping delete of directory '" + subfolder.getAbsolutePath()
                        + "' because it does not contain any *.vproj file.");
            }
        }
    }
}

From source file:com.hangum.tadpole.rdb.core.dialog.driver.JDBCDriverManageDialog.java

/**
 * Create contents of the dialog.//from w ww  . j  a va 2 s .c  o m
 * @param parent
 */
@Override
protected Control createDialogArea(Composite parent) {
    Composite container = (Composite) super.createDialogArea(parent);
    GridLayout gridLayout = (GridLayout) container.getLayout();
    gridLayout.verticalSpacing = 5;
    gridLayout.horizontalSpacing = 5;
    gridLayout.marginHeight = 5;
    gridLayout.marginWidth = 5;

    SashForm sashForm = new SashForm(container, SWT.NONE);
    sashForm.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

    Composite compositeLeft = new Composite(sashForm, SWT.NONE);
    compositeLeft.setLayout(new GridLayout(1, false));

    Label lblDriverList = new Label(compositeLeft, SWT.NONE);
    lblDriverList.setText(Messages.get().JDBCDriverSetting_DriverList);

    lvDB = new ListViewer(compositeLeft, SWT.BORDER | SWT.V_SCROLL);
    lvDB.addSelectionChangedListener(new ISelectionChangedListener() {
        public void selectionChanged(SelectionChangedEvent event) {
            StructuredSelection ss = (StructuredSelection) lvDB.getSelection();
            if (ss.isEmpty())
                return;

            DBDefine dbDefine = (DBDefine) ss.getFirstElement();
            jdbc_dir = ApplicationArgumentUtils.JDBC_RESOURCE_DIR + dbDefine.getExt()
                    + PublicTadpoleDefine.DIR_SEPARATOR;
            lblRealFullPath.setText(jdbc_dir);
            initDBFileList();
        }
    });
    List list = lvDB.getList();
    list.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

    lvDB.setContentProvider(new ArrayContentProvider());
    lvDB.setLabelProvider(new LabelProvider() {
        @Override
        public String getText(Object element) {
            DBDefine dbDefine = (DBDefine) element;
            return dbDefine.getDBToString();
        }
    });
    lvDB.setInput(DBDefine.getDriver());

    Composite compositeBody = new Composite(sashForm, SWT.NONE);
    compositeBody.setLayout(new GridLayout(3, false));

    Label lblDumy = new Label(compositeBody, SWT.NONE);
    lblDumy.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1));

    Label lblPath = new Label(compositeBody, SWT.NONE);
    lblPath.setText(Messages.get().JDBCDriverSetting_Path);

    lblRealFullPath = new Text(compositeBody, SWT.NONE | SWT.READ_ONLY);
    lblRealFullPath.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));

    Label txtFileList = new Label(compositeBody, SWT.NONE);
    txtFileList.setText(Messages.get().JDBCDriverSetting_FileList);
    new Label(compositeBody, SWT.NONE);
    new Label(compositeBody, SWT.NONE);

    lvDriverFile = new ListViewer(compositeBody, SWT.BORDER | SWT.V_SCROLL);
    lvDriverFile.addSelectionChangedListener(new ISelectionChangedListener() {
        public void selectionChanged(SelectionChangedEvent event) {
            btnDelete.setEnabled(true);
        }
    });
    lvDriverFile.setContentProvider(new ArrayContentProvider());
    lvDriverFile.setLabelProvider(new LabelProvider() {
        @Override
        public String getText(Object element) {
            String str = element.toString();
            return str;
        }
    });

    List listDriver = lvDriverFile.getList();
    listDriver.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1));

    Composite compositeBodyBtn = new Composite(compositeBody, SWT.NONE);
    compositeBodyBtn.setLayout(new GridLayout(1, false));
    compositeBodyBtn.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, false, true, 1, 1));

    btnDelete = new Button(compositeBodyBtn, SWT.NONE);
    btnDelete.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            StructuredSelection ss = (StructuredSelection) lvDriverFile.getSelection();
            if (ss.isEmpty())
                return;

            String strFile = (String) ss.getFirstElement();
            if (!MessageDialog.openConfirm(getShell(), Messages.get().Confirm, Messages.get().Delete))
                return;
            if (logger.isDebugEnabled())
                logger.debug("File delete : " + jdbc_dir + strFile);

            try {
                FileUtils.forceDelete(new File(jdbc_dir + strFile));

                initDBFileList();
            } catch (IOException e1) {
                logger.error("File delete", e1);
                MessageDialog.openError(getShell(), Messages.get().Error, "File deleteing: " + e1.getMessage());
            }

        }
    });
    btnDelete.setText(Messages.get().Delete);

    final String url = startUploadReceiver();
    pushSession = new ServerPushSession();

    fileUpload = new FileUpload(compositeBodyBtn, SWT.NONE);
    fileUpload.setText(Messages.get().JDBCDriverSetting_JARUpload);
    fileUpload.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
    fileUpload.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            String fileName = fileUpload.getFileName();
            if ("".equals(fileName) || null == fileName) //$NON-NLS-1$
                return;
            if (!MessageDialog.openConfirm(null, Messages.get().Confirm,
                    Messages.get().SQLiteLoginComposite_17))
                return;

            if (logger.isDebugEnabled())
                logger.debug("=[file name]==> " + fileName);

            pushSession.start();
            fileUpload.submit(url);
        }
    });

    Button btnRefresh = new Button(compositeBodyBtn, SWT.NONE);
    btnRefresh.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            initDBFileList();
        }
    });
    btnRefresh.setText(Messages.get().Refresh);

    sashForm.setWeights(new int[] { 3, 7 });
    initManager();

    return container;
}

From source file:com.twosigma.beakerx.kernel.magic.command.ClasspathAddMvnDepsMagicCommandTest.java

private void handleClasspathAddMvnDep(String allCode, String expected) throws Exception {
    MagicCommand command = new MagicCommand(
            new ClasspathAddMvnMagicCommand(configuration.mavenResolverParam(kernel), kernel), allCode);
    Code code = Code.createCode(allCode, singletonList(command), NO_ERRORS,
            new Message(new Header(JupyterMessages.COMM_MSG, "session1")));
    //when/*from  w w  w  . j  a v a2  s.  c  o m*/
    code.execute(kernel, 1);
    //then
    Optional<Message> updateMessage = EvaluatorResultTestWatcher.waitForUpdateMessage(kernel);
    String text = (String) TestWidgetUtils.getState(updateMessage.get()).get("value");
    assertThat(text).contains(expected);
    String mvnDir = kernel.getTempFolder().toString() + MavenJarResolver.MVN_DIR;
    Stream<Path> paths = Files.walk(Paths.get(mvnDir));
    Optional<Path> dep = paths.filter(file -> (file.getFileName().toFile().getName().contains("gson")
            || file.getFileName().toFile().getName().contains("slf4j"))).findFirst();
    assertThat(dep).isPresent();
    assertThat(kernel.getClasspath().get(0)).contains(mvnDir);
    assertThat(Files.exists(Paths.get(configuration.mavenResolverParam(kernel).getPathToNotebookJars()
            + File.separator + MAVEN_BUILT_CLASSPATH_FILE_NAME))).isTrue();
    dep.ifPresent(path -> {
        try {
            FileUtils.forceDelete(path.toFile());
        } catch (IOException e) {
            e.printStackTrace();
        }
    });
}

From source file:hoot.services.controllers.ingest.FileUploadResourceTest.java

@Test
@Category(UnitTest.class)
public void TestCreateNativeRequestFgdbOgrZip() throws Exception {
    String input = "fgdb_ogr.zip";
    String jobId = "test-id-123";
    String wkdirpath = homeFolder + "/upload/" + jobId;
    File workingDir = new File(wkdirpath);
    FileUtils.forceMkdir(workingDir);/*from w  w  w  . j a va  2s.  co m*/
    org.junit.Assert.assertTrue(workingDir.exists());

    File srcFile = new File(homeFolder + "/test-files/service/FileUploadResourceTest/" + input);
    File destFile = new File(wkdirpath + "/" + input);
    FileUtils.copyFile(srcFile, destFile);
    org.junit.Assert.assertTrue(destFile.exists());

    FileUploadResource res = new FileUploadResource();

    // Let's test zip
    JSONArray results = new JSONArray();
    JSONObject zipStat = new JSONObject();
    List<String> inputsList = new ArrayList<String>();
    inputsList.add(input);

    res._buildNativeRequest(jobId, "fgdb_ogr", "zip", input, results, zipStat);

    int shpCnt = 0;
    int osmCnt = 0;
    int fgdbCnt = 0;

    int zipCnt = 0;
    int shpZipCnt = 0;
    int osmZipCnt = 0;
    int fgdbZipCnt = 0;
    List<String> zipList = new ArrayList<String>();

    shpZipCnt += (Integer) zipStat.get("shpzipcnt");
    fgdbZipCnt += (Integer) zipStat.get("fgdbzipcnt");
    osmZipCnt += (Integer) zipStat.get("osmzipcnt");

    zipList.add("fgdb_ogr");
    zipCnt++;

    // Test zip containing fgdb + shp
    JSONArray resA = res._createNativeRequest(results, zipCnt, shpZipCnt, fgdbZipCnt, osmZipCnt, shpCnt,
            fgdbCnt, osmCnt, zipList, "TDSv61.js", jobId, "fgdb_ogr", inputsList);

    JSONObject req = (JSONObject) resA.get(0);
    JSONArray params = (JSONArray) req.get("params");

    int nP = 0;

    for (Object o : params) {
        JSONObject oJ = (JSONObject) o;

        if (oJ.get("INPUT") != null) {
            org.junit.Assert.assertTrue(oJ.get("INPUT").toString()
                    .equals("\"fgdb_ogr/DcGisRoads.gdb\" \"fgdb_ogr/jakarta_raya_coastline.shp\" "));
            nP++;
        }

        if (oJ.get("INPUT_PATH") != null) {
            org.junit.Assert.assertTrue(oJ.get("INPUT_PATH").toString().equals("upload/test-id-123"));
            nP++;
        }

        if (oJ.get("INPUT_TYPE") != null) {
            org.junit.Assert.assertTrue(oJ.get("INPUT_TYPE").toString().equals("OGR"));
            nP++;
        }

        if (oJ.get("UNZIP_LIST") != null) {
            org.junit.Assert.assertTrue(oJ.get("UNZIP_LIST").toString().equals("fgdb_ogr"));
            nP++;
        }
    }
    org.junit.Assert.assertTrue(nP == 4);
    FileUtils.forceDelete(workingDir);
}

From source file:com.liferay.maven.arquillian.internal.LiferayWarPackagingProcessor.java

@Override
public LiferayWarPackagingProcessor importBuildOutput(MavenResolutionStrategy strategy)
        throws IllegalArgumentException, ResolutionException {

    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()));
    }//  www .j  a v a 2s.  c o  m

    // 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);
    }

    // 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:RestoreService.java

/**
 * execute restore process//w w  w . j av a2  s .co  m
 *
 * @throws Exception
 */
public void run() throws Exception {
    // load index
    Collection<File> bckIdxCollection = FileUtils.listFiles(repository.getMetaPath(),
            new WildcardFileFilter(bckIdxName + "*"), TrueFileFilter.INSTANCE);

    // TODO Lebeda - check only one index file

    // find files ro restore
    Set<VOBackupFile> oldFileSet = repository.collectBackupedFilesFromIndex(bckIdxCollection);
    Set<VOBackupFile> restoreFileSet = new HashSet<>();
    for (final String path : pathToRestoreList) {
        //noinspection unchecked
        restoreFileSet.addAll((Collection<VOBackupFile>) CollectionUtils.select(oldFileSet, new Predicate() {
            @Override
            public boolean evaluate(Object object) {
                VOBackupFile voBackupFile = (VOBackupFile) object;
                return StringUtils.startsWithIgnoreCase(voBackupFile.getPath(), path + File.separator);
            }
        }));
    }

    // create directory if not exists
    for (String pathForRestore : pathToRestoreList) {
        pathForRestore = changedPathToRestore(pathForRestore, targetPath);
        File baseFile = new File(pathForRestore);
        if (!baseFile.exists()) {
            //noinspection ResultOfMethodCallIgnored
            baseFile.mkdirs(); // TODO Lebeda - oetit hodnotu
        }
    }

    // find files in directory
    List<VOBackupFile> newFileList = new ArrayList<>();
    for (String pathForRestore : pathToRestoreList) {
        pathForRestore = changedPathToRestore(pathForRestore, targetPath);
        //noinspection unchecked
        final Collection<File> fileColection = FileUtils.listFiles(new File(pathForRestore),
                TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);

        for (File file : fileColection) {
            newFileList.add(new VOBackupFile(file));
        }
    }

    // delete files not in index (new or changed)
    //noinspection unchecked
    final Collection<VOBackupFile> toDelete = (Collection<VOBackupFile>) CollectionUtils.subtract(newFileList,
            restoreFileSet);
    for (VOBackupFile voBackupFile : toDelete) {
        FileUtils.forceDelete(new File(voBackupFile.getPath()));
        logger.debug("deleted file: {}", voBackupFile.getPath());
    }

    // restore files not in direcroty
    //noinspection unchecked
    final Collection<VOBackupFile> toRestore = (Collection<VOBackupFile>) CollectionUtils
            .subtract(restoreFileSet, newFileList);

    final Collection<VOBackupFile> toTime = new ArrayList<>();
    for (VOBackupFile voBackupFile : toRestore) {
        String path = changedPathToRestore(voBackupFile.getPath(), targetPath);
        if (!voBackupFile.isSymLink()) {
            if (voBackupFile.isDirectory()) {
                File dir = new File(path);
                dir.mkdirs(); // TODO Lebeda - zajistit oeten
                toTime.add(voBackupFile);
                setAdvancedAttributes(voBackupFile, dir);
            } else if (voBackupFile.getSize() == 0) {
                File file = new File(path);
                file.createNewFile(); // TODO Lebeda - oetit
                file.setLastModified(voBackupFile.getModify().getTime());
                setAdvancedAttributes(voBackupFile, file);
            } else if (StringUtils.isNotBlank(voBackupFile.getFileHash())) {
                repository.restoreFile(voBackupFile, path);
            } else {
                // TODO Lebeda - chyba
                //                LoggerTools.log("unable to restore ${it}")
            }
        }
    }

    // symlinks restore at end
    for (VOBackupFile voBackupFile : toRestore) {
        String path = changedPathToRestore(voBackupFile.getPath(), targetPath);
        if (voBackupFile.isSymLink()) {
            Files.createSymbolicLink(Paths.get(path), Paths.get(voBackupFile.getSymlinkTarget()));
        }
    }

    for (VOBackupFile voBackupFile : toTime) {
        String path = changedPathToRestore(voBackupFile.getPath(), targetPath);
        File dir = new File(path);
        dir.setLastModified(voBackupFile.getModify().getTime());
    }

}

From source file:com.pieframework.runtime.utils.azure.Cspack.java

private void stageRoleBinaries(Role role, File roleDir) {
    File roleBin = null;/* w ww  .  j  a  va  2 s  . c  om*/
    if (role.getProps().get("type") != null) {
        roleBin = new File(roleDir.getPath() + File.separatorChar);
        roleBin.mkdir();

        if (roleBin != null) {
            for (String key : role.getChildren().keySet()) {

                if (role.getChildren().get(key) instanceof Service) {
                    Service s = (Service) role.getChildren().get(key);
                    if (s.getProps().get("type") != null
                            && s.getProps().get("type").equalsIgnoreCase("application")) {
                        String query = s.getProps().get("package");
                        if (query != null) {
                            String fQuery = s.getProps().get("package");
                            String nQuery = ResourceLoader.getResourceName(fQuery);
                            String pQuery = ResourceLoader.getResourcePath(fQuery);
                            Files bootstrap = (Files) s.getResources().get(nQuery);
                            if (bootstrap != null) {
                                List<File> flist = ResourceLoader.findPath(bootstrap.getLocalPath(), pQuery);
                                if (flist.size() == 1 && flist.get(0).exists()
                                        && FilenameUtils.isExtension(flist.get(0).getPath(), "zip")) {

                                    try {
                                        Zipper.unzip(flist.get(0).getPath(), roleBin.getPath());
                                        if (role.getProps().get("type").equals("WebRole")) {
                                            //Cleanup non-bin files
                                            for (File f : roleBin.listFiles()) {
                                                if (!f.getName().equalsIgnoreCase("bin")) {
                                                    FileUtils.forceDelete(f);
                                                }
                                            }

                                            //Move contents of bin dir into the current directory
                                            File binDir = new File(
                                                    roleBin.getPath() + File.separatorChar + "bin");
                                            if (binDir.exists()) {
                                                for (File f : binDir.listFiles()) {
                                                    if (f.isDirectory()) {
                                                        FileUtils.copyDirectory(f, roleBin);
                                                    } else {
                                                        FileUtils.copyFileToDirectory(f, roleBin);
                                                    }
                                                }
                                                FileUtils.forceDelete(binDir);
                                            }
                                        }
                                    } catch (ZipException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    } catch (IOException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}