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

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

Introduction

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

Prototype

public static long sizeOfDirectory(File directory) 

Source Link

Document

Counts the size of a directory recursively (sum of the length of all files).

Usage

From source file:org.carbondata.core.datastorage.store.impl.FileFactory.java

/**
 * It computes size of directory//from   www. ja  va  2  s . c o m
 *
 * @param filePath
 * @return size in bytes
 * @throws IOException
 */
public static long getDirectorySize(String filePath) throws IOException {
    FileType fileType = getFileType(filePath);
    switch (fileType) {
    case HDFS:
    case VIEWFS:
        Path path = new Path(filePath);
        FileSystem fs = path.getFileSystem(configuration);
        return fs.getContentSummary(path).getLength();
    case LOCAL:
    default:
        File file = new File(filePath);
        return FileUtils.sizeOfDirectory(file);
    }
}

From source file:org.cloudifysource.dsl.internal.ServiceReader.java

/**
 *
 * @param serviceDirOrFile/*w ww . j  ava  2s.  com*/
 *            .
 * @param maxJarSizePermitted
 *            .
 * @throws PackagingException .
 */
public static void validateFolderSize(final File serviceDirOrFile, final long maxJarSizePermitted)
        throws PackagingException {
    File folder = serviceDirOrFile;
    if (folder.isFile()) {
        folder = folder.getParentFile();
    }
    final long folderSize = FileUtils.sizeOfDirectory(folder);
    if (folderSize == 0) {
        throw new PackagingException("folder " + folder.getAbsolutePath() + " is empty");
    }
    final long maxJarSize = maxJarSizePermitted;
    if (folderSize > maxJarSize || folderSize == 0) {
        throw new PackagingException("folder " + folder.getAbsolutePath() + "size is: "
                + FileUtils.byteCountToDisplaySize(folderSize) + ", it must be smaller than: "
                + FileUtils.byteCountToDisplaySize(maxJarSize));
    }

}

From source file:org.dataconservancy.packaging.tool.impl.generator.BagItPackageAssembler.java

private File writeBagInfoTxt() throws PackageToolException {
    File bagInfoFile = new File(bagBaseDir, "bag-info.txt");
    try {/*from  w w w  .java  2s.  c  o  m*/
        FileWriter writer = new FileWriter(bagInfoFile);
        String newLine = System.getProperty("line.separator");
        String lineFormat = "%s: %s ";

        Set<String> bagInfoFields = params.getKeys();
        for (String field : bagInfoFields) {
            List<String> fieldValues = params.getParam(field);
            for (String value : fieldValues) {
                writer.write(String.format(lineFormat, field, value) + newLine);
            }
        }

        writer.write(String.format(lineFormat, BagItParameterNames.BAG_SIZE,
                FileUtils.byteCountToDisplaySize(FileUtils.sizeOfDirectory(bagBaseDir))) + newLine);
        writer.write(String.format(lineFormat, BagItParameterNames.PAYLOAD_OXUM,
                FileUtils.sizeOfDirectory(payloadDir) + "." + dataFiles.size()) + newLine);
        writer.write(String.format(lineFormat, BagItParameterNames.BAGGING_DATE,
                (new DateTime().toDate()) + newLine));

        writer.close();
    } catch (IOException e) {
        throw new PackageToolException(PackagingToolReturnInfo.PKG_IO_EXCEPTION, e,
                "Exception occurred when writing bag-info.txt file.");
    }

    return bagInfoFile;
}

From source file:org.dspace.health.InfoCheck.java

@Override
public String run(ReportInfo ri) {
    StringBuilder sb = new StringBuilder();
    ConfigurationService configurationService = new DSpace().getConfigurationService();
    sb.append("Generated: ").append(new Date().toString()).append("\n");

    sb.append("From - Till: ").append(new SimpleDateFormat("yyyy-MM-dd").format(ri.from().getTime()))
            .append(" - ").append(new SimpleDateFormat("yyyy-MM-dd").format(ri.till().getTime())).append("\n");

    sb.append("Url: ").append(ConfigurationManager.getProperty("dspace.url")).append("\n");
    sb.append("\n");

    DSBitStoreService localStore = new DSpace().getServiceManager().getServicesByType(DSBitStoreService.class)
            .get(0);//from   w  ww . j  a  v  a 2s . c o  m
    for (String[] ss : new String[][] { new String[] { localStore.getBaseDir().toString(), "Assetstore size", },
            new String[] { configurationService.getProperty("log.report.dir"), "Log dir size", }, }) {
        if (ss[0] != null) {
            try {
                File dir = new File(ss[0]);
                if (dir.exists()) {
                    long dir_size = FileUtils.sizeOfDirectory(dir);
                    sb.append(String.format("%-20s: %s\n", ss[1], FileUtils.byteCountToDisplaySize(dir_size)));
                } else {
                    sb.append(String.format("Directory [%s] does not exist!\n", ss[0]));
                }
            } catch (Exception e) {
                error(e, "directory - " + ss[0]);
            }
        } else { // cannot read property for some reason
            sb.append(String.format("Could not get information for %s!\n", ss[1]));
        }
    }

    return sb.toString();
}

From source file:org.duracloud.snapshot.service.impl.SnapshotJobExecutionListener.java

@Transactional
public void afterJob(JobExecution jobExecution) {
    log.debug("entering afterJob()...");
    JobParameters jobParams = jobExecution.getJobParameters();
    BatchStatus status = jobExecution.getStatus();

    String snapshotName = this.parameterMarshaller.unmarshal(jobParams);

    Snapshot snapshot = snapshotRepo.findByName(snapshotName);
    String snapshotPath = ContentDirUtils.getDestinationPath(snapshot.getName(), config.getContentRoot());
    log.debug("Completed snapshot: {} with status: {}", snapshotName, status);

    if (BatchStatus.COMPLETED.equals(status)) {
        File snapshotDir = new File(snapshotPath);
        snapshot.setTotalSizeInBytes(FileUtils.sizeOfDirectory(snapshotDir));
        // Job success. Email Chronopolis/DPN AND DuraSpace teams about
        // snapshot ready for transfer into preservation storage.
        String subject = "DuraCloud content snapshot ready for preservation";
        String message = "A DuraCloud content snapshot has been transferred from "
                + "DuraCloud to bridge storage and ready to move into " + "preservation storage.\n"
                + "\nsnapshot-id=" + snapshotName + "\nsnapshot-path=" + snapshotPath;
        sendEmail(subject, message, config.getAllEmailAddresses());

        changeSnapshotStatus(snapshot, SnapshotStatus.WAITING_FOR_DPN, "");
    } else {/* w ww . j  a v a 2 s  .  co  m*/
        // Job failed.  Email DuraSpace team about failed snapshot attempt.
        String subject = "DuraCloud content snapshot failed to complete";
        String message = "A DuraCloud content snapshot has failed to complete.\n" + "\nsnapshot-id="
                + snapshot.getName() + "\nsnapshot-path=" + snapshotPath;
        // TODO: Add details of failure in message
        sendEmail(subject, message, config.getDuracloudEmailAddresses());
        changeSnapshotStatus(snapshot, SnapshotStatus.FAILED_TO_TRANSFER_FROM_DURACLOUD,
                "batch job did not complete: batch status = " + status);

    }
}

From source file:org.eclipse.mylyn.reviews.r4e.core.TstGeneral.java

/**
 * @param fileA//w  w  w . j av  a2s.  co  m
 * @param fileB
 * @return - true if they are the same
 */
public static boolean compareDirectories(File fileA, File fileB) {
    // valid directories
    if (!(fileA.isDirectory() && fileB.isDirectory())) {
        return false;
    }

    // must exist
    if (!(fileA.exists() && fileB.exists())) {
        return false;
    }

    // TODO: implement a recursive check file per file e.g. using FileUtils.contentEquals(file1, file2);
    // The following is a temporary workaround by directory size

    // Find the size of the Golden directory
    long fileSizeA = FileUtils.sizeOfDirectory(fileA);
    // Find the size of the new Directory
    long fileSizeB = FileUtils.sizeOfDirectory(fileB);

    boolean same = (fileSizeA == fileSizeB);
    if (!same) {
        StringBuilder sb = new StringBuilder("TestGeneral.compareDirectories, directories size are different:");
        try {
            sb.append("\n\tfile Size is:" + fileSizeA + " for: " + fileA.getCanonicalPath());
            sb.append("\n\tfile Size is:" + fileSizeB + " for: " + fileB.getCanonicalPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(sb.toString());
    }

    return same;
}

From source file:org.efs.openreports.actions.admin.EditPropertiesAction.java

public String execute() {
    try {//from w  ww  . j a va 2s  . com
        if (submitType == null) {
            dateFormat = dateProvider.getDateFormat().toPattern();
            baseDirectory = directoryProvider.getReportDirectory();
            tempDirectory = directoryProvider.getTempDirectory();
            reportGenerationDirectory = directoryProvider.getReportGenerationDirectory();

            ORProperty property = propertiesProvider.getProperty(ORProperty.MAIL_SMTP_HOST);
            if (property != null)
                mailHost = property.getValue();

            property = propertiesProvider.getProperty(ORProperty.MAIL_SMTP_AUTH);
            if (property != null)
                mailAuthenticatorUsed = new Boolean(property.getValue()).booleanValue();

            property = propertiesProvider.getProperty(ORProperty.MAIL_AUTH_USER);
            if (property != null)
                mailUser = property.getValue();

            property = propertiesProvider.getProperty(ORProperty.MAIL_AUTH_PASSWORD);
            if (property != null)
                mailPassword = property.getValue();

            property = propertiesProvider.getProperty(ORProperty.QUERYREPORT_MAXROWS);
            if (property != null)
                maxRows = property.getValue();

            //
            File imageTempDirFile = new File(directoryProvider.getReportImageTempDirectory());
            imageTempDirectory = imageTempDirFile.getPath();

            long size = FileUtils.sizeOfDirectory(imageTempDirFile);
            directorySize = FileUtils.byteCountToDisplaySize(size);

            numberOfFiles = imageTempDirFile.listFiles().length;
            //

            return INPUT;
        }

        // validate maxRows is an integer
        try {
            Integer.parseInt(maxRows);
        } catch (NumberFormatException nfe) {
            addActionError(LocalStrings.getString(LocalStrings.ERROR_INVALID_MAXROWS));
            return INPUT;
        }

        propertiesProvider.setProperty(ORProperty.BASE_DIRECTORY, baseDirectory);
        if (baseDirectory != null)
            directoryProvider.setReportDirectory(baseDirectory);

        propertiesProvider.setProperty(ORProperty.TEMP_DIRECTORY, tempDirectory);
        if (tempDirectory != null)
            directoryProvider.setTempDirectory(tempDirectory);

        propertiesProvider.setProperty(ORProperty.REPORT_GENERATION_DIRECTORY, reportGenerationDirectory);
        if (tempDirectory != null)
            directoryProvider.setReportGenerationDirectory(reportGenerationDirectory);

        propertiesProvider.setProperty(ORProperty.DATE_FORMAT, dateFormat);
        if (dateFormat != null)
            dateProvider.setDateFormat(dateFormat);

        propertiesProvider.setProperty(ORProperty.MAIL_AUTH_PASSWORD, mailPassword);
        if (mailPassword != null)
            mailProvider.setPassword(mailPassword);

        propertiesProvider.setProperty(ORProperty.MAIL_AUTH_USER, mailUser);
        if (mailUser != null)
            mailProvider.setUserName(mailUser);

        propertiesProvider.setProperty(ORProperty.MAIL_SMTP_AUTH, String.valueOf(mailAuthenticatorUsed));
        mailProvider.setUseMailAuthenticator(mailAuthenticatorUsed);

        propertiesProvider.setProperty(ORProperty.MAIL_SMTP_HOST, mailHost);
        if (mailHost != null)
            mailProvider.setMailHost(mailHost);

        propertiesProvider.setProperty(ORProperty.QUERYREPORT_MAXROWS, maxRows);

        return SUCCESS;
    } catch (Exception e) {
        addActionError(e.toString());
        return INPUT;
    }
}

From source file:org.elfinder.servlets.fs.DiskFsImpl.java

public long getDirSize(File dir) {
    return FileUtils.sizeOfDirectory(dir);
}

From source file:org.fao.geonet.services.config.GetInfo.java

/**
 * Compute information about Lucene index.
 * //from w  ww  .j a  v a  2  s  .  c o  m
 * @param luceneDir
 */
private void loadIndexInfo(String luceneDir) {
    indexProperties.put("index.path", luceneDir);
    File dir = new File(luceneDir);
    File lDir = new File(luceneDir + SearchManager.NON_SPATIAL_DIR);
    if (dir.exists()) {
        long size = FileUtils.sizeOfDirectory(dir) / 1024;
        indexProperties.put("index.size", "" + size); // lucene + Shapefile
        // if exist
        if (lDir.exists()) {
            size = FileUtils.sizeOfDirectory(lDir) / 1024;
            indexProperties.put("index.size.lucene", "" + size);
        }
    }
    indexProperties.put("index.lucene.config", sm.getCurrentLuceneConfiguration().toString());
}

From source file:org.giswater.dao.MainDao.java

public static boolean configIni(String versionCode) {

    // Giswater version
    giswaterVersion = versionCode;/*w  w w  . j a  v a 2s  .  com*/

    // Set Giswater users folder path
    giswaterUsersFolder = System.getProperty("user.home") + File.separator + FOLDER_NAME;

    // Properties files configuration
    if (!PropertiesDao.configIni(giswaterUsersFolder)) {
        return false;
    }

    // Set Locale
    setLocale();

    // Log SQL?
    Utils.setSqlLog(PropertiesDao.getPropertiesFile().get("SQL_LOG", "false"));

    // Get inp and updates folder
    String inpFolder = Utils.getAppPath() + "inp" + File.separator;
    ConfigDao.setInpFolder(inpFolder);
    updatesFolder = Utils.getAppPath() + "updates" + File.separator;
    getLastUpdates();

    // Set Config DB connection
    if (!ConfigDao.setConnectionConfig()) {
        return false;
    }

    // Start Postgis portable?
    Boolean autostart = Boolean
            .parseBoolean(PropertiesDao.getPropertiesFile().get("AUTOSTART_POSTGIS", "true"));
    if (autostart) {
        ExecuteDao.executePostgisService("start");
    }

    // Check log folder size
    String aux = PropertiesDao.getPropertiesFile().get("LOG_FOLDER_SIZE", "10");
    try {
        Double warningSize = Double.parseDouble(aux);
        double size = FileUtils.sizeOfDirectory(new File(Utils.getLogFolder()));
        double sizeMb = Math.round((size / 1048576) * 100.0) / 100.0;
        if (sizeMb > warningSize) {
            Utils.getLogger().info("Log folder size is: " + sizeMb + " Mb");
            String msg = Utils.getBundleString("MainDao.log_size") + sizeMb //$NON-NLS-1$
                    + Utils.getBundleString("MainDao.perform_maintenance"); //$NON-NLS-1$
            int answer = Utils.showYesNoDialog(msg);
            if (answer == JOptionPane.YES_OPTION) {
                Utils.openFile(Utils.getLogFolder());
            }
        }
    } catch (NumberFormatException e) {
        String msg = Utils.getBundleString("MainDao.log_size_invalid"); //$NON-NLS-1$
        Utils.logError(msg);
    }

    return true;

}