Skip to content

issues 8-14#20

Open
Rainboom7 wants to merge 2 commits intotypeundefined:masterfrom
Rainboom7:master
Open

issues 8-14#20
Rainboom7 wants to merge 2 commits intotypeundefined:masterfrom
Rainboom7:master

Conversation

@Rainboom7
Copy link
Copy Markdown

second try to create pull request properly

second try

// Get the file and save it somewhere
byte[] bytes = file.getBytes();
Path path = Paths.get(publishPath+"\\"+pathToUpload+'\\'+file.getOriginalFilename());
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не во всех ОС разделителем является \. Сам метод Paths.get() за вас построит такую конкатенацию, если передать строковые параметры через запятую.

// Get the file and save it somewhere
byte[] bytes = file.getBytes();
Path path = Paths.get(publishPath+"\\"+pathToUpload+'\\'+file.getOriginalFilename());
System.out.println(path );
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Форматирование
  2. Вывод в консоль. Привыкайте пользоваться логгером! :-)



} catch (IOException e) {
e.printStackTrace();
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В серверных приложениях печать в консоль смысла не имеет. Используйте логгер

HttpServletResponse response) {
try {
// get your file as InputStream
InputStream is = new FileInputStream( publishPath+"/"+fileName );
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А не нужно ли is закрыть по завершении?

import java.util.List;

public class DirectoryContentsRefactorer {
public DirectoryContents refactor(List<FileData> fileDataList, DirectoryContents directoryContents){
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Форматирование (Ctrl-Alt-Shift-L или Ctrl-Alt-F в раскладке Netbeans)
  2. Из названия совершенно неясно, какую проблему решает этот класс/метод. Возможно, Javadoc бы помог.

package ru.amm.fileexplorer.server.entity;

public enum SortMethod {
DATE,NAME,SIZE,DEFAULT;
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Обычно принято рассматривать два аспекта:

  1. Sort by (по чему сортируем)
  2. Sort direction: ascending, descending

return new DirectoryContents(relativePath, parentDir, filteredList);
}
private List<FileData> getSortedlist(List<FileData> fileList, SortMethod sortMethod){
switch (sortMethod){
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Switch в большинстве случаев - плохая идея. Его принято заменять либо паттерном стратегия, либо (хотя бы) поиском по Map<>. Почему бы не пойти путем, как сделан FileMatcher?

dirContents = explorerService.getRootContents(SortMethod.valueOf( sortMethod ));
} else {
dirContents = explorerService.getContents(path);
dirContents = explorerService.getContents(path,SortMethod.valueOf( sortMethod ));
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вот такой вариант имхо проще и элегантнее (ваша версия осталась в комментах)

    @RequestMapping(path = "/directories", method = RequestMethod.GET)
    public ModelAndView index(@RequestParam(name = "path", required = false) String path, @RequestParam(name="sort",required = false) Optional<SortMethod> aSortMethod) {
        DirectoryContents dirContents;
        SortMethod sortMethod = aSortMethod.orElse(SortMethod.DEFAULT);
//        if(sortMethod==null)sortMethod="DEFAULT";

        if (path == null|| path.contains( "../" )||path.contains( "/.." )) {
//            dirContents = explorerService.getRootContents(SortMethod.valueOf( sortMethod ));
            dirContents = explorerService.getRootContents(sortMethod);
        } else {
            dirContents = explorerService.getContents(path, sortMethod);
        }

        Map<String, Object> data = new HashMap<>();
        data.put("directory", dirContents);
        return new ModelAndView("index", data);

    }

Иными словами, sortMethod в контроллере не обязан быть строкой, нам не надо руками его парсить через valueOf. Ну и Optional немного упрощает жизнь.

dirContents = explorerService.getContents(path,sortMethod );
}
FileMatcher fileMatcher = new NameMatcher(pattern);
List<FileData> filteredList= dirContents.getFiles().stream().filter( file->fileMatcher.matches(file)).collect( Collectors.toList());
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Слишком много логики для контроллера. Все сортировки надо уносить в сервисы.


// Get the file and save it somewhere
byte[] bytes = file.getBytes();
Path path = Paths.get(publishPath+"\\"+pathToUpload+'\\'+file.getOriginalFilename());
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Разделитель не всегда \

e.printStackTrace();
}

return "redirect:/directories/?path="+ pathToUpload.replace("\\" ,"%5C" )+"&sort=DEFAULT";
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Здесь очень легко забыть что-то еще заэкранировать (я про .replace). Лучше и проще передать параметр через RedirectAttributes

try {

// Get the file and save it somewhere
byte[] bytes = file.getBytes();
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Поскольку byte[] это не ленивая структура, то все содержимое файла будет вычитано в память целиком. Это потенциальный OutOfMemory


import java.util.List;

public class DirectoryContentsRefactorer {
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Добавьте Javadoc или выберите более подходящее название. Я не понимаю, что делает этот класс.

fileData.setDirectory(attr.isDirectory());
String mimeType=Files.probeContentType( file );
System.out.println(mimeType );
if(mimeType==null)mimeType="directory";
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вы уверены, что это однозначный критерий?

@@ -0,0 +1,5 @@
package ru.amm.fileexplorer.server.entity;

public enum FileType {
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Мне нравится идея отдавать в модель осмысленный тип файла, а не строку с mime-type.

HttpServletResponse response) {
try {
// get your file as InputStream
InputStream is = new FileInputStream( publishPath+"/"+fileName );
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

InputStream нигде не закрывается

return new DirectoryContents(relativePath, parentDir, filteredList);
}
private List<FileData> getSortedlist(List<FileData> fileList, SortMethod sortMethod){
switch (sortMethod){
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Как правило, switch почти всегда это плохая практика. Почему бы не пойти тем же путем, что и FileMatcher?

Copy link
Copy Markdown
Owner

@typeundefined typeundefined left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Неплохая работа, но есть несколько моментов, которые нужно поправить (см. мои комментарии).

Основные претензии:

  1. Форматирование - просто не забывайте нажимать Ctrl-Alt-L (или Alt-Shift-F в Netbeans keymap). Иначе читается тяжело.
  2. Утечки ресурсов (память, незакрытый input stream)

…есто или кроме mime-type и как поступать с файлами без расширения, так же не знаю как именно избежать использования switch case(кроме создания матчера для каждого типа файла, что скорее всего будет выглядеть не очень красиво)
Copy link
Copy Markdown
Author

@Rainboom7 Rainboom7 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

попытка пофиксить большинство проблем,(кроме использования mimetype и swithc case)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants