Example usage for java.io File getTotalSpace

List of usage examples for java.io File getTotalSpace

Introduction

In this page you can find the example usage for java.io File getTotalSpace.

Prototype

public long getTotalSpace() 

Source Link

Document

Returns the size of the partition named by this abstract pathname.

Usage

From source file:com.ikon.servlet.admin.StatsGraphServlet.java

/**
 * Generate disk statistics//from w  ww . j a  va  2s.  co m
 */
public JFreeChart diskStats() throws IOException, ServletException {
    String repHome = null;

    // Allow absolute repository path
    if ((new File(Config.REPOSITORY_HOME)).isAbsolute()) {
        repHome = Config.REPOSITORY_HOME;
    } else {
        repHome = Config.HOME_DIR + File.separator + Config.REPOSITORY_HOME;
    }

    File df = new File(repHome);
    long total = df.getTotalSpace();
    long usable = df.getUsableSpace();
    long used = total - usable;
    String title = "Disk: " + FormatUtil.formatSize(total);

    log.debug("Total space: {}", FormatUtil.formatSize(total));
    log.debug("Usable space: {}", FormatUtil.formatSize(usable));
    log.debug("Used space: {}", FormatUtil.formatSize(used));

    DefaultPieDataset dataset = new DefaultPieDataset();
    dataset.setValue("Available (" + FormatUtil.formatSize(usable) + ")", usable * 100 / total);
    dataset.setValue("Used (" + FormatUtil.formatSize(used) + ")", used * 100 / total);

    return ChartFactory.createPieChart(title, dataset, true, false, false);
}

From source file:org.codice.ddf.spatial.geocoding.extract.GeoNamesFileExtractor.java

/**
 * Get the InputStream for the given file resource.
 *
 * @param resource - the absolute path of the file to open the InputStream for.
 * @return the InputStream for the file resource
 * @throws GeoEntryExtractionException when the file cannot be found.
 *///  w  w  w  . j  ava 2 s. c  o  m
private InputStream getFileInputStream(String resource) throws GeoEntryExtractionException {
    FileInputStream fileInputStream;

    try {
        File file = new File(resource);
        fileSize = file.getTotalSpace();
        fileInputStream = new FileInputStream(file);
    } catch (FileNotFoundException e) {
        throw new GeoEntryExtractionException(resource + " cannot be found", e);
    }
    return fileInputStream;
}

From source file:org.apache.activemq.usage.PeriodicDiskUsageLimitTest.java

protected int getFreePercentage(File directory) {
    File storeDir = StoreUtil.findParentDirectory(directory);
    return (int) (((double) storeDir.getUsableSpace() / storeDir.getTotalSpace()) * 100);
}

From source file:de.uni_koblenz.jgralab.utilities.tgraphbrowser.TGraphBrowserServer.java

public TGraphBrowserServer(int port, String path, String maximumFileSize, String maximumWorkspaceSize)
        throws IOException {
    if (path == null) {
        throw new IllegalArgumentException("path must not be null");
    }//from  w w  w . ja v  a2s .  c  om
    workspace = path;
    if ((path != null) && (workspace.startsWith("\"") || workspace.startsWith("'"))) {
        workspace = workspace.substring(1, workspace.length() - 1);
    }
    StateRepository.MAXIMUM_FILE_SIZE = maximumFileSize == null ? null
            : Long.parseLong(maximumFileSize) * 1024 * 1024;
    File ws = new File(workspace);
    StateRepository.MAXIMUM_WORKSPACE_SIZE = maximumWorkspaceSize == null
            ? ws.getFreeSpace() + ws.getTotalSpace()
            : Long.parseLong(maximumWorkspaceSize) * 1024 * 1024;
    _serverSocket = new ServerSocket(port);
}

From source file:org.apache.bookkeeper.bookie.BookieInitializationTest.java

/**
 * Check disk full. Expected to throw NoWritableLedgerDirException
 * during bookie initialisation.//from  w ww.  j a  v  a 2  s.  c  o  m
 */
@Test(timeout = 30000)
public void testWithDiskFull() throws Exception {
    File tempDir = createTempDir("DiskCheck", "test");

    long usableSpace = tempDir.getUsableSpace();
    long totalSpace = tempDir.getTotalSpace();
    final ServerConfiguration conf = new ServerConfiguration().setZkServers(zkUtil.getZooKeeperConnectString())
            .setZkTimeout(5000).setJournalDirName(tempDir.getPath())
            .setLedgerDirNames(new String[] { tempDir.getPath() });
    conf.setDiskUsageThreshold((1f - ((float) usableSpace / (float) totalSpace)) - 0.05f);
    conf.setDiskUsageWarnThreshold((1f - ((float) usableSpace / (float) totalSpace)) - 0.25f);
    try {
        new Bookie(conf).initialize();
        fail("Should fail with NoWritableLedgerDirException");
    } catch (NoWritableLedgerDirException nlde) {
        // expected
    }
}

From source file:org.wso2.emm.agent.api.DeviceState.java

/**
 * Returns the total external memory size.
 *
 * @return - Total external memory size.
 *///from w w w.ja  va  2 s  . c o  m
public double getTotalExternalMemorySize() {
    long totalBytesExternal = 0;
    if (externalMemoryAvailable()) {
        for (File dir : externalStorageDirectoryList) {
            if (dir != null && !dir.getAbsolutePath().contains(INTERNAL_STORAGE_PATH)) {
                totalBytesExternal += dir.getTotalSpace();
            }
        }
        return formatSizeInGb(totalBytesExternal);
    } else {
        return MEMORY_NOT_AVAILABLE;
    }
}

From source file:de.cachebox_test.splash.java

/** Given any file/folder inside an sd card, this will return the path of the sd card */
private static String getRootOfInnerSdCardFolder(java.io.File file) {
    if (file == null)
        return null;
    final long totalSpace = file.getTotalSpace();
    while (true) {
        final java.io.File parentFile = file.getParentFile();
        if (parentFile == null || parentFile.getTotalSpace() != totalSpace)
            return file.getAbsolutePath();
        file = parentFile;//from w ww. j av a2 s  . c  o  m
    }
}

From source file:org.apache.samza.monitor.LocalStoreMonitor.java

/**
 * Role of this method is to garbage collect(mark-sweep) the task store.
 * @param taskStoreDir store directory of the task to perform garbage collection.
 *
 * This method cleans up each of the task store directory in two phases.
 *
 *  Phase 1:/*from w  w w  . jav a2s .c  om*/
 *  Delete the offset file in the task store if (curTime - lastModifiedTimeOfOffsetFile) > offsetTTL.
 *
 *  Phase 2:
 *  Delete the task store directory if the offsetFile does not exist in task store directory.
 *
 * The separate phases are a safety precaution to prevent deleting a store that is currently being used.
 * A running task will recreate the deleted offset file on the next commit. If a task is not running or
 * running on a different host and gets moved to this host, it will not use a store without the offset file.
 *
 * Time interval between the two phases is controlled by this monitor scheduling
 * interval in milli seconds.
 *
 * @throws IOException if there is an exception during the clean up of the task store files.
 */
private void markSweepTaskStore(File taskStoreDir) throws IOException {
    String taskStorePath = taskStoreDir.getAbsolutePath();
    File offsetFile = new File(taskStoreDir, OFFSET_FILE_NAME);
    if (!offsetFile.exists()) {
        LOG.info("Deleting the task store: {}, since it has no offset file.", taskStorePath);
        long taskStoreSizeInBytes = taskStoreDir.getTotalSpace();
        FileUtils.deleteDirectory(taskStoreDir);
        localStoreMonitorMetrics.diskSpaceFreedInBytes.inc(taskStoreSizeInBytes);
        localStoreMonitorMetrics.noOfDeletedTaskPartitionStores.inc();
    } else if ((CLOCK.currentTimeMillis() - offsetFile.lastModified()) >= config.getOffsetFileTTL()) {
        LOG.info(
                "Deleting the offset file from the store: {}, since the last modified timestamp: {} "
                        + "is older than the configured ttl: {}.",
                taskStorePath, offsetFile.lastModified(), config.getOffsetFileTTL());
        offsetFile.delete();
    }
}

From source file:tajo.master.MockupWorker.java

@Override
public ServerStatusProto getServerStatus(PrimitiveProtos.NullProto request) {
    // serverStatus builder
    ServerStatusProto.Builder serverStatus = ServerStatusProto.newBuilder();
    // TODO: compute the available number of task slots
    serverStatus.setAvailableTaskSlotNum(taskQueue.size());

    // system(CPU, memory) status builder
    ServerStatusProto.System.Builder systemStatus = ServerStatusProto.System.newBuilder();

    systemStatus.setAvailableProcessors(Runtime.getRuntime().availableProcessors());
    systemStatus.setFreeMemory(Runtime.getRuntime().freeMemory());
    systemStatus.setMaxMemory(Runtime.getRuntime().maxMemory());
    systemStatus.setTotalMemory(Runtime.getRuntime().totalMemory());

    serverStatus.setSystem(systemStatus);

    // disk status builder
    File[] roots = File.listRoots();
    for (File root : roots) {
        ServerStatusProto.Disk.Builder diskStatus = ServerStatusProto.Disk.newBuilder();

        diskStatus.setAbsolutePath(root.getAbsolutePath());
        diskStatus.setTotalSpace(root.getTotalSpace());
        diskStatus.setFreeSpace(root.getFreeSpace());
        diskStatus.setUsableSpace(root.getUsableSpace());

        serverStatus.addDisk(diskStatus);
    }/*from   w  w  w. j  a  va2 s .co m*/
    return serverStatus.build();
}

From source file:org.springframework.boot.actuate.health.DiskSpaceHealthIndicator.java

@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
    File path = this.properties.getPath();
    long diskFreeInBytes = path.getFreeSpace();
    if (diskFreeInBytes >= this.properties.getThreshold()) {
        builder.up();/*  www.j  a  v  a 2  s .c  o m*/
    } else {
        logger.warn(
                String.format("Free disk space below threshold. " + "Available: %d bytes (threshold: %d bytes)",
                        diskFreeInBytes, this.properties.getThreshold()));
        builder.down();
    }
    builder.withDetail("total", path.getTotalSpace()).withDetail("free", diskFreeInBytes)
            .withDetail("threshold", this.properties.getThreshold());
}