-
Notifications
You must be signed in to change notification settings - Fork 0
Added interfaces for time and data parsing #5
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
The head ref may contain hidden characters: "Common-interfaces-for-parsers(Task-\u21164)"
Conversation
| data.computeIfAbsent(key, k -> new DataSet()).parseLine(line); | ||
| } | ||
| } | ||
| GCParser gcParser = new GCParser(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
У вас совсем исчез SDNG парсер, теперь вместо него почему-то GC
| data.computeIfAbsent(key, k -> new DataSet()).parseGcLine(line); | ||
| } | ||
| } | ||
| TimeParser timeParser = new TimeParser(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Вместо GC - TimeParser (не очень удачное название, не понятно что внутри)
| try (BufferedReader br = new BufferedReader(new InputStreamReader(logs.getInputStream()))) | ||
| { | ||
| String line; | ||
| while ((line = br.readLine()) != null) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
В задании было сказано, что нужно избавиться от дублирования кода. Но у вас в итоге этот while есть теперь в каждом парсере. На самом деле он должен остаться один - только в App
| switch (parseMode) | ||
| { | ||
| switch (parseMode){ | ||
| case "sdng": |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
если это все изменения, то тут ничего не изменилось. В режиме sdng работает GC-парсер, хотя для него есть режим "gc".
Если вам не очень понятно, что надо сделать - лучше задать конкретные вопросы
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Да, действительно перепутаны местами, прошу прощения.
|
|
||
| import java.text.ParseException; | ||
|
|
||
| public interface IDataParser { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ActionDoneParser, ErrorParser, GCParser, TopParser - все они должны реализовывать этот интерфейс
| import java.text.ParseException; | ||
|
|
||
| public interface ITimeParser { | ||
| public long parseTime(String line) throws ParseException; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
GCTimeParser, TimeParser, а также у TopParser должен появиться свой парсер для времени - они должны реализовывать этот интерфейс
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Имеется в виду, что каждый из них(GCTimeParser, TimeParser, TopParser) будет должен реализовать интерфейс ITimeParser, или что будут существовать другие классы-парсеры?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Есть еще мысль сделать по аналогии с GCParser (где существует подкласс GCTimeParser) или наоборот, избавиться от этого подкласса...
| int min5 = 5 * 60 * 1000; | ||
| long count = time / min5; | ||
| long key = count * min5; | ||
| data.computeIfAbsent(key, k -> new DataSet()).parseGcLine(line); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
раньше в каждом режиме (внутри каждого блока case) был вызов соответствующего данному режиму метода
parseGcLine для GC
parseLine для sdng
TopParser содержал этот цикл внутри себя.
Нужно убрать эти методы из DataSet (они всего лишь переадресуют вызов в соответствующий парсер) и прямо здесь вызывать конкретный парсер. Как вы его получите - это уже зависит от вашего решения.
Также задача была "убрать дублирование". Имелся в виду в основном цикл while, который обходит все строки файла. Он есть здесь два раза, он есть в TopParser. В конце должен остаться только один.
ykalemi
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Да, это уже правильное направление.
| Matcher matcher = Pattern.compile("\\d{8}|\\d{4}-\\d{2}-\\d{2}").matcher(logs.getOriginalFilename()); | ||
| if (matcher.find()){ | ||
| time = prepareDate(sdf.parse(dataDate + matcher.group(1)).getTime()); | ||
| currentSet = existing.computeIfAbsent(time, k -> new DataSet()); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
и не будем создавать новый датасет внутри парсера времени. Пусть это будет в вызывающем коде, где цикл while по строкам
| */ | ||
| public class TopParser implements IDataParser{ | ||
|
|
||
| public class TopParser implements IDataParser, ITimeParser{ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Теперь давайте распилим всё-таки этот парсер на два - отдельно время. отдельно данные.
| * Created by doki on 22.10.16. | ||
| */ | ||
| public class SDNGParser implements IDataParser{ | ||
| public final static class SDNGTimeParser implements ITimeParser{ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
давайте вынесем этот класс наружу
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
т.е. просто убрать SDNGTimeParser?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Или сделать совсем отдельный класс...
| TopParser topParser = new TopParser(logs, data); | ||
| topParser.configureTimeZone(timeZone); | ||
| topParser.parse(); | ||
| parse(data, timeZone, logs, topParser, topParser); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
метод parse во всех трёх вариантах - одинаковый. Давайте оставим только один сразу после этих блоков, т.е. в конце метода
ykalemi
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Направление уже верное, только, кажется, прямо сейчас приложение вообще ничего не парсит :)
Но исправления нужны не такие серьезные - просто внимательнее отнеситесь к замечаниям
| */ | ||
| public class SDNGParser implements IDataParser{ | ||
|
|
||
| private DataSet currentSet; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
currentSet всегда null?
| private Pattern timeRegex = Pattern.compile("^_+ (\\S+)"); | ||
| public class TopParser implements IDataParser{ | ||
|
|
||
| private DataSet currentSet; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
тут тоже вроде бы currentSet никогда не присваивается
| continue; | ||
| } | ||
|
|
||
| data.computeIfAbsent(time, k -> new DataSet()); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
тут создается новый dataset, но никак не используется. Надо присвоить это значение в переменную, а переменную передать в метод следующей строки - parseLine. Измените сигнатуру у parseLine в DataParser, чтобы он принимал строку и текущий dataset. Тогда не будет проблем с пустым currentSet во всех парсерах
| // private Pattern timeRegex = Pattern.compile("^_+ (\\S+)"); | ||
|
|
||
| public TopTimeParser(MultipartFile logs, Map<Long, DataSet> existingDataSet, String timeZone) throws IllegalArgumentException{ | ||
| //Supports these masks in file name: YYYYmmdd, YYY-mm-dd i.e. 20161101, 2016-11-01 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
logs в этом классе на самом деле больше не нужен. Кроме имени файла тут вообще больше ничего не используется от файла. Поэтому лучше только имя файла и передавать
| time = prepareDate(sdf.parse(dataDate + matcher.group(1)).getTime()); | ||
| return time; | ||
| } | ||
| return 0L; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Тут есть небольшая проблема - файл top устроен иначе, чем остальные. Там идет дата (время) в одной строке, потом несколько строк данных, которые относятся к этому времени. Далее опять строка со временем, несколько строк данных.
Т.е. нужно сохранить это время, и на все последующие строки данных возвращать его. Пока не получим новое время.
@ykalemi, прошу проверить.