Skip to content

Conversation

@ZeroNetto
Copy link
Owner

@ykalemi, прошу проверить.

data.computeIfAbsent(key, k -> new DataSet()).parseLine(line);
}
}
GCParser gcParser = new GCParser();
Copy link

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();
Copy link

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)
Copy link

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":
Copy link

Choose a reason for hiding this comment

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

если это все изменения, то тут ничего не изменилось. В режиме sdng работает GC-парсер, хотя для него есть режим "gc".

Если вам не очень понятно, что надо сделать - лучше задать конкретные вопросы

Copy link
Owner Author

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 {
Copy link

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;
Copy link

Choose a reason for hiding this comment

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

GCTimeParser, TimeParser, а также у TopParser должен появиться свой парсер для времени - они должны реализовывать этот интерфейс

Copy link
Owner Author

Choose a reason for hiding this comment

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

Имеется в виду, что каждый из них(GCTimeParser, TimeParser, TopParser) будет должен реализовать интерфейс ITimeParser, или что будут существовать другие классы-парсеры?

Copy link
Owner Author

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);
Copy link

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. В конце должен остаться только один.

Copy link

@ykalemi ykalemi left a 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());
Copy link

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{
Copy link

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{
Copy link

Choose a reason for hiding this comment

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

давайте вынесем этот класс наружу

Copy link
Owner Author

Choose a reason for hiding this comment

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

т.е. просто убрать SDNGTimeParser?

Copy link
Owner Author

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);
Copy link

Choose a reason for hiding this comment

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

метод parse во всех трёх вариантах - одинаковый. Давайте оставим только один сразу после этих блоков, т.е. в конце метода

Copy link

@ykalemi ykalemi left a 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;
Copy link

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;
Copy link

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());
Copy link

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
Copy link

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;
Copy link

Choose a reason for hiding this comment

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

Тут есть небольшая проблема - файл top устроен иначе, чем остальные. Там идет дата (время) в одной строке, потом несколько строк данных, которые относятся к этому времени. Далее опять строка со временем, несколько строк данных.

Т.е. нужно сохранить это время, и на все последующие строки данных возвращать его. Пока не получим новое время.

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