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:de.hybris.platform.customerticketingaddon.controllers.pages.AccountSupportTicketsPageController.java

/**
 * Get Ticket Details.//ww w .j  a v  a2  s .  c o  m
 *
 * @param ticketId
 * @param model
 * @param redirectModel
 * @param ticketUpdated
 * @return View String
 * @throws CMSItemNotFoundException
 */
@RequestMapping(value = "/support-ticket/"
        + SUPPORT_TICKET_CODE_PATH_VARIABLE_PATTERN, method = RequestMethod.GET)
@RequireHardLogIn
public String getSupportTicket(@PathVariable("ticketId") final String ticketId, final Model model,
        @RequestParam(value = "ticketUpdated", required = false, defaultValue = "false") final boolean ticketUpdated,
        final RedirectAttributes redirectModel) throws CMSItemNotFoundException {
    storeCmsPageInModel(model,
            getContentPageForLabelOrId(CustomerticketingaddonConstants.UPDATE_SUPPORT_TICKET_PAGE));
    setUpMetaDataForContentPage(model,
            getContentPageForLabelOrId(CustomerticketingaddonConstants.UPDATE_SUPPORT_TICKET_PAGE));

    model.addAttribute(WebConstants.BREADCRUMBS_KEY,
            getBreadcrumbs(CustomerticketingaddonConstants.TEXT_SUPPORT_TICKETING_UPDATE));
    model.addAttribute(ThirdPartyConstants.SeoRobots.META_ROBOTS,
            ThirdPartyConstants.SeoRobots.NOINDEX_NOFOLLOW);
    model.addAttribute(CustomerticketingaddonConstants.SUPPORT_TICKET_FORM, new SupportTicketForm());
    model.addAttribute(CustomerticketingaddonConstants.MAX_UPLOAD_SIZE, Long.valueOf(maxUploadSizeValue));
    model.addAttribute(CustomerticketingaddonConstants.MAX_UPLOAD_SIZE_MB,
            FileUtils.byteCountToDisplaySize(maxUploadSizeValue));
    try {
        final TicketData ticketData = ticketFacade.getTicket(XSSEncoder.encodeHTML(ticketId));
        model.addAttribute(CustomerticketingaddonConstants.SUPPORT_TICKET_DATA, ticketData);
    } catch (final Exception e) {
        LOG.error("Attempted to load ticket details that does not exist or is not visible", e);
        GlobalMessages.addFlashMessage(redirectModel, GlobalMessages.ERROR_MESSAGES_HOLDER,
                CustomerticketingaddonConstants.TEXT_SUPPORT_TICKETING_TRY_LATER, null);
        return REDIRECT_TO_SUPPORT_TICKETS_PAGE;
    }

    if (ticketUpdated) {
        GlobalMessages.addConfMessage(model, CustomerticketingaddonConstants.TEXT_SUPPORT_TICKETING_ADDED);
    }

    return getViewForPage(model);
}

From source file:controllers.admin.SharedStorageManagerController.java

/**
 * Upload a new file into the shared storage.
 * /*  w  ww .  j a  v  a 2 s  .  c  o m*/
 * @param isInput
 *            if true the field name containing the file uploaded is
 *            IFrameworkConstants.INPUT_FOLDER_NAME
 *            (IFrameworkConstants.OUTPUT_FOLDER_NAME otherwise)
 * @return
 */
@BodyParser.Of(value = BodyParser.MultipartFormData.class, maxLength = MAX_FILE_SIZE)
public Promise<Result> upload(final boolean isInput) {
    final String folderName = isInput ? IFrameworkConstants.INPUT_FOLDER_NAME
            : IFrameworkConstants.OUTPUT_FOLDER_NAME;
    final

    // Test if the max number of files is not exceeded
    String[] files;
    try {
        files = getSharedStorageService().getFileList("/" + folderName);
    } catch (IOException e1) {
        return redirectToIndexAsPromiseWithErrorMessage(null);
    }
    int numberOfFiles = files != null ? files.length : 0;
    if (numberOfFiles >= getConfiguration().getInt("maf.sftp.store.maxfilenumber")) {
        return redirectToIndexAsPromiseWithErrorMessage(
                Msg.get("admin.shared_storage.upload.error.max_number"));
    }

    // Perform the upload
    return Promise.promise(new Function0<Result>() {
        @Override
        public Result apply() throws Throwable {
            try {
                MultipartFormData body = request().body().asMultipartFormData();
                FilePart filePart = body.getFile(folderName);
                if (filePart != null) {
                    IOUtils.copy(new FileInputStream(filePart.getFile()), getSharedStorageService()
                            .writeFile("/" + folderName + "/" + filePart.getFilename(), true));
                    Utilities.sendSuccessFlashMessage(Msg.get("form.input.file_field.success"));
                } 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_FILE_SIZE)));
                String message = String.format("Failure while uploading a new file in %s", folderName);
                log.error(message);
                throw new IOException(message, e);
            }
            return redirect(routes.SharedStorageManagerController.index());
        }
    });
}

From source file:cu.uci.coj.restapi.controller.RestProblemsController.java

@ApiOperation(value = "Obtener descripcin del problema", notes = "Devuelve la descripcin de un problema dado su identificador.", response = ProblemDescriptionRest.class)
@ApiResponses(value = { @ApiResponse(code = 404, message = "bad pid") })
@RequestMapping(value = "/{pid}", method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody//from  www.j a  v a  2 s  .  co  m
public ResponseEntity<?> getProblemDescriptionsByID(
        @ApiParam(value = "Identificador del problema") @PathVariable int pid,
        @ApiParam(value = "Idioma del problema (Ver filter)") @RequestParam(required = false, value = "locale", defaultValue = "en") String locale) {

    if (!problemDAO.exists(pid))
        return new ResponseEntity<>(ErrorUtils.BAD_PID, HttpStatus.NOT_FOUND);

    Problem p;
    try {
        p = problemDAO.getProblemByCode(locale, pid, false);
    } catch (NullPointerException ne) {
        return new ResponseEntity<>(ErrorUtils.BAD_PID, HttpStatus.NOT_FOUND);
    }
    p.setDate(p.getDate().split(" ")[0]);
    problemDAO.fillProblemLanguages(p);
    problemDAO.fillProblemLimits(p);
    Recommender recommender = new Recommender(userDAO, problemDAO, recommenderDAO);
    List<Problem> recommendations = recommender.findSimilarProblems(p);

    List<String> languages = new LinkedList();
    List<Long> totaltime = new LinkedList();
    List<Long> testtime = new LinkedList();
    List<String> memory = new LinkedList();
    List<String> size = new LinkedList();
    for (Language leng : p.getLanguages()) {
        for (Limits limit : p.getLimits()) {
            if (leng.getLid() == limit.getLanguageId()) {
                totaltime.add(limit.getMaxTotalExecutionTime());
                testtime.add(limit.getMaxCaseExecutionTime());
                memory.add(FileUtils.byteCountToDisplaySize(limit.getMaxMemory()));
                size.add(FileUtils.byteCountToDisplaySize(limit.getMaxSourceCodeLenght()));
            }

        }
        languages.add(leng.getLanguage());
    }

    List<String> recomended = new LinkedList();

    for (Problem pro : recommendations) {
        recomended.add("" + pro.getPid());
    }

    String[] arreglo = author_source(pid);
    ProblemDescriptionRest problemDescrptions;
    problemDescrptions = new ProblemDescriptionRest(p.getAuthor(), arreglo[0].trim(), arreglo[1].trim(),
            p.getUsername(), p.getDate(), totaltime, testtime, memory, "64 MB", size, languages,
            p.getDescription(), p.getInput(), p.getOutput(), p.getInputex(), p.getOutputex(), p.getComments(),
            recomended);

    return new ResponseEntity<>(problemDescrptions, HttpStatus.OK);

}

From source file:com.loop81.fxcomparer.FXComparerController.java

/** Convert the given difference to a more readable string using {@link FileUtils#byteCountToDisplaySize(long)}. */
private String convertdifferenceToReadableString(long difference) {
    if (difference < FileUtils.ONE_KB && difference > -1 * FileUtils.ONE_KB) {
        return (difference > 0 ? "+" : "") + FileUtils.byteCountToDisplaySize(difference);
    } else {/*from   ww  w.j a  v a  2s.  com*/
        return (difference > 0 ? "+" : "-") + FileUtils.byteCountToDisplaySize(Math.abs(difference)) + " ("
                + difference + " " + MessageBundle.getString("general.bytes") + ")";
    }
}

From source file:com.netflix.suro.sink.localfile.LocalFileSink.java

@Override
public String getStat() {
    return String.format("%d msgs, %s written, %s have empty routing key. %s failures of closing files",
            writtenMessages, FileUtils.byteCountToDisplaySize(writtenBytes), emptyRoutingKeyCount,
            errorClosedFiles);//from   w ww .  ja  v  a2  s  .com
}

From source file:info.magnolia.ui.form.field.upload.basic.BasicUploadField.java

/**
 * Add File Info./*from   w  w  w  . j a  va 2  s  .  c  o  m*/
 */
protected Component getFileDetailSize() {
    Label label = new Label("", ContentMode.HTML);
    label.setCaption(i18n.translate(fileDetailSizeCaption));
    label.setValue(FileUtils.byteCountToDisplaySize(getValue().getFileSize()));
    return label;
}

From source file:gov.nih.nci.rembrandt.web.inbox.QueryInbox.java

public String checkAllDownloadStatus() {

    try {//from  w  w  w. ja v  a2s .c  o  m
        rbtCaArrayFileDownloadManagerInterface = ApplicationContext.getCaArrayFileDownloadManagerInterface();
        JSONArray dlArray = new JSONArray();
        JSONObject dlObject = new JSONObject();
        if (rbtCaArrayFileDownloadManagerInterface == null) {
            dlObject.put("name", "caArray server unavaiable");
            dlObject.put("status", DownloadStatus.Error);
            dlObject.put("url", "");
            dlObject.put("size", "");
        } else {
            rbtCaArrayFileDownloadManagerInterface
                    .setBusinessCacheManager(ApplicationFactory.getBusinessTierCache());
            Collection<DownloadTask> downloads = rbtCaArrayFileDownloadManagerInterface
                    .getAllSessionDownloads(session.getId());

            //////// TESTing
            //         dlObject.put("name", "My first download");
            //         dlObject.put("status", "downloading");
            //         dlArray.add(dlObject);
            //         dlObject = new JSONObject();
            //         dlObject.put("name", "My second download");
            //         dlObject.put("status", "zipping");
            //         dlArray.add(dlObject);
            ////// END TESTING

            for (DownloadTask dl : downloads) {
                if (dl.getListOfZipFileLists() == null) {
                    dlObject = new JSONObject();
                    dlObject.put("name", dl.getZipFileName());
                    dlObject.put("status", dl.getDownloadStatus().toString());
                    if (dl.getZipFileName() != null)
                        dlObject.put("url", zipFileUrl + dl.getZipFileName());
                    else
                        dlObject.put("url", "");

                    ;
                    if (dl.getZipFileSize() != null)
                        dlObject.put("size", FileUtils.byteCountToDisplaySize(dl.getZipFileSize()));
                    else
                        dlObject.put("size", "");

                    dlArray.add(dlObject);
                } else {
                    List<ZipItem> zipItems = dl.getListOfZipFileLists();
                    for (ZipItem zi : zipItems) {
                        dlObject = new JSONObject();
                        dlObject.put("name", zi.getFileName());
                        dlObject.put("status", dl.getDownloadStatus().toString());
                        if (zi.getFileName() != null)
                            dlObject.put("url", zipFileUrl + zi.getFileName());
                        else
                            dlObject.put("url", "");

                        ;
                        if (zi.getFileSize() != null)
                            dlObject.put("size", FileUtils.byteCountToDisplaySize(zi.getFileSize()));
                        else
                            dlObject.put("size", "");

                        dlArray.add(dlObject);
                    }
                }
            }
        }
        return dlArray.toString();

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return "error";
    }
}

From source file:fr.inria.lille.repair.nopol.NoPol.java

private void logSystemInformation() {
    this.logger.info("Available processors (cores): " + Runtime.getRuntime().availableProcessors());

    /* Total amount of free memory available to the JVM */
    this.logger.info("Free memory: " + FileUtils.byteCountToDisplaySize(Runtime.getRuntime().freeMemory()));

    /* This will return Long.MAX_VALUE if there is no preset limit */
    long maxMemory = Runtime.getRuntime().maxMemory();
    /* Maximum amount of memory the JVM will attempt to use */
    this.logger.info("Maximum memory: "
            + (maxMemory == Long.MAX_VALUE ? "no limit" : FileUtils.byteCountToDisplaySize(maxMemory)));

    /* Total memory currently available to the JVM */
    this.logger.info("Total memory available to JVM: "
            + FileUtils.byteCountToDisplaySize(Runtime.getRuntime().totalMemory()));

    this.logger.info("Java version: " + Runtime.class.getPackage().getImplementationVersion());
    this.logger.info("JAVA_HOME: " + System.getenv("JAVA_HOME"));
    this.logger.info("PATH: " + System.getenv("PATH"));
}

From source file:de.interactive_instruments.etf.webapp.controller.TestObjectController.java

@RequestMapping(value = "/testobjects/add-file-to", method = RequestMethod.POST)
public String addFileTestData(@ModelAttribute("testObject") @Valid TestObjectDto testObject,
        BindingResult result, MultipartHttpServletRequest request, Model model)
        throws IOException, URISyntaxException, StoreException, ParseException, NoSuchAlgorithmException {
    if (SUtils.isNullOrEmpty(testObject.getLabel())) {
        throw new IllegalArgumentException("Label is empty");
    }//from w  w w.  j  av a 2 s.  com

    if (result.hasErrors()) {
        return showCreateDoc(model, testObject);
    }

    final GmlAndXmlFilter filter;
    final String regex = testObject.getProperty("regex");
    if (regex != null && !regex.isEmpty()) {
        filter = new GmlAndXmlFilter(new RegexFileFilter(regex));
    } else {
        filter = new GmlAndXmlFilter();
    }

    // Transfer uploaded data
    final MultipartFile multipartFile = request.getFile("testObjFile");
    if (multipartFile != null && !multipartFile.isEmpty()) {
        // Transfer file to tmpUploadDir
        final IFile testObjFile = this.tmpUploadDir
                .secureExpandPathDown(testObject.getLabel() + "_" + multipartFile.getOriginalFilename());
        testObjFile.expectFileIsWritable();
        multipartFile.transferTo(testObjFile);
        final String type;
        try {
            type = MimeTypeUtils.detectMimeType(testObjFile);
            if (!type.equals("application/xml") && !type.equals("application/zip")) {
                throw new IllegalArgumentException(type + " is not supported");
            }
        } catch (Exception e) {
            result.reject("l.upload.invalid", new Object[] { e.getMessage() }, "Unable to use file: {0}");
            return showCreateDoc(model, testObject);
        }

        // Create directory for test data file
        final IFile testObjectDir = testDataDir
                .secureExpandPathDown(testObject.getLabel() + ".upl." + getSimpleRandomNumber(4));
        testObjectDir.ensureDir();

        if (type.equals("application/zip")) {
            // Unzip files to test directory
            try {
                testObjFile.unzipTo(testObjectDir, filter);
            } catch (IOException e) {
                try {
                    testObjectDir.delete();
                } catch (Exception de) {
                    ExcUtils.supress(de);
                }
                result.reject("l.decompress.failed", new Object[] { e.getMessage() },
                        "Unable to decompress file: {0}");
                return showCreateDoc(model, testObject);
            } finally {
                // delete zip file
                testObjFile.delete();
            }
        } else {
            // Move XML to test directory
            testObjFile.copyTo(testObjectDir.getPath() + File.separator + multipartFile.getOriginalFilename());
        }
        testObject.addResource("data", testObjectDir.toURI());
        testObject.getProperties().setProperty("uploaded", "true");
    } else {
        final URI resURI = testObject.getResourceById("data");
        if (resURI == null) {
            throw new StoreException("Workflow error. Data path resource not set.");
        }
        final IFile absoluteTestObjectDir = testDataDir.secureExpandPathDown(resURI.getPath());
        testObject.getResources().clear();
        testObject.getResources().put(EidFactory.getDefault().createFromStrAsStr("data"),
                absoluteTestObjectDir.toURI());

        // Check if file exists
        final IFile sourceDir = new IFile(new File(testObject.getResourceById("data")));
        try {
            sourceDir.expectDirIsReadable();
        } catch (Exception e) {
            result.reject("l.testObject.testdir.insufficient.rights", new Object[] { e.getMessage() },
                    "Insufficient rights to read directory: {0}");
            return showCreateDoc(model, testObject);
        }
        testObject.getProperties().setProperty("uploaded", "false");
    }

    final FileHashVisitor v = new FileHashVisitor(filter);
    Files.walkFileTree(new File(testObject.getResourceById("data")).toPath(),
            EnumSet.of(FileVisitOption.FOLLOW_LINKS), 5, v);

    if (v.getFileCount() == 0) {
        if (regex != null && !regex.isEmpty()) {
            result.reject("l.testObject.regex.null.selection", new Object[] { regex },
                    "No files were selected with the regular expression \"{0}\"!");
        } else {
            result.reject("l.testObject.testdir.no.xml.gml.found",
                    "No file were found in the directory with a gml or xml file extension");
        }
        return showCreateDoc(model, testObject);
    }
    VersionDataDto vd = new VersionDataDto();
    vd.setItemHash(v.getHash());
    testObject.getProperties().setProperty("files", String.valueOf(v.getFileCount()));
    testObject.getProperties().setProperty("size", String.valueOf(v.getSize()));
    testObject.getProperties().setProperty("sizeHR", FileUtils.byteCountToDisplaySize(v.getSize()));
    testObject.setVersionData(vd);

    testObject.setId(EidFactory.getDefault().createRandomUuid());

    testObjStore.create(testObject);

    return "redirect:/testobjects";
}

From source file:com.devnexus.ting.web.controller.cfp.CallForPapersController.java

private CfpSpeakerImage processPicture(MultipartFile picture, BindingResult bindingResult) {
    CfpSpeakerImage cfpSpeakerImage = null;
    byte[] pictureData = null;

    try {//from  ww  w. j av a 2s  .c o  m
        pictureData = picture.getBytes();
    } catch (IOException e) {
        LOGGER.error("Error processing Image.", e);
        bindingResult
                .addError(new FieldError("cfpSubmissionSpeaker", "pictureFile", "Error processing Image."));
        return null;
    }

    if (pictureData != null && picture.getSize() > 0) {

        ByteArrayInputStream bais = new ByteArrayInputStream(pictureData);
        BufferedImage image;
        try {
            image = ImageIO.read(bais);
        } catch (IOException e) {
            LOGGER.error("Error processing Image.", e);
            bindingResult
                    .addError(new FieldError("cfpSubmissionSpeaker", "pictureFile", "Error processing Image."));
            return null;
        }

        if (image == null) {
            //FIXME better way?
            final String fileSizeFormatted = FileUtils.byteCountToDisplaySize(picture.getSize());
            LOGGER.warn(String.format("Cannot parse file '%s' (Content Type: %s; Size: %s) as image.",
                    picture.getOriginalFilename(), picture.getContentType(), fileSizeFormatted));
            bindingResult.addError(new FieldError("cfpSubmissionSpeaker", "pictureFile",
                    String.format(
                            "Did you upload a valid image? We cannot parse file '%s' (Size: %s) as image file.",
                            picture.getOriginalFilename(), fileSizeFormatted)));
            return null;
        }

        int imageHeight = image.getHeight();
        int imageWidth = image.getWidth();

        if (imageHeight < 360 && imageWidth < 360) {
            bindingResult.addError(new FieldError("cfpSubmissionSpeaker", "pictureFile", String.format(
                    "Your image '%s' (%sx%spx) is too small. Please provide an image of at least 360x360px.",
                    picture.getOriginalFilename(), imageWidth, imageHeight)));
        }

        cfpSpeakerImage = new CfpSpeakerImage();

        cfpSpeakerImage.setFileData(pictureData);
        cfpSpeakerImage.setFileModified(new Date());
        cfpSpeakerImage.setFileSize(picture.getSize());
        cfpSpeakerImage.setName(picture.getOriginalFilename());
        cfpSpeakerImage.setType(picture.getContentType());

        return cfpSpeakerImage;
    }

    return null;
}