public PropertySheetApplicationStats() {
    setLayout(LookAndFeelTweaks.createVerticalPercentLayout());

    final Bean data = new Bean();

    TimeSpan timespan = null;

    // counts of objects
    long discCount = HibernateDao.countAll(Disc.class);
    data.setCountArtists(Long.toString(HibernateDao.countAll(Artist.class)));
    data.setCountDiscs(Long.toString(discCount));
    data.setCountTracks(Long.toString(HibernateDao.countAll(Track.class)));

    // time stats
    long totalTime = 0;
    long totalSize = 0;
    long avgTimePerDisc = 0;
    long avgSizePerDisc = 0;
    try {
      totalTime = HibernateDao.sum(Disc.class, Disc.PROPERTYNAME_DURATION);
      totalSize = HibernateDao.sum(Track.class, Track.PROPERTYNAME_TRACK_SIZE);
      avgTimePerDisc = (totalTime / discCount) * 1000;
      avgSizePerDisc = (totalSize / discCount);
    } catch (RuntimeException ex) {
      totalTime = 0;
    }

    // calculate time fields to display properly
    timespan = new TimeSpan(totalTime * 1000);
    data.setTimeTotal(timespan.toString());
    timespan = new TimeSpan(avgTimePerDisc);
    data.setTimeAveragePerDisc(timespan.toString());

    // file stats
    data.setFileTotal(FileUtils.byteCountToDisplaySize(totalSize));
    data.setFileAveragePerDisc(FileUtils.byteCountToDisplaySize(avgSizePerDisc));

    DefaultBeanInfoResolver resolver = new DefaultBeanInfoResolver();
    BeanInfo beanInfo = resolver.getBeanInfo(data);

    PropertySheetPanel sheet = new PropertySheetPanel();
    sheet.setMode(PropertySheet.VIEW_AS_CATEGORIES);
    sheet.setProperties(beanInfo.getPropertyDescriptors());
    sheet.readFromObject(data);
    sheet.setDescriptionVisible(true);
    sheet.setSortingCategories(true);
    sheet.setSortingProperties(true);
    add(sheet, "*");

    // everytime a property change, update the button with it
    PropertyChangeListener listener =
        new PropertyChangeListener() {
          public void propertyChange(PropertyChangeEvent evt) {
            Property prop = (Property) evt.getSource();
            prop.writeToObject(data);
          }
        };
    sheet.addPropertySheetChangeListener(listener);
  }
Beispiel #2
0
 public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   String hdfsFolder = request.getParameter("hdfsFolder");
   HttpSession session = request.getSession(true);
   ConfigurationManager configurationManager =
       ((LoginPass) session.getAttribute(ShsContext.LOGIN_PASS)).getConfigurationManager();
   PrintWriter out = response.getWriter();
   Map<String, String> jsonKeyValMap = new LinkedHashMap<String, String>();
   try {
     IFileSystem filesystem = configurationManager.getFileSystem();
     IFile[] files = filesystem.listFiles(hdfsFolder);
     response.setContentType("application/json");
     int count = 0;
     for (IFile file : files) {
       jsonKeyValMap.put("fileName" + count, file.getFilename());
       jsonKeyValMap.put("fileOwner" + count, file.getOwner());
       jsonKeyValMap.put("fileLen" + count, FileUtils.byteCountToDisplaySize(file.getLen()));
       jsonKeyValMap.put(
           "fileModificationTime" + count,
           ShsContext.DATE_FORMAT.format(new Date(file.getModificationTime())));
       jsonKeyValMap.put("isDir" + count, file.isDir() ? "0" : "1");
       count++;
     }
   } catch (Exception ee) {
     IOException iee = new IOException(ee);
     iee.setStackTrace(ee.getStackTrace());
     throw iee;
   }
   out.write(ShsContext.getJsonString(jsonKeyValMap));
   out.close();
 }
  protected HttpHeaders attachmentList(T entity, String category) {
    HttpServletRequest request = getRequest();
    String url = request.getServletPath();
    AttachmentFileService attachmentFileService =
        SpringContextHolder.getBean(AttachmentFileService.class);
    List<AttachmentFile> attachmentFiles =
        attachmentFileService.findBy(
            entity.getClass().getName(), String.valueOf(entity.getId()), category);
    List<Map<String, Object>> filesResponse = Lists.newArrayList();
    for (AttachmentFile attachmentFile : attachmentFiles) {
      Map<String, Object> dataMap = Maps.newHashMap();
      dataMap.put("id", attachmentFile.getId());
      dataMap.put("attachmentName", "_attachment_" + attachmentFile.getEntityFileCategory());
      dataMap.put("name", attachmentFile.getFileRealName());
      dataMap.put("size", FileUtils.byteCountToDisplaySize(attachmentFile.getFileLength()));

      dataMap.put(
          "url",
          getRequest().getContextPath()
              + StringUtils.substringBefore(url, "!attachmentList")
              + "!attachmentDownload?id="
              + entity.getId()
              + "&attachmentId="
              + attachmentFile.getId());
      filesResponse.add(dataMap);
    }
    Map<String, List<Map<String, Object>>> response = Maps.newHashMap();
    response.put("files", filesResponse);
    setModel(response);
    return buildDefaultHttpHeaders();
  }
  private void browseDir(ModelImpl model, File requestedFile) throws IOException {
    if (logger.isTraceEnabled()) logger.trace("> browseDir {}", requestedFile.getAbsolutePath());
    model.put("app", this);
    Map files = new HashMap();
    model.put("files", files);
    for (File file : requestedFile.listFiles()) {
      files.put(
          file.getName(),
          new Object[] {
            file,
            FileUtils.byteCountToDisplaySize(file.length()),
            DateTimeUtil.timestampForDisplay(file.lastModified())
          });
    }

    File indexFile = new File(requestedFile, "index.html");
    String selectedTemplate;
    if (indexFile.exists()) {
      selectedTemplate = FileUtils.readFileToString(indexFile);
    } else {
      selectedTemplate = dirTemplate;
    }
    String dirPage = StringTemplateUtils.render(selectedTemplate, model);
    model.getResponse().getWriter().println(dirPage);
    if (logger.isTraceEnabled()) logger.trace("< browseDir");
  }
 @Override
 public void beforeUpload(long total, long offset, String fname) {
   fileName = fname;
   this.total = total;
   this.offset = offset;
   totalDisplay = FileUtils.byteCountToDisplaySize(total);
   progressBar.setString(getMessage(MessageCode.FTP_UPLOAD_WAIT));
   drawProgressBar();
   if (beforeUpload != null) {
     window.call(beforeUpload, null);
   }
 }
 /**
  * Creates a human readable string for the attachment upload size limit.
  *
  * @return the human readable string of the max upload size
  */
 private String getHumanReadableUploadSizeLimit() {
   if (humanReadableUploadSizeLimit == null) {
     long fileUploadLimit =
         Long.parseLong(
             CommunoteRuntime.getInstance()
                 .getConfigurationManager()
                 .getApplicationConfigurationProperties()
                 .getProperty(ApplicationProperty.ATTACHMENT_MAX_UPLOAD_SIZE));
     humanReadableUploadSizeLimit = FileUtils.byteCountToDisplaySize(fileUploadLimit);
   }
   return humanReadableUploadSizeLimit;
 }
    private void drawProgressBar() {
      String uploadedDisplay = FileUtils.byteCountToDisplaySize(offset + readTotal);
      int percent = (int) Math.floor((offset + readTotal) * 100 / total);
      String speedDisplay =
          FileUtils.byteCountToDisplaySize(
              (long) Math.ceil((readTotal / (int) Math.ceil(costTotal / 1000))));

      StringBuffer display = new StringBuffer();
      display
          .append(uploadedDisplay)
          .append('/')
          .append(totalDisplay)
          .append('(')
          .append(percent)
          .append("%,")
          .append(getMessage(MessageCode.AVERAGE))
          .append(speedDisplay)
          .append('/')
          .append(getMessage(MessageCode.SECOND))
          .append(')');

      progressBar.setValue(percent);
      progressBar.setString(display.toString());
    }
 public static String byteCountToDisplaySize(long size) {
   return FileUtils.byteCountToDisplaySize(size);
 }
Beispiel #9
0
  /** Reads view contents from the underlying model. */
  @Override
  protected void updateView() {
    final String currentCoverUrl;
    Track track = getTrack();
    titleField.setText(track.getName());
    trackNumber.setText(track.getTrackNumber());
    comment.setText(track.getComment());
    location.setText(track.getTrackUrl());
    location.setToolTipText(track.getTrackUrl());
    createdDateLabel.setText(DATE_FORMAT.format(track.getCreatedDate()));
    createdByLabel.setText(track.getCreatedUser());
    modifiedDateLabel.setText(DATE_FORMAT.format(track.getModifiedDate()));
    modifiedByLabel.setText(track.getModifiedUser());
    albumImage.setDisc(track.getDisc());
    if (this.getSettings().isCopyImagesToDirectory()) {
      currentCoverUrl =
          ImageFactory.standardImageFileName(
              track.getDisc().getArtist().getName(),
              track.getDisc().getName(),
              track.getDisc().getYear());
    } else {
      currentCoverUrl = track.getDisc().getCoverUrl();
    }
    if (StringUtils.isNotBlank(currentCoverUrl)) {
      int dimension = this.getSettings().getCoverSizeSmall();
      albumImage.setImage(
          ImageFactory.getScaledImage(currentCoverUrl, dimension, dimension).getImage());
    } else {
      albumImage.setImage(null);
    }

    // try and open the tag, but fail safely
    try {
      // AZ: verify if file is accessible
      final File file = new File(track.getTrackUrl());
      if (file.exists()) {
        musicTag = TagFactory.getTag(track.getTrackUrl());
        duration.setText(musicTag.getTrackLengthAsString());
        layer.setText(musicTag.getLayer());
        version.setText(musicTag.getVersion());
        bitRate.setText(musicTag.getBitRateAsString());
        frequency.setText(musicTag.getFrequency() + " Hz");
        mode.setText(musicTag.getMode());
        fileSize.setText(FileUtils.byteCountToDisplaySize(musicTag.getFile().length()));
        emphasis.setText(musicTag.getEmphasis());
        copyrighted.setText(musicTag.getCopyrighted());
      } else {
        LOG.debug("File: " + track.getTrackUrl() + " is not accessible");
        duration.setText("");
        layer.setText("");
        version.setText("");
        bitRate.setText("");
        frequency.setText("");
        mode.setText("");
        fileSize.setText("");
        emphasis.setText("");
        copyrighted.setText("");
        musicTag = null;
      }
    } catch (MusicTagException ex) {
      LOG.info(ex.getMessage(), ex);
      duration.setText("");
      layer.setText("");
      version.setText("");
      bitRate.setText("");
      frequency.setText("");
      mode.setText("");
      fileSize.setText("");
      emphasis.setText("");
      copyrighted.setText("");
      musicTag = null;
    }
  }
Beispiel #10
0
  /** build the context for batch archive confirm */
  public String buildDownloadContext(
      VelocityPortlet portlet, Context context, RunData rundata, SessionState state) {
    context.put("tlang", rb);
    buildMenu(context);

    // get list of existing archives
    Collection<File> files = Collections.<File>emptySet();
    File archiveBaseDir =
        new File(serverConfigurationService.getString("archive.storage.path", "sakai/archive"));

    if (archiveBaseDir.exists() && archiveBaseDir.isDirectory()) {
      files = FileUtils.listFiles(archiveBaseDir, new SuffixFileFilter(".zip"), null);
    }

    List<SparseFile> zips = new ArrayList<SparseFile>();

    SimpleDateFormat dateFormatIn = new SimpleDateFormat("yyyyMMddHHmmss");
    SimpleDateFormat dateFormatOut = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    Calendar calendar = Calendar.getInstance();

    // porcess the list. also get the hash for the file if it exists
    for (File f : files) {

      String absolutePath = f.getAbsolutePath();

      SparseFile sf = new SparseFile();
      sf.setFilename(f.getName());
      sf.setAbsolutePath(absolutePath);
      sf.setSize(FileUtils.byteCountToDisplaySize(f.length()));

      // get the datetime string, its the last part of the file name, convert back to a date that we
      // can display
      String dateTimeStr =
          StringUtils.substringAfterLast(StringUtils.removeEnd(f.getName(), ".zip"), "-");

      try {
        Date date = dateFormatIn.parse(dateTimeStr);
        sf.setDateCreated(dateFormatOut.format(date));
      } catch (ParseException pe) {
        // ignore, just don't set the date
      }

      // get siteId, first part of name
      String siteId = StringUtils.substringBeforeLast(f.getName(), "-");
      sf.setSiteId(siteId);

      // try to get site title if the site still exists
      try {
        Site site = siteService.getSite(siteId);
        sf.setSiteTitle(site.getTitle());
      } catch (IdUnusedException e) {
        // ignore, no site available
      }

      // get the hash. need to read it from the file. Same filename but diff extension
      String hashFilePath = StringUtils.removeEnd(absolutePath, ".zip");
      hashFilePath = hashFilePath + ".sha1";

      File hashFile = new File(hashFilePath);
      try {
        String hash = FileUtils.readFileToString(hashFile);
        sf.setHash(hash);
      } catch (IOException e) {
        // ignore, dont use the hash
      }

      zips.add(sf);
    }

    context.put("archives", zips);

    return "-download";
  }
 @Override
 public String toString() {
   String fileName = getFileName();
   long length = getLength();
   return fileName + " (" + FileUtils.byteCountToDisplaySize(length) + ")";
 }
 public String getSizeString() {
   if (lastModifiedAndSize == null) return null;
   return FileUtils.byteCountToDisplaySize(lastModifiedAndSize.getSize());
 }
Beispiel #13
0
  public String getFormattedSize() {

    return FileUtils.byteCountToDisplaySize(getSize());
  }
 public String asNumber(long bytesTransfered) {
   // Extra Pedantry: I love *-ibytes
   return FileUtils.byteCountToDisplaySize(bytesTransfered).replaceAll("B$", "iB");
 }
Beispiel #15
0
  /** 视频评论 */
  @RequestMapping(value = PREFIX_API_1_COMMENTS + "createWithMedia", method = RequestMethod.POST)
  @ResponseBody
  public Object createWithMedia(
      @RequestParam(value = "video", required = false) MultipartFile video,
      @RequestParam(value = "image", required = false) MultipartFile image,
      @RequestParam(value = "audio", required = false) MultipartFile audio,
      @RequestParam(value = "audioDuration", required = false) Long audioDuration,
      @RequestParam(value = "text", required = false) String text,
      @RequestParam(value = "postId", required = false) String postId,
      @RequestParam(value = "replyCommentId", required = false) String replyCommentId) {
    try {
      logger.debug("正在发布视频评论:");
      if (video != null) {
        logger.debug("           video : {}", FileUtils.byteCountToDisplaySize(video.getSize()));
      }
      if (image != null) {
        logger.debug("           image : {}", FileUtils.byteCountToDisplaySize(image.getSize()));
      }
      if (audio != null) {
        logger.debug("           audio : {}", FileUtils.byteCountToDisplaySize(audio.getSize()));
      }
      logger.debug("            text : {}", text);
      logger.debug("          postId : {}", postId);
      logger.debug("  replyCommentId : {}", replyCommentId);

      // 参数检查
      if (StringUtils.isBlank(postId) && StringUtils.isBlank(replyCommentId)) {
        return ErrorDto.badRequest("参数postId和replyCommentId不能都为空");
      }

      // 文件大小限制
      if (video != null && video.getSize() > Setting.MAX_VIDEO_LENGTH_BYTES
          || image != null && image.getSize() > Setting.MAX_IMAGE_LENGTH_BYTES
          || audio != null && audio.getSize() > Setting.MAX_AUDIO_LENGTH_BYTES) {
        return ErrorDto.badRequest("上传的文件太大");
      }

      FileInfo videoFileInfo = null;
      FileInfo imageFileInfo = null;
      FileInfo audioFileInfo = null;

      // 视频评论
      if (video != null && image != null) {
        videoFileInfo = ControllerUtils.getFileInfo(video);
        imageFileInfo = ControllerUtils.getFileInfo(image);
      }
      // 语音评论
      else if (audio != null) {
        audioFileInfo = ControllerUtils.getFileInfo(audio);
        audioFileInfo.setDuration(audioDuration);
      }
      // 参数错误
      else {
        return ErrorDto.badRequest(
            "参数必须满足这个条件:(video != null && image != null) || (audio != null)");
      }

      return createComment(
          text, replyCommentId, postId, videoFileInfo, imageFileInfo, audioFileInfo);

    } catch (DuplicateException e) {
      return ErrorDto.duplicate();
    } catch (Exception e) {
      logger.info("发布评论失败", e);
      return ErrorDto.internalServerError(e.getMessage());
    }
  }