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

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

Introduction

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

Prototype

public static String byteCountToDisplaySize(long size) 

Source Link

Document

Returns a human-readable version of the file size, where the input represents a specific number of bytes.

Usage

From source file:com.thoughtworks.go.server.service.BackupService.java

public String availableDiskSpace() {
    File artifactsDir = artifactsDirHolder.getArtifactsDir();
    return FileUtils.byteCountToDisplaySize(artifactsDir.getUsableSpace());
}

From source file:com.thoughtworks.go.service.ConfigRepository.java

private String getConfigRepoDisplaySize() {
    return FileUtils.byteCountToDisplaySize(FileUtils.sizeOfDirectory(workingDir));
}

From source file:com.alta189.cyborg.admin.AdminCommands.java

@Command(name = "memory", desc = "Returns information on the JVM's memory usage", aliases = { "mem" })
@Usage(".memory")
public CommandResult memory(CommandSource source, CommandContext context) {
    if (source.getSource() == CommandSource.Source.USER
            && (context.getPrefix() == null || !context.getPrefix().equals("."))) {
        return null;
    }//from w  w  w  . ja  v  a 2 s. c o m
    CommandResult result = new CommandResult();
    if (source.getSource() == CommandSource.Source.USER && !hasPerm(source.getUser(), "admin.memory")) {
        return result.setReturnType(ReturnType.NOTICE).setBody("You don't have permission!")
                .setTarget(source.getUser().getNick());
    }
    String freeMemory = FileUtils.byteCountToDisplaySize(Runtime.getRuntime().freeMemory());
    String maxMemory = FileUtils.byteCountToDisplaySize(Runtime.getRuntime().maxMemory());
    String totalMemory = FileUtils.byteCountToDisplaySize(Runtime.getRuntime().totalMemory());

    StringBuilder builder = new StringBuilder();
    builder.append("Maximum Memory: ").append(maxMemory).append(", Used Memory: ").append(totalMemory)
            .append(", Free Memory: ").append(freeMemory);
    return get(ReturnType.MESSAGE, builder.toString(), source, context);
}

From source file:com.adobe.acs.commons.httpcache.store.jcr.impl.JCRHttpCacheStoreImpl.java

@Override
protected void addCacheData(Map<String, Object> data, CacheContent cacheObj) {
    data.put(JMX_PN_STATUS, cacheObj.getStatus());
    data.put(JMX_PN_CONTENTTYPE, cacheObj.getContentType());
    data.put(JMX_PN_CHARENCODING, cacheObj.getCharEncoding());

    try {//from w ww  .  java 2s.  c o  m
        data.put(JMX_PN_SIZE,
                FileUtils.byteCountToDisplaySize(IOUtils.toByteArray(cacheObj.getInputDataStream()).length));
    } catch (IOException e) {
        log.error("Error adding cache data to JMX data map", e);
        data.put(JMX_PN_SIZE, "0");
    }
}

From source file:edu.harvard.iq.dvn.core.web.study.StudyVersionDifferencesPage.java

private boolean fileMetadataIsDifferent(FileMetadata fm1, FileMetadata fm2) {
    if (fm1 == null && fm2 == null) {
        return false;
    }//  ww  w .  j  a v  a2  s .  com

    if (fm1 == null && fm2 != null) {
        return true;
    }

    if (fm2 == null && fm1 != null) {
        return true;
    }

    // Both are non-null metadata objects.
    // We simply go through the 5 metadata fields, if any one of them
    // is different between the 2 versions, we declare the objects
    // different.

    String value1;
    String value2;

    // filename:

    value1 = fm1.getStudyFile().getFileName();
    value2 = fm2.getStudyFile().getFileName();

    if (value1 != null || value2 != null) {
        if ((value1 != null && !value1.equals(value2)) || (value2 != null && !value2.equals(value1))) {
            return true;
        }
    }

    // file type:
    value1 = fm1.getStudyFile().getFileType();
    value2 = fm2.getStudyFile().getFileType();

    if (value1 != null || value2 != null) {
        if ((value1 != null && !value1.equals(value2)) || (value2 != null && !value2.equals(value1))) {
            return true;
        }
    }

    // file size:
    value1 = FileUtils.byteCountToDisplaySize(new File(fm1.getStudyFile().getFileSystemLocation()).length());
    value2 = FileUtils.byteCountToDisplaySize(new File(fm2.getStudyFile().getFileSystemLocation()).length());

    if (value1 != null || value2 != null) {
        if ((value1 != null && !value1.equals(value2)) || (value2 != null && !value2.equals(value1))) {
            return true;
        }
    }

    // file category:
    value1 = fm1.getCategory();
    value2 = fm2.getCategory();

    if (value1 != null || value2 != null) {
        if ((value1 != null && !value1.equals(value2)) || (value2 != null && !value2.equals(value1))) {
            return true;
        }
    }

    // file description:
    value1 = fm1.getDescription();
    value2 = fm2.getDescription();

    if (value1 != null || value2 != null) {
        if ((value1 != null && !value1.equals(value2)) || (value2 != null && !value2.equals(value1))) {
            return true;
        }
    }

    // if we got this far, the 2 metadatas are identical:
    return false;
}

From source file:edu.harvard.iq.dvn.core.web.study.StudyVersionDifferencesPage.java

private studyFileDifferenceItem selectFileMetadataDiffs(FileMetadata fm1, FileMetadata fm2) {
    studyFileDifferenceItem fdi = new studyFileDifferenceItem();

    if (fm1 == null && fm2 == null) {
        // this should never happen; but if it does,
        // we return an empty diff object.

        return fdi;

    }/*from  w  w  w . ja  va  2  s  .  c  om*/
    if (fm2 == null) {
        fdi.setFileName1(fm1.getLabel());
        fdi.setFileType1(fm1.getStudyFile().getFileType());
        fdi.setFileSize1(FileUtils
                .byteCountToDisplaySize(new File(fm1.getStudyFile().getFileSystemLocation()).length()));
        fdi.setFileCat1(fm1.getCategory());
        fdi.setFileDesc1(fm1.getDescription());

        fdi.setFile2Empty(true);

    } else if (fm1 == null) {
        fdi.setFile1Empty(true);

        fdi.setFileName2(fm2.getLabel());
        fdi.setFileType2(fm2.getStudyFile().getFileType());
        fdi.setFileSize2(FileUtils
                .byteCountToDisplaySize(new File(fm2.getStudyFile().getFileSystemLocation()).length()));
        fdi.setFileCat2(fm2.getCategory());
        fdi.setFileDesc2(fm2.getDescription());

    } else {
        // Both are non-null metadata objects.
        // We simply go through the 5 metadata fields, if any are
        // different between the 2 versions, we add them to the
        // difference object:

        String value1;
        String value2;

        // filename:

        value1 = fm1.getLabel();
        value2 = fm2.getLabel();

        if (value1 != null || value2 != null) {
            if ((value1 != null && !value1.equals(value2)) || (value2 != null && !value2.equals(value1))) {

                if (value1 == null || value1.equals("")) {
                    value1 = "[Empty]";
                } else if (value2 == null || value2.equals("")) {
                    value2 = "[Empty]";
                }

                fdi.setFileName1(value1);
                fdi.setFileName2(value2);
            }
        }

        // NOTE:
        // fileType and fileSize will always be the same
        // for the same studyFile! -- so no need to check for differences in
        // these 2 items.

        // file category:

        value1 = fm1.getCategory();
        value2 = fm2.getCategory();

        if (value1 != null || value2 != null) {
            if ((value1 != null && !value1.equals(value2)) || (value2 != null && !value2.equals(value1))) {

                if (value1 == null || value1.equals("")) {
                    value1 = "[Empty]";
                } else if (value2 == null || value2.equals("")) {
                    value2 = "[Empty]";
                }

                fdi.setFileCat1(value1);
                fdi.setFileCat2(value2);
            }
        }

        // file description:

        value1 = fm1.getDescription();
        value2 = fm2.getDescription();

        if (value1 != null || value2 != null) {
            if ((value1 != null && !value1.equals(value2)) || (value2 != null && !value2.equals(value1))) {

                if (value1 == null || value1.equals("")) {
                    value1 = "[Empty]";
                } else if (value2 == null || value2.equals("")) {
                    value2 = "[Empty]";
                }

                fdi.setFileDesc1(value1);
                fdi.setFileDesc2(value2);
            }
        }
    }
    return fdi;
}

From source file:com.checkmarx.jenkins.CxScanBuilder.java

private CxWSResponseRunID submitScan(final AbstractBuild<?, ?> build, final CxWebService cxWebService,
        final BuildListener listener) throws IOException {
    isThisBuildIncremental = isThisBuildIncremental(build.getNumber());

    if (isThisBuildIncremental) {
        instanceLogger.info("\nScan job started in incremental scan mode\n");
    } else {/*from w w  w  . java 2  s .  co m*/
        instanceLogger.info("\nScan job started in full scan mode\n");
    }

    instanceLogger.info("Started zipping the workspace");

    try {
        // hudson.FilePath will work in distributed Jenkins installation
        FilePath baseDir = build.getWorkspace();
        if (baseDir == null) {
            throw new AbortException(
                    "Checkmarx Scan Failed: cannot acquire Jenkins workspace location. It can be due to workspace residing on a disconnected slave.");
        }
        EnvVars env = build.getEnvironment(listener);

        String combinedFilterPattern = env.expand(getFilterPattern()) + ","
                + processExcludeFolders(env.expand(getExcludeFolders()));
        // Implementation of FilePath.FileCallable allows extracting a java.io.File from
        // hudson.FilePath and still working with it in remote mode
        CxZipperCallable zipperCallable = new CxZipperCallable(combinedFilterPattern);

        final CxZipResult zipResult = baseDir.act(zipperCallable);
        instanceLogger.info(zipResult.getLogMessage());
        final FilePath tempFile = zipResult.getTempFile();
        final int numOfZippedFiles = zipResult.getNumOfZippedFiles();

        instanceLogger.info("Zipping complete with " + numOfZippedFiles + " files, total compressed size: "
                + FileUtils.byteCountToDisplaySize(tempFile.length() / 8 * 6)); // We print here the size of compressed sources before encoding to base 64
        instanceLogger.info("Temporary file with zipped and base64 encoded sources was created at: "
                + tempFile.getRemote());
        listener.getLogger().flush();
        // Create cliScanArgs object with dummy byte array for zippedFile field
        // Streaming scan web service will nullify zippedFile filed and use tempFile
        // instead

        final CliScanArgs cliScanArgs = createCliScanArgs(new byte[] {}, env);

        // Check if the project already exists
        final CxWSBasicRepsonse validateProjectRespnse = cxWebService.validateProjectName(projectName, groupId);
        CxWSResponseRunID cxWSResponseRunID;
        if (validateProjectRespnse.isIsSuccesfull()) {
            cxWSResponseRunID = cxWebService.createAndRunProject(cliScanArgs.getPrjSettings(),
                    cliScanArgs.getSrcCodeSettings().getPackagedCode(), true, true, tempFile);
        } else {
            if (projectId == 0) {
                projectId = cxWebService.getProjectId(cliScanArgs.getPrjSettings());
            }

            cliScanArgs.getPrjSettings().setProjectID(projectId);

            if (incremental) {
                cxWSResponseRunID = cxWebService.runIncrementalScan(cliScanArgs.getPrjSettings(),
                        cliScanArgs.getSrcCodeSettings().getPackagedCode(), true, true, tempFile);
            } else {
                cxWSResponseRunID = cxWebService.runScanAndAddToProject(cliScanArgs.getPrjSettings(),
                        cliScanArgs.getSrcCodeSettings().getPackagedCode(), true, true, tempFile);
            }
        }

        tempFile.delete();
        instanceLogger.info("Temporary file deleted");

        return cxWSResponseRunID;
    } catch (Zipper.MaxZipSizeReached e) {
        throw new AbortException("Checkmarx Scan Failed: Reached maximum upload size limit of "
                + FileUtils.byteCountToDisplaySize(CxConfig.maxZipSize()));
    } catch (Zipper.NoFilesToZip e) {
        throw new AbortException("Checkmarx Scan Failed: No files to scan");
    } catch (InterruptedException e) {
        throw new AbortException("Remote operation failed on slave node: " + e.getMessage());
    }
}

From source file:com.constellio.app.services.appManagement.AppManagementService.java

public void getWarFromServer(ProgressInfo progressInfo)
        throws AppManagementServiceRuntimeException.CannotConnectToServer {
    String URL_WAR = getWarURLFromServer();

    System.out.println("URL FOR WAR => " + URL_WAR);

    try {/*from w  ww .  j av  a 2  s. c o m*/
        progressInfo.reset();
        progressInfo.setTask("Getting WAR from server");
        progressInfo.setEnd(1);

        progressInfo.setProgressMessage("Downloading WAR");
        InputStream input = getInputForPost(URL_WAR, getLicenseInfo().getSignature());
        if (input == null) {
            throw new AppManagementServiceRuntimeException.CannotConnectToServer(URL_WAR);
        }
        CountingInputStream countingInputStream = new CountingInputStream(input);

        progressInfo.setProgressMessage("Creating WAR file");
        OutputStream warFileOutput = getWarFileDestination().create("war upload");

        try {
            progressInfo.setProgressMessage("Copying downloaded WAR");

            byte[] buffer = new byte[8 * 1024];
            int bytesRead;
            while ((bytesRead = countingInputStream.read(buffer)) != -1) {
                warFileOutput.write(buffer, 0, bytesRead);
                long totalBytesRead = countingInputStream.getByteCount();
                String progressMessage = FileUtils.byteCountToDisplaySize(totalBytesRead);
                progressInfo.setProgressMessage(progressMessage);
            }
        } finally {
            IOUtils.closeQuietly(countingInputStream);
            IOUtils.closeQuietly(warFileOutput);
        }
        progressInfo.setCurrentState(1);

    } catch (IOException ioe) {
        throw new AppManagementServiceRuntimeException.CannotConnectToServer(URL_WAR, ioe);
    }
}

From source file:com.lizardtech.expresszip.vaadin.ExportOptionsViewComponent.java

private void configureGridding() {
    GriddingOptions griddingOptions = new GriddingOptions();

    ExportProps props = getExportProps();
    griddingOptions.setExportWidth(props.getWidth());
    griddingOptions.setExportHeight(props.getHeight());

    griddingOptions.setGridding(gridCheckbox.booleanValue() && griddingDrawEnabled);

    if (griddingOptions.isGridding()) {

        if ((String) optGridOpt.getValue() == GRID_NUM_TILES) {
            griddingOptions.setGridMode(GriddingOptions.GridMode.DIVISION);

            int divX = Integer.parseInt(xTilesTextBox.getValue().toString());
            int divY = Integer.parseInt(yTilesTextBox.getValue().toString());
            griddingOptions.setDivX(divX > 0 ? divX : griddingOptions.getDivX());
            griddingOptions.setDivY(divY > 0 ? divY : griddingOptions.getDivY());

        } else { // GRID_TILE_DIMENSIONS or GRID_GROUND_DISTANCE

            griddingOptions.setGridMode(GriddingOptions.GridMode.METERS);
            if ((String) optGridOpt.getValue() == GRID_GROUND_DISTANCE) {
                Double groundResolution = getGroundResolution();
                griddingOptions.setTileSizeX((int) (Double.parseDouble(getDistance_X()) / groundResolution));
                griddingOptions.setTileSizeY((int) (Double.parseDouble(getDistance_Y()) / groundResolution));
            } else {
                griddingOptions.setTileSizeX(Integer.parseInt(getTile_X()));
                griddingOptions.setTileSizeY(Integer.parseInt(getTile_Y()));
            }/* w w w  .jav  a  2  s  . c o  m*/
        }
    }
    getExportProps().setGriddingOptions(griddingOptions);

    // update job summary text
    numTilesLabel.setValue(NUMBER_OF_TILES + griddingOptions.getNumTiles());

    BigInteger size = griddingOptions.getExportSize();
    String format = getImageFormat();
    if (format.equals(PNG))
        size = size.multiply(BigInteger.valueOf(85)).divide(BigInteger.valueOf(100));
    else if (format.equals(JPEG))
        size = size.divide(BigInteger.valueOf(15));
    else if (format.equals(GIF))
        size = size.multiply(BigInteger.valueOf(15)).divide(BigInteger.valueOf(100));
    else if (format.equals(BMP))
        size = size.multiply(BigInteger.valueOf(85)).divide(BigInteger.valueOf(100));
    exportSizeEstimate.setValue(DISK_ESTIMATE + FileUtils.byteCountToDisplaySize(size));
    for (ExportOptionsViewListener listener : listeners)
        listener.updateGridding(getExportProps());
}

From source file:de.mpg.imeji.logic.item.ItemService.java

/**
 * Check user disk space quota. Quota is calculated for user of target collection.
 *
 * @param file/*from  www .j a v a2  s .  c  o  m*/
 * @param col
 * @throws ImejiException
 * @return remained disk space after successfully uploaded <code>file</code>; <code>-1</code> will
 *         be returned for unlimited quota
 */
public static long checkQuota(User user, File file, CollectionImeji col) throws ImejiException {
    final User targetCollectionUser = col == null || user.getId().equals(col.getCreatedBy()) ? user
            : new UserService().retrieve(col.getCreatedBy(), Imeji.adminUser);

    final Search search = SearchFactory.create();
    final List<String> results = search
            .searchString(JenaCustomQueries.selectUserFileSize(user.getId().toString()), null, null, 0, -1)
            .getResults();
    long currentDiskUsage = 0L;
    try {
        currentDiskUsage = Long.parseLong(results.get(0).toString());
    } catch (final NumberFormatException e) {
        throw new UnprocessableError(
                "Cannot parse currentDiskSpaceUsage " + results.get(0).toString() + "; requested by user: "
                        + user.getEmail() + "; targetCollectionUser: " + targetCollectionUser.getEmail(),
                e);
    }
    final long needed = currentDiskUsage + file.length();
    if (needed > targetCollectionUser.getQuota()) {
        throw new QuotaExceededException("Data quota ("
                + QuotaUtil.getQuotaHumanReadable(targetCollectionUser.getQuota(), Locale.ENGLISH)
                + " allowed) has been exceeded (" + FileUtils.byteCountToDisplaySize(currentDiskUsage)
                + " used)");
    }
    return targetCollectionUser.getQuota() - needed;
}