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:com.tps.ttorrent.client.storage.FileStorage.java

/** Move the partial file to its final location.
 *///from   w w w  .  j  ava 2 s.  c  o  m
@Override
public synchronized void finish() throws IOException {
    logger.debug("Closing file channel to " + this.current.getName() + " (download hasHeader).");
    if (this.channel.isOpen()) {
        this.channel.force(true);
    }

    // Nothing more to do if we're already on the target file.
    if (this.isFinished()) {
        return;
    }

    this.raf.close();
    FileUtils.deleteQuietly(this.target);
    FileUtils.moveFile(this.current, this.target);

    logger.debug("Re-opening torrent byte storage at {}.", this.target.getAbsolutePath());

    this.raf = new RandomAccessFile(this.target, "rw");
    this.raf.setLength(this.size);
    this.channel = this.raf.getChannel();
    this.current = this.target;

    FileUtils.deleteQuietly(this.partial);
    logger.info("Moved torrent data from {} to {}.", this.partial.getName(), this.target.getName());
}

From source file:fr.sanofi.fcl4transmart.controllers.listeners.clinicalData.SetLabelsOntologyListener.java

@Override
public void handleEvent(Event event) {
    // TODO Auto-generated method stub
    Vector<String> headers = this.setLabelsOntologyUI.getHeaders();
    Vector<String> newLabels = this.setLabelsOntologyUI.getNewLabels();
    Vector<String> codes = this.setLabelsOntologyUI.getCodes();

    if (((ClinicalData) this.dataType).getCMF() == null) {
        this.setLabelsOntologyUI.displayMessage("Error: no column mapping file");
        return;//  w ww .ja  v  a 2  s  .  c  om
    }
    File file = new File(this.dataType.getPath().toString() + File.separator
            + this.dataType.getStudy().toString() + ".columns.tmp");
    try {
        FileWriter fw = new FileWriter(file);
        BufferedWriter out = new BufferedWriter(fw);
        out.write(
                "Filename\tCategory Code\tColumn Number\tData Label\tData Label Source\tControlled Vocab Code\n");
        try {
            BufferedReader br = new BufferedReader(new FileReader(((ClinicalData) this.dataType).getCMF()));
            String line = br.readLine();
            while ((line = br.readLine()) != null) {
                if (line.split("\t", -1)[3].compareTo("SUBJ_ID") == 0
                        || line.split("\t", -1)[3].compareTo("VISIT_NAME") == 0
                        || line.split("\t", -1)[3].compareTo("SITE_ID") == 0
                        || line.split("\t", -1)[3].compareTo("\\") == 0
                        || line.split("\t", -1)[3].compareTo("DATA_LABEL") == 0
                        || line.split("\t", -1)[3].compareTo("OMIT") == 0) {
                    out.write(line + "\n");
                } else {
                    File rawFile = new File(this.dataType.getPath() + File.separator + line.split("\t", -1)[0]);
                    String header = FileHandler.getColumnByNumber(rawFile,
                            Integer.parseInt(line.split("\t", -1)[2]));
                    String newLabel = newLabels.elementAt(headers.indexOf(rawFile.getName() + " - " + header));
                    if (newLabel.compareTo("") == 0) {
                        newLabel = header;
                    }
                    out.write(line.split("\t", -1)[0] + "\t" + line.split("\t", -1)[1] + "\t"
                            + line.split("\t", -1)[2] + "\t" + newLabel + "\t\t"
                            + codes.elementAt(headers.indexOf(rawFile.getName() + " - " + header)) + "\n");

                }
            }
            br.close();
        } catch (Exception e) {
            this.setLabelsOntologyUI.displayMessage("Error: " + e.getLocalizedMessage());
            e.printStackTrace();
            out.close();
        }

        out.close();
        String fileName = ((ClinicalData) this.dataType).getCMF().getName();
        FileUtils.deleteQuietly(((ClinicalData) this.dataType).getCMF());
        try {
            File fileDest = new File(this.dataType.getPath() + File.separator + fileName);
            FileUtils.moveFile(file, fileDest);
            ((ClinicalData) this.dataType).setCMF(fileDest);
        } catch (Exception ioe) {
            this.setLabelsOntologyUI.displayMessage("File error: " + ioe.getLocalizedMessage());
            return;
        }
    } catch (Exception e) {
        this.setLabelsOntologyUI.displayMessage("Error: " + e.getLocalizedMessage());
        e.printStackTrace();
    }
    this.setLabelsOntologyUI.displayMessage("Column mapping file updated");
    WorkPart.updateSteps();
    WorkPart.updateFiles();
}

From source file:com.ikanow.aleph2.analytics.spark.services.SparkCompilerService.java

/** Compiles a scala class
 * @param script//from  w  w  w  .j  a v  a  2  s .c  om
 * @param clazz_name
 * @return
 * @throws IOException
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws ClassNotFoundException
 */
public Tuple2<ClassLoader, Object> buildClass(final String script, final String clazz_name,
        final Optional<IBucketLogger> logger)
        throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException {
    final String relative_dir = "./script_classpath/";
    new File(relative_dir).mkdirs();

    final File source_file = new File(relative_dir + clazz_name + ".scala");
    FileUtils.writeStringToFile(source_file, script);

    final String this_path = LiveInjector.findPathJar(this.getClass(), "./dummy.jar");
    final File f = new File(this_path);
    final File fp = new File(f.getParent());
    final String classpath = Arrays.stream(fp.listFiles()).map(ff -> ff.toString())
            .filter(ff -> ff.endsWith(".jar")).collect(Collectors.joining(":"));

    // Need this to make the URL classloader be used, not the system classloader (which doesn't know about Aleph2..)

    final Settings s = new Settings();
    s.classpath().value_$eq(System.getProperty("java.class.path") + classpath);
    s.usejavacp().scala$tools$nsc$settings$AbsSettings$AbsSetting$$internalSetting_$eq(true);
    final StoreReporter reporter = new StoreReporter();
    final Global g = new Global(s, reporter);
    final Run r = g.new Run();
    r.compile(JavaConverters.asScalaBufferConverter(Arrays.<String>asList(source_file.toString())).asScala()
            .toList());

    if (reporter.hasErrors() || reporter.hasWarnings()) {
        final String errors = "Compiler: Errors/warnings (**to get to user script line substract 22**): "
                + JavaConverters.asJavaSetConverter(reporter.infos()).asJava().stream()
                        .map(info -> info.toString()).collect(Collectors.joining(" ;; "));
        logger.ifPresent(l -> l.log(reporter.hasErrors() ? Level.ERROR : Level.DEBUG, false, () -> errors,
                () -> "SparkScalaInterpreterTopology", () -> "compile"));

        //ERROR:
        if (reporter.hasErrors()) {
            System.err.println(errors);
        }
    }
    // Move any class files (eg including sub-classes)
    Arrays.stream(fp.listFiles()).filter(ff -> ff.toString().endsWith(".class"))
            .forEach(Lambdas.wrap_consumer_u(ff -> {
                FileUtils.moveFile(ff, new File(relative_dir + ff.getName()));
            }));

    // Create a JAR file...

    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    final JarOutputStream target = new JarOutputStream(new FileOutputStream("./script_classpath.jar"),
            manifest);
    Arrays.stream(new File(relative_dir).listFiles()).forEach(Lambdas.wrap_consumer_i(ff -> {
        JarEntry entry = new JarEntry(ff.getName());
        target.putNextEntry(entry);
        try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(ff))) {
            byte[] buffer = new byte[1024];
            while (true) {
                int count = in.read(buffer);
                if (count == -1)
                    break;
                target.write(buffer, 0, count);
            }
            target.closeEntry();
        }
    }));
    target.close();

    final String created = "Created = " + new File("./script_classpath.jar").toURI().toURL() + " ... "
            + Arrays.stream(new File(relative_dir).listFiles()).map(ff -> ff.toString())
                    .collect(Collectors.joining(";"));
    logger.ifPresent(l -> l.log(Level.DEBUG, true, () -> created, () -> "SparkScalaInterpreterTopology",
            () -> "compile"));

    final Tuple2<ClassLoader, Object> o = Lambdas.get(Lambdas.wrap_u(() -> {
        _cl.set(new java.net.URLClassLoader(
                Arrays.asList(new File("./script_classpath.jar").toURI().toURL()).toArray(new URL[0]),
                Thread.currentThread().getContextClassLoader()));
        Object o_ = _cl.get().loadClass("ScriptRunner").newInstance();
        return Tuples._2T(_cl.get(), o_);
    }));
    return o;
}

From source file:de.uzk.hki.da.repository.Fedora3RepositoryFacade.java

@Override
public void ingestFile(String objectId, String collection, String dsId, File file, String label,
        String mimeType) throws RepositoryException, IOException {
    String pid = generatePid(objectId, collection);
    AddDatastreamResponse r = null;// w w w. ja v  a 2s. c  o m
    try {
        String fileName = file.getAbsolutePath();
        String fileNameWithoutWhitespace = fileName.replaceAll("\\s+", "_");
        if (!fileName.equals(fileNameWithoutWhitespace)) {
            logger.debug(
                    "Whitespace(s) in file name! Rename file " + fileName + " in " + fileNameWithoutWhitespace);
            File newFile = Path.makeFile(fileNameWithoutWhitespace);
            FileUtils.moveFile(file, newFile);
            file = newFile;
        }

        String dsLocation = "file://" + file.getAbsolutePath();
        logger.debug("dsLocation: " + dsLocation);

        r = new AddDatastream(pid, dsId).mimeType(mimeType).controlGroup("E").dsLabel(label)
                .dsLocation(dsLocation).execute(fedora);
        logger.info("Successfully created datastream with dsID {} for file {}.", dsId, file.getName());
    } catch (FedoraClientException e) {
        throw new RepositoryException("Error while trying to add datastream for file " + file.getName(), e);
    } finally {
        if (r != null)
            r.close();
    }
}

From source file:com.qq.tars.web.controller.patch.UploadController.java

@RequestMapping(value = "server/api/upload_patch_package", produces = "application/json")
@ResponseBody/*from www  .  j  av  a2 s .  c  om*/
public ServerPatchView upload(@Application @RequestParam String application,
        @ServerName @RequestParam("module_name") String moduleName, HttpServletRequest request,
        ModelMap modelMap) throws Exception {
    String comment = StringUtils.trimToEmpty(request.getParameter("comment"));
    String uploadTgzBasePath = systemConfigService.getUploadTgzPath();

    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
            request.getSession().getServletContext());
    if (multipartResolver.isMultipart(request)) {
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        Iterator<String> it = multiRequest.getFileNames();
        if (it.hasNext()) {
            MultipartFile file = multiRequest.getFile(it.next());

            String originalName = file.getOriginalFilename();
            String extension = FilenameUtils.getExtension(originalName);
            String temporary = uploadTgzBasePath + "/" + UUID.randomUUID() + "." + extension;
            IOUtils.copy(file.getInputStream(), new FileOutputStream(temporary));

            String packageType = "suse";

            // war?
            if (temporary.endsWith(".war")) {
                temporary = patchService.war2tgz(temporary, moduleName);
            }

            // ?
            String updateTgzPath = uploadTgzBasePath + "/" + application + "/" + moduleName;

            // ????
            String uploadTgzName = application + "." + moduleName + "_" + packageType + "_"
                    + System.currentTimeMillis() + ".tgz";

            // ??
            String uploadTgzFullPath = updateTgzPath + "/" + uploadTgzName;

            log.info("temporary path={}, upload path={}", temporary, uploadTgzFullPath);

            File uploadPathDir = new File(updateTgzPath);
            if (!uploadPathDir.exists()) {
                if (!uploadPathDir.mkdirs()) {
                    throw new IOException(
                            String.format("mkdirs error, path=%s", uploadPathDir.getCanonicalPath()));
                }
            }

            FileUtils.moveFile(new File(temporary), new File(uploadTgzFullPath));

            return mapper.map(patchService.addServerPatch(application, moduleName, uploadTgzFullPath, comment),
                    ServerPatchView.class);
        }
    }

    throw new Exception("???");
}

From source file:edu.isi.misd.scanner.network.worker.webapp.ResultsReleaseDelegate.java

@Override
public void execute(DelegateExecution execution) throws Exception {
    if (!execution.hasVariable(BaseConstants.ID)) {
        throw new Exception("Variable not present: " + BaseConstants.ID);
    }/*from ww w .j a v  a 2  s .c o m*/

    if (!execution.hasVariable(BaseConstants.REQUEST_URL)) {
        throw new Exception("Variable not present: " + BaseConstants.REQUEST_URL);
    }

    if (!execution.hasVariable(SITE_NAME)) {
        throw new Exception("Variable not present: " + SITE_NAME);
    }

    if (!execution.hasVariable(NODE_NAME)) {
        throw new Exception("Variable not present: " + NODE_NAME);
    }

    if (!execution.hasVariable(COMMENTS)) {
        throw new Exception("Variable not present: " + COMMENTS);
    }

    if (!execution.hasVariable(APPROVED)) {
        throw new Exception("Variable not present: " + APPROVED);
    }

    if (!execution.hasVariable(FILE_PATH)) {
        throw new Exception("Variable not present: " + FILE_PATH);
    }

    if (!execution.hasVariable(HOLDING_PATH)) {
        throw new Exception("Variable not present: " + HOLDING_PATH);
    }

    File outputFile = new File((String) execution.getVariable(FILE_PATH));
    File holdingFile = new File((String) execution.getVariable(HOLDING_PATH));

    String id = (String) execution.getVariable(BaseConstants.ID);
    String url = (String) execution.getVariable(BaseConstants.REQUEST_URL);
    String siteName = (String) execution.getVariable(SITE_NAME);
    String nodeName = (String) execution.getVariable(NODE_NAME);
    String approved = (String) execution.getVariable(APPROVED);
    String comments = (String) execution.getVariable(COMMENTS);
    if (!Boolean.parseBoolean(approved)) {
        log.info("Release approval rejected for request [" + id + "]."
                + "  The following file will be deleted: " + holdingFile.getCanonicalPath());
        try {
            writeRejectedServiceResponse(id, url, siteName, nodeName, comments, outputFile);
        } catch (Exception e) {
            log.warn("Could write service response output file " + outputFile.getCanonicalPath()
                    + " : Exception: " + e);
            throw e;
        }
        try {
            FileUtils.forceDelete(holdingFile);
        } catch (Exception e) {
            log.warn("Could not delete output file from holding directory: " + holdingFile.getCanonicalPath());
            throw e;
        }
        return;
    }

    if (outputFile.exists()) {
        try {
            FileUtils.forceDelete(outputFile);
        } catch (Exception e) {
            log.warn("Could not delete output file: " + outputFile.getCanonicalPath());
            throw e;
        }
    }

    try {
        FileUtils.moveFile(holdingFile, outputFile);
        log.info("Release approval accepted for request [" + id + "]." + "  The results file was moved from "
                + holdingFile.getCanonicalPath() + " to " + outputFile.getCanonicalPath());
    } catch (Exception e) {
        log.warn("Unable to move file " + holdingFile.getCanonicalPath() + " to "
                + outputFile.getCanonicalPath());
        throw e;
    }
}

From source file:com.kwoksys.biz.files.FileService.java

/**
 * Will be moved to FileService class/*from   w w  w  .j  av  a  2 s  . c om*/
 * @param actionForm
 * @return
 * @throws DatabaseException
 */
private ActionMessages upload(File file, FileUploadForm uploadForm) throws DatabaseException {
    java.io.File[] files = uploadForm.getFiles();
    String[] fileNames = uploadForm.getFileNames();
    String[] mineTypes = uploadForm.getMineTypes();

    ActionMessages errors = new ActionMessages();

    if (files == null) {
        errors.add("fileUpload", new ActionMessage("files.error.fileUpload"));
        return errors;
    }

    // Set file detail.
    file.setLogicalName(fileNames[0]);
    file.setMimeType(mineTypes[0]);
    file.setSize(new Long(files[0].length()).intValue());
    file.setAttachedFile(files[0]);

    if (file.getLogicalName().isEmpty()) {
        errors.add("emptyFilePath", new ActionMessage("files.error.emptyFilePath"));
        return errors;
    }
    if (file.getSize() > ConfigManager.file.getMaxFileUploadSize() || file.getSize() < 0) {
        errors.add("fileMaxSize", new ActionMessage("files.error.fileMaxSize"));
        return errors;
    }

    FileDao fileDao = new FileDao(requestContext);

    try {
        // Create a record in the database.
        errors = fileDao.add(file);

        if (!errors.isEmpty()) {
            return errors;
        }

        java.io.File uploadFile = new java.io.File(file.getConfigRepositoryPath(),
                file.getConfigUploadedFilePrefix() + file.getId());

        // Check to see if file already exists
        if (uploadFile.exists()) {
            throw new Exception("File already exists");
        }

        // Move file from temp upload to storage.
        FileUtils.moveFile(file.getAttachedFile(), uploadFile);

    } catch (Throwable t) {
        // Upload failed, do some clean up.
        fileDao.deleteNew(file.getId());

        errors.add("fileUpload", new ActionMessage("files.error.fileUpload"));
        logger.log(Level.SEVERE,
                "Problem writing file to repository. " + "Original file name: " + file.getLogicalName()
                        + ". Physical file name: " + file.getConfigUploadedFilePrefix() + file.getId()
                        + ". File repository: " + file.getConfigRepositoryPath(),
                t);
    }
    return errors;
}

From source file:fr.letroll.ttorrentandroid.client.storage.FileStorage.java

/**
 * Move the partial file to its final location.
 *///from ww  w  .  j a  v  a 2  s.  c  om
@Override
public synchronized void finish() throws IOException {
    logger.debug("Closing file channel to {} (download complete).", this.current.getName());
    if (this.channel.isOpen())
        this.channel.force(true);

    // Nothing more to do if we're already on the target file.
    if (this.isFinished())
        return;

    this.raf.close();
    FileUtils.deleteQuietly(this.target);
    FileUtils.moveFile(this.current, this.target);
    logger.info("Moved torrent data from {} to {}.", this.current.getName(), this.target.getName());
    this.current = this.target;

    logger.debug("Re-opening torrent byte storage at {}.", this.target.getAbsolutePath());

    this.raf = new RandomAccessFile(this.target, "rw");
    this.raf.setLength(this.size);
    this.channel = this.raf.getChannel();
}

From source file:jmupen.JMupenUpdater.java

public static void installUpdate() {
    try {/*from  www .  j av a 2 s  .  co m*/
        String digest = MD5ForFile.getDigest(new FileInputStream(updatePackage), 2048);
        System.out.println("DIGEST UPDATED PACK: " + digest);
        System.out.println("DIGEST ONLINE: " + MD5ForFile.getMd5FromUrl(new URL(Md5URL).openConnection()));
        if (!digest.trim().equals(MD5ForFile.getMd5FromUrl(new URL(Md5URL).openConnection()).trim())) {
            System.err.println("Download failed, removing update file.");
            JMupenGUI.getInstance().showError("Download failed - MD5 Check",
                    "MD5 Check failed, not installing the update.");
            boolean isDeleted = updatePackage.delete();
            if (!isDeleted) {
                JMupenGUI.getInstance().showError("Can't delete temp file",
                        "Please manually delete file at " + updatePackage.getAbsolutePath());
            }
            return;
        }
    } catch (FileNotFoundException e) {
        System.err.println("File not found. Nothing to install.");
        return;
    } catch (Exception e) {
        System.err.println(
                "Almost impossible error (malformed MD5 url or IO problem). " + e.getLocalizedMessage());
    }
    boolean deleted = jarFile.delete();
    System.out.println("Deleted jar? " + deleted);

    if (!deleted) {

        JMupenUtils.extractJar(jarFile, tmpDir);
        JMupenUpdater.startWinUpdaterApplication();

    }
    try {
        FileUtils.moveFile(updatePackage, jarFile);
        JMupenUpdater.restartApplication();
    } catch (IOException ex) {
        System.err.println("Error moving file. You can find updated file at " + JMupenUtils.getConfigDir()
                + " Full mess: " + ex.getLocalizedMessage());
        JMupenGUI.getInstance().showError("Error updating JMupen.",
                "I couldn't move update file in place. You can find the app file in "
                        + JMupenUtils.getConfigDir() + " folder.");
    }
}

From source file:it.geosolutions.geobatch.actions.commons.MoveAction.java

/**
 * Removes TemplateModelEvents from the queue and put
 *///  w w  w . ja  va2  s  . c om
public Queue<EventObject> execute(Queue<EventObject> events) throws ActionException {

    listenerForwarder.started();
    listenerForwarder.setTask("build the output absolute file name");

    // return
    final Queue<EventObject> ret = new LinkedList<EventObject>();

    listenerForwarder.setTask("Building/getting the root data structure");

    boolean moveMultipleFile;
    final int size = events.size();
    if (size == 0) {
        throw new ActionException(this, "Empty file list");
    } else if (size > 1) {
        moveMultipleFile = true;
    } else {
        moveMultipleFile = false;
    }
    if (conf.getDestination() == null) {
        throw new IllegalArgumentException("Unable to work with a null dest dir");
    }
    if (!conf.getDestination().isAbsolute()) {
        conf.setDestination(new File(this.getConfigDir(), conf.getDestination().getPath()));
        if (LOGGER.isWarnEnabled()) {
            LOGGER.warn("Destination is not an absolute path. Absolutizing destination using temp dir: "
                    + conf.getDestination());
        }
    }

    boolean moveToDir;
    if (!conf.getDestination().isDirectory()) {
        // TODO LOG
        moveToDir = false;
        if (moveMultipleFile) {
            throw new ActionException(this,
                    "Unable to run on multiple file with an output file, use directory instead");
        }
    } else {
        moveToDir = true;
    }

    while (!events.isEmpty()) {
        listenerForwarder.setTask("Generating the output");

        final EventObject event = events.remove();
        if (event == null) {
            // TODO LOG
            continue;
        }
        if (event instanceof FileSystemEvent) {
            File source = ((FileSystemEvent) event).getSource();
            File dest;
            listenerForwarder.setTask("moving to destination");
            if (moveToDir) {
                dest = conf.getDestination();
                try {
                    FileUtils.moveFileToDirectory(source, dest, true);
                } catch (IOException e) {
                    throw new ActionException(this, e.getLocalizedMessage());
                }
            } else if (moveMultipleFile) {
                dest = new File(conf.getDestination(), source.getPath());
                try {
                    FileUtils.moveFile(source, dest);
                } catch (IOException e) {
                    throw new ActionException(this, e.getLocalizedMessage());
                }
            } else {
                // LOG continue
                continue;
            }

            // add the file to the return
            ret.add(new FileSystemEvent(dest, FileSystemEventType.FILE_ADDED));
        }
    }

    listenerForwarder.completed();
    return ret;
}