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.actuate.development.tool.task.InstallBRDPro.java

private int downloadBRDPro(final IProgressMonitor monitor, boolean[] downloadFlag, final int[] step,
        final String[] stepDetail, StringBuffer errorMessage) throws IOException, InterruptedException {
    File brdproFile = new File(data.getBrdproFile());
    long fileLength = brdproFile.length();
    String defaultTaskName = "[Step " + ++step[0] + "] Downloading the BRDPro archive file...";

    File downloadFile = null;//from   w  w w .ja v a  2 s  .co  m

    if (brdproFile.isFile()) {
        monitorDownload(monitor, downloadFlag, defaultTaskName,
                new File(data.getTempDir() + "\\brdpro\\zip", brdproFile.getName()), fileLength);

        monitor.subTask(defaultTaskName + "\t[ Size: " + FileUtils.byteCountToDisplaySize(fileLength) + " ] ");
        stepDetail[0] = "Download the BRDPro archive file";
        downloadFile = getAntFile("/templates/Download.xml", true);
    } else {
        defaultTaskName = "[Step " + ++step[0] + "] Downloading the BRDPro installation files...";

        Collection<File> targetFiles = FileUtils.listFiles(brdproFile, new String[] { "cab" }, true);

        Iterator<File> fileIter = targetFiles.iterator();
        while (fileIter.hasNext()) {
            fileLength += fileIter.next().length();
        }

        monitorDownload(monitor, downloadFlag, defaultTaskName,
                new File(data.getTempDir() + "\\brdpro\\install"), fileLength);

        monitor.subTask(defaultTaskName + "\t[ Size: " + FileUtils.byteCountToDisplaySize(fileLength) + " ] ");
        stepDetail[0] = "Download the BRDPro installation files";
        downloadFile = getAntFile("/templates/Download_II.xml", true);
    }

    antProcess = Runtime.getRuntime()
            .exec(new String[] { System.getProperty("java.home") + "/bin/java", "-cp",
                    System.getProperty("java.class.path"), AntTask.class.getName(),
                    "\"" + downloadFile.getAbsolutePath() + "\"", "download" });
    interruptAntTaskErrorMessage(antProcess, errorMessage);

    int result = antProcess.waitFor();
    antProcess = null;

    return result;
}

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

/**
 * Methode gibt Zusammenfassung der auf dem Server liegenenden Daten
 * /*from  w w w.j  a  v  a  2  s.  com*/
 * @throws DirSyncException
 */
public void printStorageSummary() throws DirSyncException {
    int storedObjects = 0;
    try {
        if (!S3Utils.bucketExists(accessKey, secretKey, bucket)) {
            System.out.println("No such bucket");
            return;
        }
        System.out.println("Summary for bucket " + bucket);
        for (String str : S3Utils.listObjects(accessKey, secretKey, bucket)) {
            storedObjects++;
        }
    } catch (Exception e) {
        throw new DirSyncException(e.getMessage());
    }
    connect(false);
    int usedObjects = getAllUsedObjects().size();
    System.out.println("Total objects in use: " + usedObjects);
    System.out.println("Total stored objects: " + storedObjects);
    if (usedObjects < storedObjects) {
        System.out.println(
                (storedObjects - usedObjects) + " orphaned objects found. '-cleanup' command recommended");
    }
    System.out.println("---------------------------------------------------------------------------------");
    long totalSize = 0;
    for (Map.Entry<String, String> entry : mainIndex.getFolders().entrySet()) {
        System.out.println("Folder: " + entry.getKey());
        Folder folder = getFolder(entry.getKey());
        long folderSize = 0;
        if (folder != null) {
            for (FileInfo fi : folder.getIndexData().values()) {
                folderSize += fi.getLength();
            }
            System.out.println("Files: " + folder.getIndexData().size());
            System.out.println("Size: " + FileUtils.byteCountToDisplaySize(folderSize));
            System.out.println();
        }
        totalSize += folderSize;
    }
    System.out.println("---------------------------------------------------------------------------------");
    System.out.println("Total folders: " + mainIndex.getFolders().size());
    System.out.println("Total size: " + FileUtils.byteCountToDisplaySize(totalSize));
}

From source file:controllers.admin.PluginManagerController.java

/**
 * Import a previously exported configuration file.<br/>
 * The file is posted using a file input control.
 * //from   w  w  w. j a  v  a  2 s  .c  om
 * @param pluginConfigurationId
 *            the plugin configuration id
 * @return
 */
@Restrict({ @Group(IMafConstants.ADMIN_PLUGIN_MANAGER_PERMISSION) })
@BodyParser.Of(value = BodyParser.MultipartFormData.class, maxLength = MAX_CONFIG_FILE_SIZE)
public Promise<Result> importConfiguration(Long pluginConfigurationId) {
    // Perform the upload
    return Promise.promise(new Function0<Result>() {
        @Override
        public Result apply() throws Throwable {
            try {
                if (log.isDebugEnabled()) {
                    log.debug("Configuration upload requested for " + pluginConfigurationId);
                }
                MultipartFormData body = request().body().asMultipartFormData();
                FilePart filePart = body.getFile("import");
                if (filePart != null) {
                    if (log.isDebugEnabled()) {
                        log.debug("A file has been found");
                    }
                    String configuration = IOUtils.toString(new FileInputStream(filePart.getFile()));
                    if (log.isDebugEnabled()) {
                        log.debug("Content of the uploaded file is " + configuration);
                    }
                    try {
                        getPluginManagerService().importPluginConfiguration(pluginConfigurationId,
                                configuration);
                        if (log.isDebugEnabled()) {
                            log.debug("Plugin configuration uploaded");
                        }
                        Utilities.sendWarningFlashMessage(Msg.get(
                                "admin.plugin_manager.configuration.view.panel.configuration.import.success"));
                    } catch (PluginException e) {
                        log.error("Attempt to upload an invalid plugin configuration for "
                                + pluginConfigurationId, e);
                        Utilities.sendErrorFlashMessage(
                                Msg.get("admin.plugin_manager.configuration_block.import.error"));
                    }
                } else {
                    Utilities.sendErrorFlashMessage(Msg.get("form.input.file_field.no_file"));
                }
            } catch (Exception e) {
                Utilities.sendErrorFlashMessage(Msg.get("admin.shared_storage.upload.file.size.invalid",
                        FileUtils.byteCountToDisplaySize(MAX_CONFIG_FILE_SIZE)));
                String message = String.format("Failure while uploading the plugin configuration for %d",
                        pluginConfigurationId);
                log.error(message);
                throw new IOException(message, e);
            }
            return redirect(routes.PluginManagerController.pluginConfigurationDetails(pluginConfigurationId));
        }
    });
}

From source file:com.actuate.development.tool.task.InstallBRDPro.java

private void initSubtask(final IProgressMonitor monitor, final int[] step, final DefaultLogger consoleLogger,
        String subtaskName[], final boolean[] flag, File file) {
    subtaskName[0] += "\t[ Size: " + FileUtils.byteCountToDisplaySize(file.length()) + " ] ";
    interruptOutput(monitor, step, consoleLogger, flag, subtaskName);
    monitor.subTask(subtaskName[0]);/* w  w  w.j  a v a2  s.c o  m*/
}

From source file:com.actuate.development.tool.task.InstallBRDPro.java

private void monitorDownload(final IProgressMonitor monitor, final boolean[] flag, final String defaultTaskName,
        final File file, final long size) {
    downloadThread = new Thread("Monitor Download") {

        public void run() {
            long donwloadSize = file.length();
            if (file.isDirectory()) {
                Collection<File> targetFiles = FileUtils.listFiles(file, new String[] { "cab" }, true);
                Iterator<File> fileIter = targetFiles.iterator();
                while (fileIter.hasNext()) {
                    donwloadSize += fileIter.next().length();
                }/*from   www  .jav a  2s. com*/
            }
            long time = System.currentTimeMillis();
            final Module module = current[0];
            while (!flag[0]) {
                if (module != current[0])
                    break;
                if (file.exists()) {
                    if (file.length() != donwloadSize) {
                        if (module != current[0])
                            break;
                        String speed = FileUtil.format(((float) (file.length() - donwloadSize))
                                / (((float) (System.currentTimeMillis() - time)) / 1000)) + "/s";
                        donwloadSize = file.length();
                        time = System.currentTimeMillis();
                        monitor.subTask(defaultTaskName + "\t[ " + (donwloadSize * 100 / size) + "% , Speed: "
                                + speed + " , Size: " + FileUtils.byteCountToDisplaySize(size) + " ]");
                    }
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                }
            }
        }
    };
    downloadThread.setDaemon(true);
    downloadThread.start();
}

From source file:ca.uviccscu.lp.server.main.MainFrame.java

public static void updateGameInterfaceFromStorage() {
    wipeGameTableRows();/*from  ww w. j a v  a2s .  c  om*/
    Iterator it = GamelistStorage.getAllGames().listIterator();
    while (it.hasNext()) {
        Game g = (Game) it.next();
        addFreeRow();
        int row = jTable1.getRowCount() - 1;
        jTable1.getModel().setValueAt(g.gameName, row, 0);
        jTable1.getModel().setValueAt(g.gameAbsoluteExecPath, row, 1);
        jTable1.getModel().setValueAt(FileUtils.byteCountToDisplaySize(g.gameSize), row, 2);
        jTable1.getModel().setValueAt(GamelistStorage.gameStatusToString(g.gameStatus), row, 3);
    }
    jTextField1.setText(SettingsManager.getStorage().getFirstCfgValue("clientgamefolder"));
    jTextField2.setText(SettingsManager.getStorage().getFirstCfgValue("clientgamefolder"));
    jTextField3.setText(Shared.workingDirectory);
    jTextField4.setText(SettingsManager.getStorage().getFirstCfgValue("serverutorrentlocation"));
    jLabel21.setText("Server version: " + Shared.serverConfigVersion);
}

From source file:ca.uviccscu.lp.server.main.MainFrame.java

public static void updateNetworkInterfaceFromStorage() {
    wipeGameTableRows();//from   w w  w  . j a v a2 s . c om
    Iterator it = GamelistStorage.getAllGames().listIterator();
    while (it.hasNext()) {
        Game g = (Game) it.next();
        addFreeRow();
        int row = jTable1.getRowCount() - 1;
        jTable1.getModel().setValueAt(g.gameName, row, 0);
        jTable1.getModel().setValueAt(g.gameAbsoluteExecPath, row, 1);
        jTable1.getModel().setValueAt(FileUtils.byteCountToDisplaySize(g.gameSize), row, 2);
        jTable1.getModel().setValueAt(GamelistStorage.gameStatusToString(g.gameStatus), row, 3);
    }
    jTextField1.setText(SettingsManager.getStorage().getFirstCfgValue("clientgamefolder"));
    jTextField2.setText(SettingsManager.getStorage().getFirstCfgValue("clientgamefolder"));
    jTextField3.setText(Shared.workingDirectory);
    jTextField4.setText(SettingsManager.getStorage().getFirstCfgValue("serverutorrentlocation"));
    jLabel21.setText("Server version: " + Shared.serverConfigVersion);
}

From source file:ca.uviccscu.lp.server.main.MainFrame.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    l.info("Add game action activated");
    MainFrame.lockInterface();/*  w w  w  .jav a  2s  . c o m*/
    MainFrame.updateTask("Adding game...", true);
    AddGameDialog addGameDialog = new AddGameDialog(this, true);
    addGameDialog.setLocationRelativeTo(null);
    //addGameDialog.setVisible(true);
    final Game g = addGameDialog.popupCreateDialog();
    if (g != null) {
        l.trace("Analyzing game: " + g.gameAbsoluteFolderPath);
        MainFrame.updateTask("Adding game...", true);
        final int row = getNextFreeRowNumber();
        addFreeRow();
        jTable1.getModel().setValueAt(g.gameName, row, 0);
        jTable1.getModel().setValueAt(g.gameAbsoluteExecPath, row, 1);
        jTable1.getModel().setValueAt(GamelistStorage.gameStatusToString(g.gameStatus), row, 3);
        MainFrame.updateProgressBar(0, 0, 0, "Analyzing game", true, true);
        final ObjectPlaceholder obj = new ObjectPlaceholder();
        SwingWorker worker = new SwingWorker<Long, Void>() {

            @Override
            public Long doInBackground() throws IOException {
                l.trace("Checking size");
                MainFrame.updateProgressBar(0, 0, 0, "Analyzing game size", true, true);
                obj.payload = FileUtils.sizeOfDirectory(new File(g.gameAbsoluteFolderPath));
                l.trace("Checking files");
                MainFrame.updateProgressBar(0, 0, 0, "Analyzing game files", true, true);
                g.gameFileNumber = FileUtils.listFiles(new File(g.gameAbsoluteFolderPath), null, true).size();
                l.trace("Checking CRC32");
                MainFrame.updateProgressBar(0, 0, 0, "Analyzing game signature", true, true);
                g.gameExecCRC32 = FileUtils.checksumCRC32(new File(g.gameAbsoluteExecPath));
                return ((Long) obj.payload);
            }

            public void done() {
                l.trace("Finishing game check");
                MainFrame.updateProgressBar(0, 0, 0, "Finishing game creation", false, false);
                g.gameSize = ((Long) obj.payload);
                /*
                double mbsize = Math.ceil(g.gameSize / (1024 * 1024));
                jTable1.getModel().setValueAt(mbsize, row, 2);
                 * 
                 */
                jTable1.getModel().setValueAt(FileUtils.byteCountToDisplaySize(g.gameSize), row, 2);
                Shared.lastCreatedGame = null;
                GamelistStorage.addGame(g);
                jTable1.getModel().setValueAt(GamelistStorage.gameStatusToString(g.gameStatus), row, 3);
                g.gameStatus = 0;
                SettingsManager.getStorage().storeGame(g);
                /*
                try {
                SettingsManager.storeCurrentSettings();
                } catch (Exception ex) {
                l.debug(ex.getMessage(), ex);
                }
                 * 
                 */
                l.trace("Done adding game");
                MainFrame.setReportingIdle();
                MainFrame.unlockInterface();
            }
        };
        worker.execute();
    } else {
        l.debug("Add game dialog - null game returned, nothing done");
        MainFrame.setReportingIdle();
        MainFrame.unlockInterface();
    }
    MainFrame.updateGameInterfaceFromStorage();
}

From source file:net.sf.zekr.common.config.ApplicationConfig.java

public AudioData addNewRecitationPack(File zipFileToImport, String destDir,
        IntallationProgressListener progressListener) throws ZekrMessageException {
    try {//from w  w w .  j  a  va  2  s.com
        ZipFile zipFile = new ZipFile(zipFileToImport);
        InputStream is = zipFile.getInputStream(new ZipEntry(ApplicationPath.RECITATION_DESC));
        if (is == null) {
            logger.debug(
                    String.format("Could not find recitation descriptor %s in the root of the zip archive %s.",
                            zipFileToImport, ApplicationPath.RECITATION_DESC));
            throw new ZekrMessageException("INVALID_RECITATION_FORMAT",
                    new String[] { zipFileToImport.getName() });
        }

        String tempFileName = System.currentTimeMillis() + "-" + ApplicationPath.RECITATION_DESC;
        tempFileName = System.getProperty("java.io.tmpdir") + "/" + tempFileName;
        File recitPropsFile = new File(tempFileName);
        OutputStreamWriter output = null;
        InputStreamReader input = null;
        try {
            output = new OutputStreamWriter(new FileOutputStream(recitPropsFile), "UTF-8");
            input = new InputStreamReader(is, "UTF-8");
            IOUtils.copy(input, output);
        } finally {
            IOUtils.closeQuietly(output);
            IOUtils.closeQuietly(input);
        }
        logger.debug("Add new recitation: " + recitPropsFile);

        AudioData newAudioData = loadAudioData(recitPropsFile, false);
        if (newAudioData == null || newAudioData.getId() == null) {
            logger.debug("Invalid recitation descriptor: " + recitPropsFile);
            throw new ZekrMessageException("INVALID_RECITATION_FORMAT",
                    new String[] { zipFileToImport.getName() });
        }
        File newRecitPropsFile = new File(destDir, newAudioData.id + ".properties");

        if (newRecitPropsFile.exists()) {
            newRecitPropsFile.delete();
        }
        FileUtils.moveFile(recitPropsFile, newRecitPropsFile);

        /*
        ZipEntry recFolderEntry = zipFile.getEntry(newAudioData.id);
        if (recFolderEntry == null || !recFolderEntry.isDirectory()) {
           logger.warn(String.format("Recitation audio folder (%s) doesn't exist in the root of archive %s.",
          newAudioData.id, zipFileToImport));
           throw new ZekrMessageException("INVALID_RECITATION_FORMAT", new String[] { zipFileToImport.getName() });
        }
        */

        AudioData installedAudioData = audio.get(newAudioData.id);
        if (installedAudioData != null) {
            if (newAudioData.compareTo(installedAudioData) < 0) {
                throw new ZekrMessageException("NEWER_VERSION_INSTALLED", new String[] {
                        recitPropsFile.toString(), newAudioData.lastUpdate, installedAudioData.lastUpdate });
            }
        }

        newAudioData.file = newRecitPropsFile;

        logger.info(String.format("Start uncompressing recitation: %s with size: %s to %s.",
                zipFileToImport.getName(), FileUtils.byteCountToDisplaySize(zipFileToImport.length()),
                destDir));

        boolean result;
        try {
            result = ZipUtils.extract(zipFileToImport, destDir, progressListener);
        } finally {
            File file = new File(newRecitPropsFile.getParent(), ApplicationPath.RECITATION_DESC);
            if (file.exists()) {
                FileUtils.deleteQuietly(file);
            }
        }
        if (result) {
            logger.info("Uncompressing process done: " + zipFileToImport.getName());
            audio.add(newAudioData);
        } else {
            logger.info("Uncompressing process intrrrupted: " + zipFileToImport.getName());
        }

        // FileUtils.deleteQuietly(new File(newRecitPropsFile.getParent(), ApplicationPath.RECITATION_DESC));

        progressListener.finish(newAudioData);

        return result ? newAudioData : null;
    } catch (ZekrMessageException zme) {
        throw zme;
    } catch (Exception e) {
        logger.error("Error occurred while adding new recitation archive.", e);
        throw new ZekrMessageException("RECITATION_LOAD_FAILED",
                new String[] { zipFileToImport.getName(), e.toString() });
    }
}

From source file:nl.strohalm.cyclos.controls.BaseAction.java

/**
 * The Struts standard execute method is reserved, being the executeAction the one that subclasses must implement
 *//* ww  w  . jav a2s  .  com*/
@Override
public final ActionForward execute(final ActionMapping actionMapping, final ActionForm actionForm,
        final HttpServletRequest request, final HttpServletResponse response) throws Exception {

    // Check for uploads that exceeded the max length
    final Boolean maxLengthExceeded = (Boolean) request
            .getAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED);
    if (maxLengthExceeded != null && maxLengthExceeded) {
        final LocalSettings settings = settingsService.getLocalSettings();
        return ActionHelper.sendError(actionMapping, request, response, "error.maxUploadSizeExceeded",
                FileUtils.byteCountToDisplaySize(settings.getMaxUploadBytes()));
    }
    HttpSession session = request.getSession(false);

    // Validate the logged user
    User user = null;
    try {
        user = validate(request, response, actionMapping);
        if (user == null) {
            return null;
        }
    } catch (final LoggedOutException e) {
        // Invalidate the current session
        if (session != null) {
            session.invalidate();
        }
        // Create a new session
        session = request.getSession();
        ActionForward forward = resolveLoginForward(actionMapping, request);
        // If the action is stored on navigation path, we should return to it after re-login
        if (storePath(actionMapping, request)) {
            // Store the path on session, so that after logging in, the user will stay on this page
            String path = actionMapping.getPath();
            final String queryString = request.getQueryString();
            if (StringUtils.isNotEmpty(queryString)) {
                path += "?" + queryString;
            }
            session.setAttribute("returnTo", path);
            session.setAttribute("loggedOut", true);

            // Redirect to the login page
            final Map<String, Object> params = new HashMap<String, Object>();
            if (path.contains("/operator/")) {
                params.put("operator", true);
            }
            forward = ActionHelper.redirectWithParams(request, forward, params);
        }
        return forward;
    } catch (final AccessDeniedException e) {
        if (session != null) {
            session.invalidate();
        }
        return ActionHelper.sendError(actionMapping, request, response, "error.accessDenied");
    } catch (final Exception e) {
        CurrentTransactionData.setError(e);
        actionHelper.generateLog(request, getServlet().getServletContext(), e);
        LOG.error("Application error on " + getClass().getName(), e);
        return ActionHelper.sendError(actionMapping, request, response, null);
    }

    // Check if the member shall accept a registration agreement or change the expired password before proceeding
    if (session != null) {
        String forwardName = null;
        if (Boolean.TRUE.equals(session.getAttribute("shallAcceptRegistrationAgreement"))) {
            // AcceptRegistrationAgreementAction is a BasePublicFormAction, not BaseAction, so, we don't need to check if this is not that action
            forwardName = RequestHelper.isPosWeb(request) ? "poswebAcceptRegistrationAgreement"
                    : "acceptRegistrationAgreement";
        } else if (Boolean.TRUE.equals(session.getAttribute("expiredPassword"))
                && !(this instanceof ChangeExpiredPasswordAction)) {
            // Only redirect to change expired password if this is not that action

            if (RequestHelper.isPosWeb(request)) {
                forwardName = "poswebChangeExpiredPassword";
            } else {
                return actionHelper.getForwardFor(LoggedUser.element().getNature(), "changeExpiredPassword",
                        true);
            }
        }
        if (forwardName != null) {
            return actionMapping.findForward(forwardName);
        }
    }

    // Perform special actions when the request is coming from menu
    if (RequestHelper.isFromMenu(request)) {
        request.setAttribute("fromMenu", true);
    }

    // Create an action context
    final ActionContext context = new ActionContext(actionMapping, actionForm, request, response, user,
            messageHelper);
    request.setAttribute("formAction", actionMapping.getPath());

    try {
        // checks access to the action
        actionAccessMonitor.requestAccess(context);

        // Store the navigation data
        final Navigation navigation = context.getNavigation();
        if (storePath(actionMapping, request)) {
            navigation.setLastAction(actionMapping);
            navigation.store(context);
        }

        // Process the action
        final ActionForward forward = executeAction(context);
        return forward;
    } catch (final PermissionDeniedException e) {
        CurrentTransactionData.setError(e);
        final boolean userBlocked = accessService.notifyPermissionDeniedException();
        if (userBlocked) {
            request.getSession(false).invalidate();
            return ActionHelper.sendError(actionMapping, request, response, "login.error.blocked");
        } else {
            return ActionHelper.sendError(actionMapping, request, response, "error.permissionDenied");
        }
    } catch (final QueryParseException e) {
        CurrentTransactionData.setError(e);
        return ActionHelper.sendError(actionMapping, request, response, "error.queryParse");
    } catch (final ImageHelper.UnknownImageTypeException e) {
        CurrentTransactionData.setError(e);
        final String recognizedTypes = StringUtils.join(ImageType.values(), ", ");
        return ActionHelper.sendError(actionMapping, request, response, "error.unknownImageType",
                recognizedTypes);
    } catch (final ImageException e) {
        CurrentTransactionData.setError(e);
        return ActionHelper.sendError(actionMapping, request, response, e.getKey());
    } catch (final ValidationException e) {
        CurrentTransactionData.setError(e);
        return ActionHelper.handleValidationException(actionMapping, request, response, e);
    } catch (final EntityNotFoundException e) {
        // An entity not found is handled as a validation exception
        return ActionHelper.handleValidationException(actionMapping, request, response,
                new ValidationException());
    } catch (final ExternalException e) {
        CurrentTransactionData.setError(e);
        return ActionHelper.sendErrorWithMessage(actionMapping, request, response, e.getMessage());
    } catch (final Exception e) {
        CurrentTransactionData.setError(e);
        actionHelper.generateLog(request, getServlet().getServletContext(), e);
        LOG.error("Application error on " + getClass().getName(), e);
        return ActionHelper.sendError(actionMapping, request, response, null);
    }
}