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

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

Introduction

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

Prototype

public static void moveFile(File srcFile, File destFile) throws IOException 

Source Link

Document

Moves a file.

Usage

From source file:nl.mpi.lamus.workspace.exporting.implementation.LamusVersioningHandler.java

/**
 * @see VersioningHandler#moveOrCopyFileToOrphansFolder(nl.mpi.lamus.workspace.model.Workspace, nl.mpi.lamus.workspace.model.WorkspaceNode)
 *//*from w w w.  ja v a2 s  .  co m*/
@Override
public URL moveOrCopyFileToOrphansFolder(Workspace workspace, WorkspaceNode nodeToMove, boolean copy) {

    File orphanOldLocation = null;

    File archiveLocation = null;

    //if file was not in the archive already, then it will be moved from its workspace location
    //if file is in the archive and is a resource, then it will be moved from its archive location
    //if file is metadata, then it will be moved from its workspace location; if it is also in the archive, then it has to be removed from there

    if (nodeToMove.getArchiveURI() != null) {
        CorpusNode archiveNode = corpusStructureProvider.getNode(nodeToMove.getArchiveURI());
        archiveLocation = nodeResolver.getLocalFile(archiveNode);
    }

    if (nodeToMove.getArchiveURI() == null || nodeUtil.isNodeMetadata(nodeToMove)) {
        URL orphanOldLocationUrl = nodeToMove.getWorkspaceURL();
        orphanOldLocation = new File(orphanOldLocationUrl.getPath());
        if (archiveFileLocationProvider.isFileInOrphansDirectory(orphanOldLocation)) {
            logger.info("File already in orphans directory: " + orphanOldLocation.getAbsolutePath());
            return orphanOldLocationUrl;
        }
    }

    if (orphanOldLocation == null) {
        orphanOldLocation = archiveLocation;
    }

    String filename;
    if (orphanOldLocation != null) {
        filename = orphanOldLocation.getName();
    } else {
        throw new IllegalStateException("No valid file location was found.");
    }

    File orphanNewLocation;
    try {
        File orphansDirectory = archiveFileLocationProvider
                .getOrphansDirectory(workspace.getTopNodeArchiveURL().toURI());
        if (!archiveFileHelper.canWriteTargetDirectory(orphansDirectory)) {
            logger.error("Problem with write permissions in target directory " + orphansDirectory);
            return null;
        }
        orphanNewLocation = archiveFileHelper.getFinalFile(orphansDirectory, filename);
    } catch (URISyntaxException ex) {
        String errorMessage = "Error retrieving archive location of node " + workspace.getTopNodeArchiveURI();
        logger.error(errorMessage, ex);
        return null;
    }

    try {
        if (!copy) {
            FileUtils.moveFile(orphanOldLocation, orphanNewLocation);
            if (archiveLocation != null) {
                Files.deleteIfExists(archiveLocation.toPath());
            }
        } else {
            FileUtils.copyFile(orphanOldLocation, orphanNewLocation);
        }

    } catch (IOException ex) {
        logger.error("File couldn't be " + (copy ? "copied" : "moved") + " from [" + orphanOldLocation
                + "] to [" + orphanNewLocation + "]", ex);
        return null;
    }

    URL newFileUrl = null;
    try {
        newFileUrl = orphanNewLocation.toURI().toURL();
    } catch (MalformedURLException ex) {
        logger.warn((copy ? "Copied" : "Moved") + " file location is not a URL", ex);
    }

    return newFileUrl;
}

From source file:nl.mpi.lamus.workspace.exporting.implementation.LamusVersioningHandler.java

private URL moveFileTo(WorkspaceNode nodeToMove, boolean toDelete) {

    CorpusNode archiveNode = corpusStructureProvider.getNode(nodeToMove.getArchiveURI());
    File currentFile = nodeResolver.getLocalFile(archiveNode);

    File targetDirectory;/*from  w  w  w  .j a v a  2  s  .  co  m*/
    if (toDelete) {
        targetDirectory = archiveFileHelper.getDirectoryForDeletedNode(nodeToMove.getWorkspaceID());
    } else { // node is replaced
        targetDirectory = archiveFileHelper.getDirectoryForReplacedNode(nodeToMove.getWorkspaceID());
    }

    if (!archiveFileHelper.canWriteTargetDirectory(targetDirectory)) {
        logger.error("Problem with write permissions in target directory " + targetDirectory);
        return null;
    }

    File targetFile = archiveFileHelper.getTargetFileForReplacedOrDeletedNode(targetDirectory,
            handleParser.stripAndValidateHandleIfPrefixIsKnown(nodeToMove.getArchiveURI()), currentFile);

    try {
        FileUtils.moveFile(currentFile, targetFile);
    } catch (IOException ex) {
        logger.error("File couldn't be moved from [" + currentFile + "] to [" + targetFile + "]", ex);
        return null;
    }

    URL movedFileURL = null;
    try {
        movedFileURL = targetFile.toURI().toURL();
    } catch (MalformedURLException ex) {
        logger.warn("Moved file location is not a URL", ex);
    }

    return movedFileURL;
}

From source file:nl.umcg.westrah.binarymetaanalyzer.BinaryMetaAnalysis.java

public void run() throws IOException {
    initialize();//from   ww  w  . ja  va  2 s  .  co  m
    loadProbeAnnotation();

    String outdir = settings.getOutput();
    if (usetmp) {
        outdir = tempDir;
    }

    System.out.println("Placing output here: " + outdir);
    outdir = Gpio.formatAsDirectory(outdir);
    Gpio.createDir(outdir);

    System.out.println(
            "Permutations: " + settings.getStartPermutations() + " until " + settings.getNrPermutations());

    String zscoretableheader = null;
    if (settings.isMakezscoretable()) {
        StringBuilder builder = new StringBuilder();
        builder.append("SNP\tAlleles\tAlleleAssessed");
        for (int t = 0; t < traitList.length; t++) {
            builder.append("\t").append(traitList[t].getMetaTraitName()).append("_")
                    .append(traitList[t].getAnnotation());
        }
        zscoretableheader = builder.toString();
    }

    int availableProcessors = Runtime.getRuntime().availableProcessors();
    int cores = settings.getNrThreads();
    if (cores < 1) {
        cores = 1;
    } else if (cores > availableProcessors) {
        cores = availableProcessors;
    }

    System.out.println("Will try to make use of " + cores + " CPU cores");
    System.out.println();

    HashSet<QTLPair> prevSet = null;
    for (int permutation = settings.getStartPermutations(); permutation <= settings
            .getNrPermutations(); permutation++) {
        // load probe annotation and index
        // this particular probe annotation can take multiple probes for a single location into account.

        HashSet<QTLPair> set = new HashSet<>();

        Descriptives.initializeZScoreToPValue();

        // re-intialize for each permutation, just to be sure
        if (permutation > settings.getStartPermutations()) {
            initialize();
            System.out.println("Loading probe annotation from: " + settings.getProbetranslationfile());
            loadProbeAnnotation();
            if (traitList.length == 0) {
                System.err.println("Error: no annotation loaded.");
                System.exit(-1);
            }
        }
        //         clearResultsBuffer();

        // create dataset objects
        System.out.println("Running permutation " + permutation);
        datasets = new BinaryMetaAnalysisDataset[settings.getDatasetlocations().size()];

        System.out.println("Loading datasets");
        for (int d = 0; d < datasets.length; d++) {
            datasets[d] = new BinaryMetaAnalysisDataset(settings.getDatasetlocations().get(d),
                    settings.getDatasetnames().get(d), settings.getDatasetPrefix().get(d), permutation,
                    settings.getDatasetannotations().get(d), probeAnnotation,
                    settings.getFeatureOccuranceScaleMaps().get(d));
        }

        System.out.println("Loaded " + datasets.length + " datasets");

        // create meta-analysis SNP index. have to recreate this every permutation,
        // since the order of SNPs is generated at random.
        System.out.println("Creating SNP index");
        createSNPIndex(outdir);
        System.out.println("Total of " + snpIndex.length + " SNPs");

        System.out.println("Creating probe index");
        createProbeIndex(outdir);
        System.out.println("Total of " + probeIndex.length + " probes");

        // make index of snp/probe combinations, if any specified
        createSNPProbeCombos(outdir);

        // load SNP annotation for SNPs present in dataset
        //         if (snpChr == null) {
        System.out.println("Loading SNP annotation from " + settings.getSNPAnnotationFile());
        loadSNPAnnotation();
        //         }

        // run analysis
        System.out.println("Type of analysis: " + settings.getAnalysisType());
        System.out.println("Cis-window: " + settings.getCisdistance());
        System.out.println("Trans-window: " + settings.getTransdistance());

        TextFile zscoreTableTf = null;
        TextFile zscoreTableTfNrSamples = null;

        if (settings.isMakezscoretable()) {

            String tableoutfile = outdir + "ZScoreMatrix-Permutation" + permutation + ".txt.gz";
            String tableoutfileNrSamples = outdir + "ZScoreMatrixNrSamples-Permutation" + permutation
                    + ".txt.gz";
            if (permutation == 0) {
                tableoutfile = outdir + "ZScoreMatrix.txt.gz";
                tableoutfileNrSamples = outdir + "ZScoreMatrixNrSamples.txt.gz";
            }
            System.out.println("Writing z-score table: " + tableoutfile);
            zscoreTableTf = new TextFile(tableoutfile, TextFile.W, 10 * 1048576);
            zscoreTableTfNrSamples = new TextFile(tableoutfileNrSamples, TextFile.W, 10 * 1048576);

            // write header
            zscoreTableTf.writeln(zscoretableheader);
            zscoreTableTfNrSamples.writeln(zscoretableheader);
        }

        ExecutorService threadPool = Executors.newFixedThreadPool(cores);
        CompletionService<Triple<ArrayList<QTL>, String, String>> pool = new ExecutorCompletionService<Triple<ArrayList<QTL>, String, String>>(
                threadPool);

        maxSavedPvalue = -Double.MAX_VALUE;
        locationToStoreResult = 0;
        bufferHasOverFlown = false;
        System.out.println("Max P: " + maxSavedPvalue + "\tLocationToStoreResult: " + locationToStoreResult);

        System.out.println("Starting meta-analysis");
        ProgressBar pb = new ProgressBar(snpList.length);
        int returned = 0;
        ArrayList<Future> futures = new ArrayList<>();
        for (int snp = 0; snp < snpList.length; snp++) {
            // this can go in different threads..
            boolean outputallzscores = true;
            if (permutation > 0) {
                outputallzscores = fullpermutationoutput;
            }
            BinaryMetaAnalysisTask t = new BinaryMetaAnalysisTask(settings, probeAnnotation, datasets, snpIndex,
                    snpList, snpChr, snpPositions, probeIndex, snpprobeCombos, traitMap, traitList, snp, DEBUG,
                    outputallzscores);
            futures.add(pool.submit(t));
        }

        // give the threadpool the signal to shutdown
        threadPool.shutdown();

        int addcalled = 0;
        while (returned < snpList.length) {
            try {
                Future<Triple<ArrayList<QTL>, String, String>> threadfuture = pool.take();
                if (threadfuture != null) {
                    Triple<ArrayList<QTL>, String, String> result = threadfuture.get();

                    for (QTL q : result.getLeft()) {
                        if (!DEBUG) {
                            addEQTL(q);
                        } else {

                            //                        int snpid = q.getSNPId();
                            //                        MetaQTL4MetaTrait trait = q.getMetaTrait();

                            //                        QTLPair combo = new QTLPair();
                            //                        combo.snpid = snpid;
                            //                        combo.trait = trait;
                            //                        set.add(combo);

                        }

                        addcalled++;
                    }
                    if (settings.isMakezscoretable()) {
                        zscoreTableTf.writeln(result.getMiddle());

                        zscoreTableTfNrSamples.writeln(result.getRight());
                    }
                    result = null;
                    returned++;
                    pb.iterate();
                }
                threadfuture = null;
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        pb.close();

        if (DEBUG) {
            if (prevSet != null) {
                // compare sets
                TextFile tf = new TextFile(outdir + "debug-p" + permutation + ".txt", TextFile.W);
                for (QTLPair p : prevSet) {
                    if (!set.contains(p)) {
                        tf.writeln(snpList[p.snpid] + "\t" + p.trait.getMetaTraitName());
                    }
                }
                tf.close();
            }
            prevSet = set;
        }

        System.out.println("Snps returned: " + returned + "\tNr of snps submitted: " + snpList.length
                + "\tNr of eQTLs evaluated: " + addcalled);
        System.out.println("Max P: " + maxSavedPvalue + "\tLocationToStoreResult: " + locationToStoreResult);

        if (settings.isMakezscoretable()) {
            zscoreTableTf.close();
            zscoreTableTfNrSamples.close();

            if (usetmp) {

                String filename = "ZScoreMatrix-Permutation" + permutation + ".txt.gz";
                if (permutation == 0) {
                    filename = "ZScoreMatrix.txt.gz";
                }
                File source = new File(tempDir + filename);
                File dest = new File(settings.getOutput() + filename);
                if (dest.exists()) {
                    System.out.println(
                            "Destination file: " + dest.getAbsolutePath() + " exists already.. Deleting!");
                    dest.delete();
                }
                System.out.println(
                        "Moving file: " + tempDir + filename + " --> " + settings.getOutput() + filename);
                FileUtils.moveFile(source, dest);

                filename = "ZScoreMatrixNrSamples-Permutation" + permutation + ".txt.gz";
                if (permutation == 0) {
                    filename = "ZScoreMatrixNrSamples.txt.gz";
                }
                source = new File(tempDir + filename);
                dest = new File(settings.getOutput() + filename);
                if (dest.exists()) {
                    System.out.println(
                            "Destination file: " + dest.getAbsolutePath() + " exists already.. Deleting!");
                    dest.delete();
                }
                System.out.println(
                        "Moving file: " + tempDir + filename + " --> " + settings.getOutput() + filename);
                FileUtils.moveFile(source, dest);
            }
        }

        for (BinaryMetaAnalysisDataset dataset : datasets) {
            dataset.close();
        }

        if (!DEBUG) {
            writeBuffer(outdir, permutation);

        }
    }
    if (usetmp) {
        // move remaining contents of tmp dir to final directory
        File source = new File(tempDir);
        File dest = new File(settings.getOutput());
        FileUtils.copyDirectory(source, dest);
        FileUtils.cleanDirectory(source);
    }
}

From source file:nl.umcg.westrah.binarymetaanalyzer.BinaryMetaAnalysis.java

private void writeBuffer(String outdir, int permutation) throws IOException {

    // sort the finalbuffer for a last time
    if (locationToStoreResult != 0) {
        Arrays.parallelSort(finalEQTLs, 0, locationToStoreResult);
    }/*from w w  w . j a va2 s  .c o m*/

    String outfilename = outdir + "eQTLs.txt.gz";
    FileFormat outformat = FileFormat.LARGE;
    if (permutation > 0) {
        outfilename = outdir + "PermutedEQTLsPermutationRound" + permutation + ".txt.gz";
        if (!fullpermutationoutput) {
            outformat = FileFormat.REDUCED;
        }
    }

    String tab = "\t";
    String newline = "\n";

    TextFile output = new TextFile(outfilename, TextFile.W, 10 * 1048576);

    String header = "PValue\t" + "SNPName\t" + "SNPChr\t" + "SNPChrPos\t" + "ProbeName\t" + "ProbeChr\t"
            + "ProbeCenterChrPos\t" + "CisTrans\t" + "SNPType\t" + "AlleleAssessed\t" + "OverallZScore\t"
            + "DatasetsWhereSNPProbePairIsAvailableAndPassesQC\t" + "DatasetsZScores\t" + "DatasetsNrSamples\t"
            + "IncludedDatasetsMeanProbeExpression\t" + "IncludedDatasetsProbeExpressionVariance\t"
            + "HGNCName\t" + "IncludedDatasetsCorrelationCoefficient\t" + "Meta-Beta (SE)\t" + "Beta (SE)\t"
            + "FoldChange";
    if (outformat.equals(FileFormat.REDUCED)) {
        header = "PValue\tSNP\tProbe\tGene\tAlleles\tAlleleAssessed\tZScore";
    }
    output.writeln(header);
    // PValue   SNPName   SNPChr   SNPChrPos   ProbeName   ProbeChr   ProbeCenterChrPos   CisTrans   SNPType   AlleleAssessed   OverallZScore   DatasetsWhereSNPProbePairIsAvailableAndPassesQC   DatasetsZScores   DatasetsNrSamples   IncludedDatasetsMeanProbeExpression   IncludedDatasetsProbeExpressionVariance   HGNCName   IncludedDatasetsCorrelationCoefficient   Meta-Beta (SE)   Beta (SE)   FoldChange   FDR

    DecimalFormat dformat = new DecimalFormat("###.####", new DecimalFormatSymbols(Locale.US));
    DecimalFormat pformat = new DecimalFormat("###.########", new DecimalFormatSymbols(Locale.US));
    DecimalFormat smallpFormat = new DecimalFormat("0.####E0", new DecimalFormatSymbols(Locale.US));

    int ctr = 0;
    for (int i = 0; i < settings.getFinalEQTLBufferMaxLength(); i++) {
        if (finalEQTLs[i] != null) {
            ctr++;
        }
    }
    int totalctr = 0;
    for (int i = 0; i < finalEQTLs.length; i++) {
        if (finalEQTLs[i] != null) {
            totalctr++;
        }
    }
    System.out.println("There are " + ctr + " results in the buffer to write. " + totalctr
            + " QTLs are in memory at the moment.");
    ProgressBar pb = new ProgressBar(ctr, "Writing: " + outfilename);

    String cistr = "Cis";
    String transtr = "Trans";
    String greyz = "Greyzone";

    for (int i = 0; i < settings.getFinalEQTLBufferMaxLength(); i++) {
        QTL q = finalEQTLs[i];
        if (q != null) {
            //            StringBuilder sb = new StringBuilder(4096);
            if (outformat.equals(FileFormat.LARGE)) {
                if (q.getPvalue() < 1E-4) {
                    output.append(smallpFormat.format(q.getPvalue()));
                } else {
                    output.append(pformat.format(q.getPvalue()));
                }
                output.append(tab);
                int snpId = q.getSNPId();
                output.append(snpList[snpId]);
                output.append(tab);
                output.append(snpChr[snpId]);
                output.append(tab);
                output.append("" + snpPositions[snpId]);
                output.append(tab);
                MetaQTL4MetaTrait t = q.getMetaTrait();
                output.append(t.getMetaTraitName());
                output.append(tab);
                output.append(t.getChr());
                output.append(tab);
                output.append("" + t.getChrMidpoint());
                output.append(tab);
                int dist = Math.abs(t.getChrMidpoint() - snpPositions[snpId]);
                boolean sameChr = t.getChr().equals(snpChr[snpId]);
                if (sameChr && dist < settings.getCisdistance()) {
                    output.append(cistr);
                } else if (sameChr && dist < settings.getTransdistance()) {
                    output.append(greyz);
                } else {
                    output.append(transtr);
                }

                output.append(tab);
                output.append(q.getAlleles());
                output.append(tab);
                output.append(q.getAlleleAssessed());
                output.append(tab);
                output.append(dformat.format(q.getZscore()));

                float[] datasetZScores = q.getDatasetZScores();
                String[] dsBuilder = new String[datasets.length];
                String[] dsNBuilder = new String[datasets.length];
                String[] dsZBuilder = new String[datasets.length];

                for (int d = 0; d < datasetZScores.length; d++) {

                    if (!Float.isNaN(datasetZScores[d])) {
                        String str = dformat.format(datasetZScores[d]);

                        dsBuilder[d] = settings.getDatasetnames().get(d);
                        dsNBuilder[d] = "" + q.getDatasetSampleSizes()[d];
                        dsZBuilder[d] = str;
                    } else {
                        dsBuilder[d] = "-";
                        dsNBuilder[d] = "-";
                        dsZBuilder[d] = "-";
                    }
                }

                output.append(tab);
                output.append(Strings.concat(dsBuilder, Strings.semicolon));

                output.append(tab);
                output.append(Strings.concat(dsZBuilder, Strings.semicolon));

                output.append(tab);
                output.append(Strings.concat(dsNBuilder, Strings.semicolon));
                output.append("\t-\t-\t");

                output.append(t.getAnnotation());
                output.append("\t-\t-\t-\t-");
                output.append(newline);

            } else {
                //               header = "PValue\tSNP\tProbe\tGene\tAlleles\tAlleleAssessed\tZScore";

                int snpId = q.getSNPId();
                MetaQTL4MetaTrait t = q.getMetaTrait();

                if (q.getPvalue() < 1E-4) {
                    output.append(smallpFormat.format(q.getPvalue()));
                } else {
                    output.append(pformat.format(q.getPvalue()));
                }
                output.append(tab);
                output.append(snpList[snpId]);
                output.append(tab);
                output.append(t.getMetaTraitName());
                output.append(tab);
                output.append(t.getAnnotation());
                output.append(tab);
                output.append(q.getAlleles());
                output.append(tab);
                output.append(q.getAlleleAssessed());
                output.append(tab);
                output.append(dformat.format(q.getZscore()));
                output.append(newline);
            }

            pb.iterate();
        }
        finalEQTLs[i] = null; // trash it immediately
    }

    pb.close();
    output.close();
    finalEQTLs = null; // ditch the whole resultset

    if (usetmp) {

        String filename = "eQTLs.txt.gz";
        if (permutation > 0) {
            filename = "PermutedEQTLsPermutationRound" + permutation + ".txt.gz";
        }
        File source = new File(tempDir + filename);
        File dest = new File(settings.getOutput() + filename);
        if (dest.exists()) {
            System.out.println("Destination file: " + dest.getAbsolutePath() + " exists already.. Deleting!");
            dest.delete();
        }
        System.out.println("Moving file: " + tempDir + filename + " --> " + settings.getOutput() + filename);
        FileUtils.moveFile(source, dest);

    }

    System.out.println("Done.");
}

From source file:no.dusken.aranea.admin.control.UploadFileController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object object,
        BindException bindException) throws Exception {

    String url = ServletRequestUtils.getRequiredStringParameter(request, "imageUrl");

    // get the uploaded file
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile file = multipartRequest.getFile("file");
    if (file == null) {
        // There is no file. Exit
        log.error("Could not extract file from request");
        return new ModelAndView(new EmptyView());
    }/* w  ww .ja  va2  s  . c  om*/
    // transfer the file to a temporary location
    String originalName = file.getOriginalFilename();
    log.debug("Got file: {}", originalName);
    File tmpFile = new File(resourceDir + "/images/tmp/" + originalName);
    tmpFile.getParentFile().mkdirs();
    file.transferTo(tmpFile);

    // move the file to the final destination
    File newFile = new File(resourceDir + "/images/" + url);
    newFile.getParentFile().mkdirs();
    FileUtils.moveFile(tmpFile, newFile);
    // SUCCESS!
    response.setStatus(200);

    return new ModelAndView(new EmptyView());
}

From source file:ome.io.bioformats.BfPyramidPixelBuffer.java

/**
 * This method should never exit without releasing the lock.
 *///from  www .  j  a v a2  s  .  co m
private void closeWriter() throws IOException {
    try {
        if (writer != null) {
            writer.close();
            writer = null;
        }
    } finally {
        try {
            if (writerFile != null) {
                try {
                    FileUtils.moveFile(writerFile, readerFile);
                } finally {
                    writerFile = null;
                }
            }
        } finally {
            releaseLock();
        }
    }
}

From source file:omero.util.TempFileManager.java

/**
 * Command-line interface to the global {@link TempFileManager} instance (
 * {@link #manger}). Valid arguments: "--debug", "clean", "dir", and for
 * testing, "lock"/*from  w ww .  j  a v a 2  s.c  om*/
 */
public static void main(String[] _args) throws IOException {
    List<String> args = Arrays.asList(_args);

    if (args.size() > 0) {

        // Debug may already be activated. See static block above.
        if (args.contains("--debug") && !System.getenv().containsKey("DEBUG")) {
            ConsoleAppender console = new ConsoleAppender();
            console.setName("System.err");
            console.setTarget(ConsoleAppender.SYSTEM_ERR);
            console.setLayout(new SimpleLayout());
            console.activateOptions();
            Logger logger = Logger.getLogger("omero");
            logger.addAppender(console);
            logger.setLevel(Level.DEBUG);
            logger.addAppender(console);
        }

        if (args.contains("clean")) {
            manager.cleanUserDir();
            System.exit(0);
        } else if (args.contains("dir")) {
            System.out.println(manager.getTempDir().getAbsolutePath());
            System.exit(0);
        } else if (args.contains("test")) {
            File test = new File("/tmp/test");
            if (test.exists()) {
                test.delete();
                System.out.println("Deleted test");
            }
            File f = create_path();
            System.out.println(f.getAbsolutePath());
            f.deleteOnExit();
            FileUtils.writeStringToFile(f, "test");
            FileUtils.moveFile(f, test);
            System.exit(0);
        } else if (args.contains("lock")) {
            System.out.println("Locking " + manager.getTempDir().getAbsolutePath());
            System.out.println("Waiting on user input...");
            System.in.read();
            System.exit(0);
        }
    }
    System.err.println("Usage: TempFileManager clean");
    System.err.println("   or: TempFileManager dir");
    System.exit(2);

}

From source file:org.ado.biblio.desktop.db.DatabaseConnectionTest.java

public void setUp() throws Exception {
    FileUtils.deleteQuietly(DATABASE_FILE_TMP);
    if (DATABASE_FILE.exists()) {
        FileUtils.moveFile(DATABASE_FILE, DATABASE_FILE_TMP);
    }/*from   ww w . jav a  2 s .c  o m*/
    Locale.setDefault(Locale.ENGLISH);
}

From source file:org.ado.biblio.desktop.db.DatabaseConnectionTest.java

@After
public void tearDown() throws Exception {
    FileUtils.deleteQuietly(DATABASE_FILE);
    if (DATABASE_FILE_TMP.exists()) {
        FileUtils.moveFile(DATABASE_FILE_TMP, DATABASE_FILE);
    }//  ww w .  j a  v a 2s  .  c o m
}

From source file:org.ado.picasa.Main.java

private static void downloadAlbum(FirefoxDriver driver, String album, File outputDir) {
    try {//from w  ww . ja v  a 2  s  .  c  om
        final String albumName = getAlbumName(album);
        System.out.println(String.format("> album name: %s  url: %s", albumName, album));
        driver.navigate().to(album);

        final List<String> photoHrefLinks = driver.findElements(By.xpath("//div[@class='goog-icon-list']//a"))
                .stream().filter(a -> MediaType.PHOTO.equals(getMediaType(a))).map(a -> a.getAttribute("href"))
                .collect(Collectors.toList());

        for (String href : photoHrefLinks) {
            downloadPhoto(driver, href);
        }

        driver.navigate().to(album);

        final List<String> videoHrefLinks = driver.findElements(By.xpath("//div[@class='goog-icon-list']//a"))
                .stream().filter(a -> MediaType.VIDEO.equals(getMediaType(a))).map(a -> a.getAttribute("href"))
                .collect(Collectors.toList());

        int index = 1;
        final FileDownloader fileDownloader = new FileDownloader(driver, outputDir.getAbsolutePath());
        for (String videoUrl : getVideoUrls(driver, videoHrefLinks, album)) {
            try {
                new FileHandler(fileDownloader.downloader(videoUrl, albumName + index++ + ".m4v"));
            } catch (Exception e) {
                System.err.println(String.format("Cannot download video '%s'.", videoUrl));
                e.printStackTrace();
            }
        }

        TimeUnit.SECONDS.sleep(10);
        System.out.println(String.format("moving photos to directory: %s", albumName));
        final File albumDirectory = new File(outputDir, albumName);
        for (File file : FileUtils.listFiles(outputDir, null, false)) {
            try {
                FileUtils.moveFileToDirectory(file, albumDirectory, true);
            } catch (IOException e) {
                FileUtils.moveFile(file,
                        new File(albumDirectory, file.getName() + "-" + System.currentTimeMillis()));
            }
        }
    } catch (Exception e) {
        System.err.println(String.format("Cannot download album '%s'", album));
        e.printStackTrace();
    }
}