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.linkedin.pinot.controller.api.restlet.resources.PinotSegmentUploadRestletResource.java

@HttpVerb("post")
@Summary("Uploads a segment")
@Tags({ "segment" })
@Paths({ "/segments", "/segments/" })
@Responses({ @Response(statusCode = "200", description = "The segment was successfully uploaded"),
        @Response(statusCode = "403", description = "Forbidden operation typically because it exceeds configured quota"),
        @Response(statusCode = "500", description = "There was an error when uploading the segment") })
private Representation uploadSegment(File indexDir, File dataFile, String downloadUrl)
        throws ConfigurationException, IOException, JSONException {
    final SegmentMetadata metadata = new SegmentMetadataImpl(indexDir);
    final File tableDir = new File(baseDataDir, metadata.getTableName());
    String tableName = metadata.getTableName();
    File segmentFile = new File(tableDir, dataFile.getName());
    OfflineTableConfig offlineTableConfig = (OfflineTableConfig) ZKMetadataProvider
            .getOfflineTableConfig(_pinotHelixResourceManager.getPropertyStore(), tableName);

    if (offlineTableConfig == null) {
        LOGGER.info("Missing configuration for table: {} in helix", metadata.getTableName());
        setStatus(Status.CLIENT_ERROR_NOT_FOUND);
        StringRepresentation repr = new StringRepresentation(
                "{\"error\" : \"Missing table: " + tableName + "\"}");
        repr.setMediaType(MediaType.APPLICATION_JSON);
        return repr;
    }/* w  w  w .ja va  2  s.c  o  m*/
    StorageQuotaChecker.QuotaCheckerResponse quotaResponse = checkStorageQuota(indexDir, metadata,
            offlineTableConfig);
    if (!quotaResponse.isSegmentWithinQuota) {
        // this is not an "error" hence we don't increment segment upload errors
        LOGGER.info("Rejecting segment upload for table: {}, segment: {}, reason: {}", metadata.getTableName(),
                metadata.getName(), quotaResponse.reason);
        setStatus(Status.CLIENT_ERROR_FORBIDDEN);
        StringRepresentation repr = new StringRepresentation("{\"error\" : \"" + quotaResponse.reason + "\"}");
        repr.setMediaType(MediaType.APPLICATION_JSON);
        return repr;
    }

    if (segmentFile.exists()) {
        FileUtils.deleteQuietly(segmentFile);
    }
    FileUtils.moveFile(dataFile, segmentFile);

    PinotResourceManagerResponse response;
    if (!isSegmentTimeValid(metadata)) {
        response = new PinotResourceManagerResponse("Invalid segment start/end time", false);
    } else {
        if (downloadUrl == null) {
            downloadUrl = ControllerConf.constructDownloadUrl(tableName, dataFile.getName(), vip);
        }
        // TODO: this will read table configuration again from ZK. We should optimize that
        response = _pinotHelixResourceManager.addSegment(metadata, downloadUrl);
    }

    if (response.isSuccessfull()) {
        setStatus(Status.SUCCESS_OK);
    } else {
        ControllerRestApplication.getControllerMetrics()
                .addMeteredGlobalValue(ControllerMeter.CONTROLLER_SEGMENT_UPLOAD_ERROR, 1L);
        setStatus(Status.SERVER_ERROR_INTERNAL);
    }

    return new StringRepresentation(response.toJSON().toString());
}

From source file:com.generalbioinformatics.rdf.VirtuosoConnection.java

public void vstore(File f, String graphUri) throws SQLException, IOException {
    File tempDir = getTempDir();/*from  ww w.j  av a2s. c o  m*/

    // adapted from http://docs.openlinksw.com/virtuoso/rdfperformancetuning.html#rdfperfdumpandreloadgraphs
    String proc = "CREATE PROCEDURE dump_one_graph ( IN  srcgraph VARCHAR  , IN  out_file VARCHAR  , IN  file_length_limit  INTEGER  := 1000000000   ) "
            + "{     " + "  DECLARE  file_name     varchar;     " + "  DECLARE  env, ses      any;     "
            + "  DECLARE  ses_len,               " + "           max_ses_len,               "
            + "           file_len,               " + "           file_idx      integer;     "
            + "  SET ISOLATION = 'uncommitted';     max_ses_len := 10000000;     file_len := 0;     file_idx := 1;     "
            + "  file_name := sprintf ('%s%06d.ttl', out_file, file_idx);     "
            + "  string_to_file ( file_name, sprintf ( '# Dump of graph <%s>, as of %s\n', srcgraph, CAST (NOW() AS VARCHAR) ), -2 ); "
            + "  env := vector (dict_new (16000), 0, '', '', '', 0, 0, 0, 0);     "
            + "  ses := string_output ();     "
            + "  FOR (SELECT * FROM ( SPARQL DEFINE input:storage \"\"                           "
            + "      SELECT ?s ?p ?o { GRAPH `iri(?:srcgraph)` { ?s ?p ?o } }                         ) "
            + "      AS sub OPTION (LOOP)) " + "  DO       " + "  {         "
            + "    http_ttl_triple (env, \"s\", \"p\", \"o\", ses);         "
            + "    ses_len := length (ses);         " + "    IF (ses_len > max_ses_len)           "
            + "    {            " + "       file_len := file_len + ses_len;             "
            + "       IF (file_len > file_length_limit)               " + "       {                 "
            + "         http (' .\n', ses);                 "
            + "         string_to_file (file_name, ses, -1);                 file_len := 0;                 file_idx := file_idx + 1;                 "
            + "         file_name := sprintf ('%s%06d.ttl', out_file, file_idx);                 "
            + "         string_to_file ( file_name,                                   "
            + "         sprintf ( '# Dump of graph <%s>, as of %s (part %d)\n', srcgraph, CAST (NOW() AS VARCHAR), file_idx), -2 ); "
            + "         env := vector (dict_new (16000), 0, '', '', '', 0, 0, 0, 0);               "
            + "       }             " + "       ELSE               "
            + "         string_to_file (file_name, ses, -1);             "
            + "         ses := string_output ();           " + "     }" + "   }     "
            + "   IF (LENGTH (ses))       " + "   {         " + "     http (' .\n', ses);         "
            + "     string_to_file (file_name, ses, -1);       " + "   }   " + "}";

    File temp = new File(tempDir, f.getName());

    String func = "dump_one_graph ('" + graphUri + "', '" + temp.getAbsolutePath() + "')";
    Statement st = getConnection().createStatement();
    try {
        execute(st, proc);
        execute(st, func);
    } catch (VirtuosoException ex) {
        rethrowWithTips(ex);
    }

    for (File g : temp.getParentFile().listFiles()) {
        if (g.getName().startsWith(f.getName())) {
            log.info("output: " + g.getName());
            FileUtils.moveFile(g, new File(f.getParentFile(), g.getName()));
        }
    }

    // TODO: following functions may be useful as well
    // DB.DBA.RDF_TRIPLES_TO_RDF_XML_TEXT
    // DB.DBA.RDF_TRIPLES_TO_TTL
}

From source file:com.ms.commons.standalone.service.StandaloneServiceImpl.java

private boolean writeCronJobMapFromXml() {
    String configPath = baseStandalonePath + File.separator + Cons.STANDALONE_CONFIG;
    List<Element> cronJobList = new ArrayList<Element>();
    for (CronJob cronJob : listCronJobs()) {
        Element identity = new Element("identity");
        identity.setText(cronJob.getIdentity());
        Element fullClassName = new Element("fullClassName");
        fullClassName.setText(cronJob.getFullClassName());
        Element jvmParameter = new Element("jvmParameter");
        jvmParameter.setText(cronJob.getJvmParameter());
        Element cronExpression = new Element("cronExpression");
        cronExpression.setText(cronJob.getCronExpression());
        Element status = new Element("status");
        status.setText(cronJob.getStatus().name());
        Element isStandalone = new Element("isStandalone");
        isStandalone.setText(String.valueOf(cronJob.isStandalone()));
        Element cronJobElement = new Element("cronJob");
        cronJobElement.addContent(identity);
        cronJobElement.addContent(fullClassName);
        cronJobElement.addContent(jvmParameter);
        cronJobElement.addContent(cronExpression);
        cronJobElement.addContent(status);
        cronJobElement.addContent(isStandalone);
        cronJobList.add(cronJobElement);
    }/*from w  w  w  . j  ava 2s .  c om*/
    File configPathTmpFile = new File(configPath + ".tmp");
    Element root = new Element("standalone");
    root.addContent(cronJobList);
    XMLOutputter xMLOutputter = new XMLOutputter();
    xMLOutputter.setFormat(Format.getPrettyFormat());
    Document doc = new Document(root);
    StringWriter stringWriter = new StringWriter();
    try {
        xMLOutputter.output(doc, stringWriter);
        IOUtils.write(stringWriter.toString(), new FileOutputStream(configPathTmpFile), "utf-8");
        File configPathFile = new File(configPath);
        if (configPathFile.exists()) {
            configPathFile.delete();
        }
        FileUtils.moveFile(configPathTmpFile, configPathFile);
        return true;
    } catch (Exception e) {
        logger.error("StandaloneServiceImpl.writeCronJobMapFromXml() failed", e);
    }
    return false;
}

From source file:com.aniruddhc.acemusic.player.FoldersFragment.FilesFoldersFragment.java

/**
 * Displays a "Rename" dialog and renames the specified file/folder.
 *
 * @param path The path of the folder/file that needs to be renamed.
 *//*www  .j  av  a 2  s  .c om*/
public void rename(String path) {

    final File renameFile = new File(path);
    final AlertDialog renameAlertDialog = new AlertDialog.Builder(getActivity()).create();
    final EditText fileEditText = new EditText(getActivity());

    fileEditText.setHint(R.string.file_name);
    fileEditText.setSingleLine(true);
    fileEditText.setText(renameFile.getName());

    renameAlertDialog.setView(fileEditText);
    renameAlertDialog.setTitle(R.string.rename);
    renameAlertDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
            mContext.getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    renameAlertDialog.dismiss();
                }

            });

    renameAlertDialog.setButton(DialogInterface.BUTTON_POSITIVE,
            mContext.getResources().getString(R.string.rename), new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {

                    //Check if the new file name is empty.
                    if (fileEditText.getText().toString().isEmpty()) {
                        Toast.makeText(getActivity(), R.string.enter_a_name_for_folder, Toast.LENGTH_LONG)
                                .show();
                    } else {

                        File newNameFile = null;
                        try {
                            newNameFile = new File(renameFile.getParentFile().getCanonicalPath() + "/"
                                    + fileEditText.getText().toString());
                        } catch (IOException e) {
                            e.printStackTrace();
                            Toast.makeText(getActivity(), R.string.folder_could_not_be_renamed,
                                    Toast.LENGTH_LONG).show();
                            return;
                        }

                        try {
                            if (renameFile.isDirectory())
                                FileUtils.moveDirectory(renameFile, newNameFile);
                            else
                                FileUtils.moveFile(renameFile, newNameFile);

                        } catch (IOException e) {
                            e.printStackTrace();
                            Toast.makeText(getActivity(), R.string.folder_could_not_be_renamed,
                                    Toast.LENGTH_LONG).show();
                            return;
                        }

                        Toast.makeText(getActivity(), R.string.folder_renamed, Toast.LENGTH_SHORT).show();
                        renameAlertDialog.dismiss();
                        refreshListView();

                    }

                }

            });

    renameAlertDialog.show();

}

From source file:de.burlov.amazon.s3.dirsync.DirSync.java

private void downloadFile(File target, String s3key) throws IOException, S3ServiceException {
    InputStream in = downloadData(s3key);
    if (in == null) {
        throw new IOException("No data found");
    }// w w w  .j a  v  a 2s.c o  m
    in = new InflaterInputStream(new CryptInputStream(in, cipher, getDataEncryptionKey()));
    File temp = File.createTempFile("dirsync", null);
    FileOutputStream fout = new FileOutputStream(temp);
    try {
        IOUtils.copy(in, fout);
        if (target.exists()) {
            target.delete();
        }
        IOUtils.closeQuietly(fout);
        IOUtils.closeQuietly(in);
        FileUtils.moveFile(temp, target);
    } catch (IOException e) {
        fetchStream(in);
        throw e;
    } finally {
        IOUtils.closeQuietly(fout);
        IOUtils.closeQuietly(in);
    }
}

From source file:com.taobao.android.tpatch.utils.JarSplitUtils.java

/**
 * jarclass//from  www .j a  v a 2s . c  om
 * @param inJar
 * @param removeClasses
 */
public static void removeFilesFromJar(File inJar, List<String> removeClasses) throws IOException {
    if (null == removeClasses || removeClasses.isEmpty()) {
        return;
    }
    File outJar = new File(inJar.getParentFile(), inJar.getName() + ".tmp");
    File outParentFolder = outJar.getParentFile();
    if (!outParentFolder.exists()) {
        outParentFolder.mkdirs();
    }
    FileOutputStream fos = new FileOutputStream(outJar);
    ZipOutputStream jos = new ZipOutputStream(fos);
    final byte[] buffer = new byte[8192];
    FileInputStream fis = new FileInputStream(inJar);
    ZipInputStream zis = new ZipInputStream(fis);

    try {
        // loop on the entries of the jar file package and put them in the final jar
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            // do not take directories or anything inside a potential META-INF folder.
            if (entry.isDirectory() || !entry.getName().endsWith(".class")) {
                continue;
            }
            String name = entry.getName();
            String className = getClassName(name);
            if (removeClasses.contains(className)) {
                continue;
            }
            JarEntry newEntry;
            // Preserve the STORED method of the input entry.
            if (entry.getMethod() == JarEntry.STORED) {
                newEntry = new JarEntry(entry);
            } else {
                // Create a new entry so that the compressed len is recomputed.
                newEntry = new JarEntry(name);
            }
            // add the entry to the jar archive
            jos.putNextEntry(newEntry);

            // read the content of the entry from the input stream, and write it into the archive.
            int count;
            while ((count = zis.read(buffer)) != -1) {
                jos.write(buffer, 0, count);
            }
            // close the entries for this file
            jos.closeEntry();
            zis.closeEntry();
        }
    } finally {
        zis.close();
    }
    fis.close();
    jos.close();
    FileUtils.deleteQuietly(inJar);
    FileUtils.moveFile(outJar, inJar);
}

From source file:com.silverpeas.silvercrawler.control.SilverCrawlerSessionController.java

public void renameFolder(String folderName, String newName)
        throws SilverCrawlerFolderRenameException, IOException {
    // looks for weird characters in new file name (security)
    if (containsWeirdCharacters(newName)) {
        throw new SilverCrawlerFolderRenameException("SilverCrawlerSessionController.renameFolder",
                SilverpeasException.ERROR, getString("silverCrawler.nameIncorrect"));
    }//ww w.j a v  a2 s . c o  m

    // Get Full Path
    File after = FileUtils.getFile(getFullPath(newName));
    if (after.exists()) {
        throw new SilverCrawlerFolderRenameException("SilverCrawlerSessionController.renameFolder",
                SilverpeasException.ERROR, getString("silverCrawler.folderNameAlreadyExists"));
    }

    // Rename file
    File before = FileUtils.getFile(getFullPath(folderName));
    if (before.isDirectory()) {
        FileUtils.moveDirectory(before, after);
    } else {
        FileUtils.moveFile(before, after);
    }
}

From source file:it.geosolutions.imageio.plugins.exif.EXIFUtilities.java

/** 
 * Replace the EXIF contained within a file referred by a {@link FileImageInputStreamExt} instance
 * with the EXIF represented by the specified {@link EXIFMetadata} instance. The original file
 * will be overwritten by the new one containing updated EXIF.
 * /*w  w  w . j  a v a2s.  co m*/
 * It is worth to point out that this replacing method won't currently perform any fields delete, 
 * but simply content update. Therefore, tags in the original EXIF which are missing in the 
 * updated EXIF parameter, won't be modified. 
 * 
 * @param inputStream a {@link FileImageInputStreamExt} referring to a JPEG containing EXIF 
 * @param exif the {@link EXIFMetadata} instance containing tags to be updated
 */
public static void replaceEXIFs(final FileImageInputStreamExt inputStream, final EXIFMetadata exif)
        throws IOException {

    EXIFMetadataWrapper exifMarker = parseExifMetadata(inputStream, exif);
    EXIFMetadata updatedExif = exifMarker.getExif();

    final int app1Length = exifMarker.getLength();
    if (updatedExif != null) {
        // Create a temp file where to store the updated EXIF
        final File file = File.createTempFile("replacingExif", ".exif");
        final OutputStream fos = new FileOutputStream(file);
        updateStream(fos, inputStream, updatedExif, app1Length);
        final File previousFile = inputStream.getFile();
        FileUtils.deleteQuietly(previousFile);
        FileUtils.moveFile(file, previousFile);
    }
}

From source file:com.linkedin.pinot.controller.api.resources.PinotSegmentUploadRestletResource.java

private String moveSegmentToPermanentDirectory(FileUploadPathProvider provider, String tableName,
        String segmentName, File tempTarredSegmentFile) throws IOException {
    // Move tarred segment file to data directory when there is no external download URL
    File tarredSegmentFile = new File(new File(provider.getBaseDataDir(), tableName), segmentName);
    FileUtils.deleteQuietly(tarredSegmentFile);
    FileUtils.moveFile(tempTarredSegmentFile, tarredSegmentFile);
    return ControllerConf.constructDownloadUrl(tableName, segmentName, provider.getVip());
}

From source file:com.mediaworx.intellij.opencmsplugin.listeners.OpenCmsModuleFileChangeListener.java

/**
 * Moves meta data xml files for a moved resource
 * @param oldOcmsModule the source OpenCms module
 * @param newOcmsModule the target OpenCms module
 * @param oldVfsPath the VFS path before the move
 * @param newVfsPath the VFS path after the move
 * @param isDirectory <code>true</code> if the resource is a folder, <code>false</code> otherwise
 *///from  w  w w.j  a  va 2 s .c  om
private void handleMetaDataForMovedResources(OpenCmsModule oldOcmsModule, OpenCmsModule newOcmsModule,
        String oldVfsPath, String newVfsPath, boolean isDirectory) {
    String oldMetaDataFilePath = getMetaDataFilePath(oldOcmsModule, oldVfsPath, isDirectory);
    String newMetaDataFilePath = getMetaDataFilePath(newOcmsModule, newVfsPath, isDirectory);
    try {
        console.info("Move meta data file from " + oldMetaDataFilePath + " to " + newMetaDataFilePath);
        File oldMetaDataFile = new File(oldMetaDataFilePath);
        File newMetaDataFile = new File(newMetaDataFilePath);
        FileUtils.moveFile(oldMetaDataFile, newMetaDataFile);
        File oldParentFile = oldMetaDataFile.getParentFile();
        File newParentFile = newMetaDataFile.getParentFile();
        refreshFiles.add(oldParentFile);
        if (!FileUtil.filesEqual(oldParentFile, newParentFile)) {
            refreshFiles.add(newParentFile);
        }
    } catch (IOException e) {
        LOG.warn("Exception while moving " + oldMetaDataFilePath + " to " + newMetaDataFilePath, e);
    }
    if (isDirectory) {
        String oldMetaFolderPath = getMetaDataFilePathWithoutSuffix(oldOcmsModule, oldVfsPath);
        String newMetaFolderPath = getMetaDataFilePathWithoutSuffix(newOcmsModule, newVfsPath);
        try {
            console.info("Move meta data folder from " + oldMetaFolderPath + " to " + newMetaFolderPath);
            File oldMetaFolder = new File(oldMetaFolderPath);
            File newMetaFolder = new File(newMetaFolderPath);
            FileUtils.moveDirectory(oldMetaFolder, newMetaFolder);
            File oldParentFolder = oldMetaFolder.getParentFile();
            File newParentFolder = newMetaFolder.getParentFile();
            refreshFiles.add(oldParentFolder);
            if (!FileUtil.filesEqual(oldParentFolder, newParentFolder)) {
                refreshFiles.add(newParentFolder);
            }
        } catch (IOException e) {
            LOG.warn("Exception while moving " + oldMetaFolderPath + " to " + newMetaFolderPath, e);
        }
    }
}