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:edu.isi.misd.scanner.network.worker.webapp.ResultsReleaseDelegate.java

private void writeRejectedServiceResponse(String id, String url, String siteName, String nodeName,
        String comments, File outputFile) throws Exception {
    // 1. Populate the rejected ServiceResponse
    ServiceResponse response = new ServiceResponse();
    ServiceResponseMetadata responseMetadata = new ServiceResponseMetadata();
    responseMetadata.setRequestID(id);/*from   w ww.  jav  a 2 s .c om*/
    responseMetadata.setRequestURL(url);
    responseMetadata.setRequestState(ServiceRequestStateType.REJECTED);
    responseMetadata.setRequestStateDetail("Reason: " + (comments.isEmpty() ? "not specified." : comments));
    responseMetadata.setRequestSiteName(siteName);
    responseMetadata.setRequestNodeName(nodeName);
    response.setServiceResponseMetadata(responseMetadata);

    // 2. Write out the result response using JAXB
    JAXBContext jaxbContext = JAXBContext.newInstance(ServiceResponse.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);
    jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
    if (outputFile.exists()) {
        try {
            FileUtils.forceDelete(outputFile);
        } catch (Exception e) {
            log.warn("Could not delete output file: " + outputFile.getCanonicalPath());
            throw e;
        }
    }
    jaxbMarshaller.marshal(response, outputFile);
}

From source file:com.zaba37.easyreader.actions.menuBar.ImageBackgroundLoader.java

private String createUnixOrMacDirectory(String mainPath) {
    mainPath = mainPath.substring(0, mainPath.lastIndexOf(File.separator));
    mainPath = mainPath + File.separator + ".TmpEasyReaderImageDirectory";
    File file = new File(mainPath);

    try {/*from  w w  w.  java  2s .c o  m*/
        if (file.exists()) {
            FileUtils.forceDelete(file);
        }

        FileUtils.forceMkdir(file);
    } catch (IOException ex) {
        Logger.getLogger(ImageBackgroundLoader.class.getName()).log(Level.SEVERE, null, ex);
    }

    return file.getPath();
}

From source file:hu.bme.mit.sette.common.tasks.RunnerProjectRunner.java

/**
 * Prepares the running of the runner project, i.e. make everything ready
 * for the execution.//from w w  w .j  ava 2  s .  c o m
 *
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
private void prepare() throws IOException {
    // delete previous outputs
    if (getRunnerProjectSettings().getRunnerOutputDirectory().exists()) {
        FileUtils.forceDelete(getRunnerProjectSettings().getRunnerOutputDirectory());
    }

    // create output directory
    FileUtils.forceMkdir(getRunnerProjectSettings().getRunnerOutputDirectory());
}

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

private void handleCellClasspathAddMvnDep(String allCode, List<String> expected) throws Exception {
    processMagicCommand(allCode);/*www. j  a  v a2 s  . c o  m*/
    String mvnDir = kernel.getTempFolder().toString() + MavenJarResolver.MVN_DIR;
    List<String> depNames = Files.walk(Paths.get(mvnDir)).map(p -> p.getFileName().toString())
            .collect(Collectors.toList());

    Optional<Message> updateMessage = EvaluatorResultTestWatcher.waitForUpdateMessage(kernel);
    String text = (String) TestWidgetUtils.getState(updateMessage.get()).get("value");

    Assertions.assertThat(kernel.getClasspath().get(0)).contains(mvnDir);
    Assertions.assertThat(expected.stream().allMatch(depNames::contains));
    Assertions.assertThat(depNames.containsAll(expected)).isTrue();
    Assertions.assertThat(expected.stream().allMatch(text::contains)).isTrue();

    Files.walk(Paths.get(mvnDir)).forEach(path -> {
        try {
            FileUtils.forceDelete(path.toFile());
        } catch (IOException e) {
            e.printStackTrace();
        }
    });
}

From source file:de.tudarmstadt.ukp.uby.resource.UbyResource.java

@SuppressWarnings("rawtypes")
@Override/*from  w  ww. ja v a 2  s. com*/
public boolean initialize(ResourceSpecifier aSpecifier, Map aAdditionalParams)
        throws ResourceInitializationException {
    if (!super.initialize(aSpecifier, aAdditionalParams)) {
        return false;
    }

    modelProvider = new ModelProviderBase<Uby>() {
        {
            setContextObject(UbyResource.this);
            setDefault(GROUP_ID, "de.tudarmstadt.ukp.uby");

            setDefault(ARTIFACT_ID, "${groupId}-model-data-${language}-${variant}");
            setDefault(LOCATION,
                    "classpath:/de/tudarmstadt/ukp/uby/data/lib/data-${language}-${variant}.properties");
            setDefault(VARIANT, "light");

            setOverride(LOCATION, modelLocation);
            setOverride(LANGUAGE, language);
            setOverride(VARIANT, variant);
        }

        @Override
        protected Uby produceResource(URL aUrl) throws IOException {
            Properties props = getAggregatedProperties();

            Properties meta = new Properties(getResourceMetaData());
            addOverride(meta, UBY_URL, url);
            addOverride(meta, UBY_DRIVER, driver);
            addOverride(meta, UBY_DIALECT, dialect);
            addOverride(meta, UBY_USERNAME, username);
            addOverride(meta, UBY_PASSWORD, password);

            // If an embedded database is to be used, extract database to disk
            if (aUrl != null) {
                UbyResource.this.getLogger().info("Using embedded database");

                File tmpFolder = File.createTempFile("uby", ".db");
                FileUtils.forceDelete(tmpFolder);
                FileUtils.forceMkdir(tmpFolder);
                tmpFolder.deleteOnExit();

                File tmpDbFile = new File(tmpFolder, DATABASE_FILE);
                tmpDbFile.deleteOnExit();

                UbyResource.this.getLogger().info("Extracting embedded database to [" + tmpDbFile + "]");

                InputStream is = null;
                OutputStream os = null;
                try {
                    // FIXME should probably just do nothing if database file is not compressed
                    // and if the URL already points to the file system.
                    is = CompressionUtils.getInputStream(aUrl.toString(), aUrl.openStream());

                    os = new FileOutputStream(tmpDbFile);
                    IOUtils.copyLarge(is, os);
                } finally {
                    IOUtils.closeQuietly(os);
                    IOUtils.closeQuietly(is);
                }

                // Well... we currently only support H2 as embedded DB. If somebody wants to
                // use a different embedded DB, we'll have to implement something more
                // generic here.
                meta.setProperty(UBY_URL, "jdbc:h2:" + tmpFolder.toURI().toURL().toString() + "/" + DATABASE
                        + ";TRACE_LEVEL_FILE=0");
            } else {
                getLogger().info("Connecting to server...");
            }

            getLogger().info("uby.url: " + meta.getProperty(UBY_URL));
            getLogger().info("uby.driver: " + meta.getProperty(UBY_DRIVER));
            getLogger().info("uby.dialect: " + meta.getProperty(UBY_DIALECT));
            getLogger().info("uby.username: " + meta.getProperty(UBY_USERNAME));
            getLogger().info("uby.password: "
                    + (StringUtils.isNotEmpty(meta.getProperty(UBY_PASSWORD)) ? "<set>" : "<unset>"));

            DBConfig dbConfig = new DBConfig(meta.getProperty(UBY_URL), meta.getProperty(UBY_DRIVER),
                    meta.getProperty(UBY_DIALECT), meta.getProperty(UBY_USERNAME),
                    meta.getProperty(UBY_PASSWORD), false);

            try {
                return new Uby(dbConfig);
            } catch (IllegalArgumentException e) {
                throw new IOException(e);
            }
        }
    };

    return true;
}

From source file:net.paissad.waqtsalat.utils.DownloadHelper.java

/**
 * <p>/*ww w .ja v  a  2 s. c  om*/
 * Download a resource from the specified url and save it to the specified
 * file.
 * </p>
 * <b>Note</b>: If you plan to cancel the download at any time, then this
 * method should be embed into it's own thread.
 * <p>
 * <b>Example</b>:
 * 
 * <pre>
 *  final DownloadHelper downloader = new DownloadHelper();
 *  Thread t = new Thread() {
 *      public void run() {
 *          try {
 *              downloader.download("http://domain.com/file.zip", new File("/tmp/output.zip"));
 *          } catch (Exception e) {
 *              ...
 *          }
 *      }
 *  };
 *  t.start();
 *  // Waits 3 seconds and then cancels the download.
 *  Thread.sleep(3 * 1000L);
 *  downloader.cancel();
 *  ...
 * </pre>
 * 
 * </p>
 * 
 * @param url
 *            - The url of the file to download.
 * @param file
 *            - The downloaded file (where it will be stored).
 * @throws IOException
 * @throws HttpException
 */
public void download(final String url, final File file) throws HttpException, IOException {

    GetMethod method = null;
    InputStream responseBody = null;
    OutputStream out = null;

    try {
        final boolean fileExisted = file.exists();

        HttpClient client = new HttpClient();
        method = new GetMethod(url);
        method.setFollowRedirects(true);
        method.setRequestHeader("User-Agent", WSConstants.WS_USER_AGENT);
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));
        method.getParams().setParameter(HttpMethodParams.WARN_EXTRA_INPUT, Boolean.TRUE);

        // Execute the method.
        int responseCode = client.executeMethod(method);
        if (responseCode != HttpStatus.SC_OK) {
            logger.error("Http method failed : {}.", method.getStatusLine().toString());
        }

        // Read the response body.
        responseBody = method.getResponseBodyAsStream();

        // Let's try to compute the amount of total bytes of the file to
        // download.
        URL u = new URL(url);
        URLConnection urlc = u.openConnection();
        this.totalBytes = urlc.getContentLength();
        long lastModified = urlc.getLastModified();

        // The OutputStream for the 'downloaded' file.
        out = new BufferedOutputStream(new FileOutputStream(file));

        this.updateState(DownloadState.IN_PROGRESS);

        byte[] data = new byte[BUFFER_SIZE];
        int length;
        while ((length = responseBody.read(data, 0, BUFFER_SIZE)) != -1 && !isCancelled) {
            out.write(data, 0, length);
            this.bytesDownloaded += length;
            setChanged();
            notifyObservers(getBytesDownloaded());
        }

        if (isCancelled) {
            this.updateState(DownloadState.CANCELED);
            logger.info("The download has been cancelled.");

        } else {
            // The download was not cancelled.
            out.flush();
            if (lastModified > 0) {
                file.setLastModified(lastModified);
            }

            if (bytesDownloaded != totalBytes) {
                logger.warn("The expected bytes to download is {}, but got {}.", getTotalBytes(),
                        getBytesDownloaded());
                this.updateState(DownloadState.ERROR);
            }

            this.updateState(DownloadState.FINISHED);
            logger.info("Download of '{}' finished successfully.", url);
        }

        // If the file did not exist before the download but does exit now,
        // we must remove it if an error occurred or if the download was
        // cancelled.
        if (getState() == DownloadState.CANCELED || getState() == DownloadState.ERROR) {
            if (!fileExisted && file.exists()) {
                FileUtils.forceDelete(file);
            }
        }

    } catch (HttpException he) {
        this.updateState(DownloadState.ERROR);
        logger.error("Fatal protocol violation : " + he);
        throw new HttpException("Error while downloading from the url '" + url + "'", he);

    } catch (IOException ioe) {
        this.updateState(DownloadState.ERROR);
        logger.error("Fatal transport error : " + ioe);
        throw new IOException(ioe);

    } finally {
        if (method != null)
            method.releaseConnection();
        if (responseBody != null)
            responseBody.close();
        if (out != null)
            out.close();
    }
}

From source file:eu.hydrologis.jgrass.geonotes.actions.OpenSelectedEntryAction.java

/**
 * @param name/*from  w  w  w  . j  a  v a  2s . c o  m*/
 * @param geonotesHandler
 * @param drawingList
 * @param path
 */
private void openImage(final String name, final GeonotesHandler geonotesHandler,
        final List<DressedStroke> drawingList, final File file) {
    final Shell shell = new Shell(SWT.SHELL_TRIM);
    shell.setText("Editing of " + name); //$NON-NLS-1$
    shell.setLayout(new GridLayout());

    Composite editorComposite = new Composite(shell, SWT.None);
    editorComposite.setLayout(new FillLayout());
    editorComposite.setLayoutData(
            new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));
    ImageData imgD = new ImageData(file.getAbsolutePath());
    final Image img = new Image(shell.getDisplay(), imgD);
    int width = img.getBounds().width;
    int height = img.getBounds().height;
    simpleSWTImageEditor = new SimpleSWTImageEditor(editorComposite, SWT.None, drawingList, img,
            new Point(1000, 1000), true, true);

    Composite buttonComposite = new Composite(shell, SWT.None);
    buttonComposite.setLayout(new RowLayout());
    buttonComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL));
    Button okButton = new Button(buttonComposite, SWT.BORDER | SWT.PUSH);
    okButton.setText("Save");
    okButton.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            try {
                if (simpleSWTImageEditor.isImageGotRotated()) {
                    ImageData rotatedImage = simpleSWTImageEditor.getRotatedImageData();
                    ImageLoader imageLoader = new ImageLoader();
                    imageLoader.data = new ImageData[] { rotatedImage };
                    File tempFile = File.createTempFile("imageeditor", "");
                    if (file.getName().toLowerCase().endsWith("jpg")) {
                        imageLoader.save(tempFile.getAbsolutePath(), SWT.IMAGE_JPEG);
                    } else if (file.getName().toLowerCase().endsWith("png")) {
                        imageLoader.save(tempFile.getAbsolutePath(), SWT.IMAGE_PNG);
                    }

                    geonotesHandler.deleteMedia(name);
                    geonotesHandler.addMedia(tempFile, name);

                    FileUtils.forceDelete(tempFile);
                }
                ArrayList<DressedStroke> drawing = (ArrayList<DressedStroke>) simpleSWTImageEditor.getDrawing();
                geonotesHandler.setMediaDrawings(drawing, name);

                simpleSWTImageEditor.dispose();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            shell.dispose();
        }
    });
    Button cancelButton = new Button(buttonComposite, SWT.BORDER | SWT.PUSH);
    cancelButton.setText("Cancel");
    cancelButton.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            simpleSWTImageEditor.dispose();
            shell.dispose();
        }
    });

    Monitor primary = Display.getDefault().getPrimaryMonitor();
    Rectangle bounds = primary.getBounds();
    Rectangle rect = shell.getBounds();
    int x = bounds.x + (bounds.width - rect.width) / 2;
    int y = bounds.y + (bounds.height - rect.height) / 2;
    shell.setLocation(x, y);
    shell.setSize(600, 400);
    shell.open();
}

From source file:net.nicholaswilliams.java.licensing.encryption.TestKeyFileUtilities.java

@Test
public void testPublicKeyEncryption01() throws Throwable {
    File file = new File("testPublicKeyEncryption01.key");

    if (file.exists())
        FileUtils.forceDelete(file);

    PublicKey publicKey = KeyPairGenerator.getInstance(KeyFileUtilities.keyAlgorithm).generateKeyPair()
            .getPublic();/*from  w  w  w . ja  v  a 2  s .c  o  m*/

    KeyFileUtilities.writeEncryptedPublicKey(publicKey, file, "myTestPassword01".toCharArray());

    PublicKey publicKey2 = KeyFileUtilities.readEncryptedPublicKey(file, "myTestPassword01".toCharArray());

    assertNotNull("The key should not be null.", publicKey2);
    assertFalse("The objects should not be the same.", publicKey == publicKey2);
    assertEquals("The keys should be the same.", publicKey, publicKey2);

    FileUtils.forceDelete(file);
}

From source file:com.asakusafw.testdriver.compiler.util.DeploymentUtil.java

private static void prepareDestination(File destination) throws IOException {
    if (destination.exists()) {
        FileUtils.forceDelete(destination);
    }/*  w  w w  . j  av  a  2  s.c  om*/
    File parent = destination.getAbsoluteFile().getParentFile();
    if (parent.mkdirs() == false && parent.exists() == false) {
        throw new IOException(MessageFormat.format("failed to create directory: {0}", destination));
    }
}

From source file:com.netflix.spinnaker.halyard.config.config.v1.HalconfigParser.java

/**
 * Deletes all files in the staging directory that are not referenced in the hal config.
 *//*from  ww w .  j  a  va2  s .co m*/
public void cleanLocalFiles(Path stagingDirectoryPath) {
    if (!GlobalApplicationOptions.getInstance().isUseRemoteDaemon()) {
        return;
    }
    Halconfig halconfig = getHalconfig();
    Set<String> referencedFiles = new HashSet<String>();
    Consumer<Node> fileFinder = n -> referencedFiles.addAll(n.localFiles().stream().map(f -> {
        try {
            f.setAccessible(true);
            return (String) f.get(n);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Failed to clean staging directory: " + e.getMessage(), e);
        } finally {
            f.setAccessible(false);
        }
    }).filter(Objects::nonNull).collect(Collectors.toSet()));
    halconfig.recursiveConsume(fileFinder);

    Set<String> existingStagingFiles = ((List<File>) FileUtils.listFiles(stagingDirectoryPath.toFile(),
            TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE)).stream().map(f -> f.getAbsolutePath())
                    .collect(Collectors.toSet());

    existingStagingFiles.removeAll(referencedFiles);

    try {
        for (String f : existingStagingFiles) {
            FileUtils.forceDelete(new File(f));
        }
    } catch (IOException e) {
        throw new HalException(FATAL, "Failed to clean staging directory: " + e.getMessage(), e);
    }
}