• ,

level39.lesson09.big01 задание 4

Вроде все работает как надо. Возможно я не верно понимаю описание методов. В чем может быть причина?

Задание 4

Реализуй интерфейс EventQuery у класса LogParser:
4.1. Метод getNumberOfAllEvents() должен возвращать количество различных типов
событий за указанный период.
4.2. Метод getAllEvents() должен возвращать события за указанный период.
4.3. Метод getEventsForIP() должен возвращать события, которые происходили с
указанного IP.
4.4. Метод getEventsForUser() должен возвращать события, которые инициировал
определенный пользователь.
4.5. Метод getFailedEvents() должен возвращать события, которые не выполнились.
4.6. Метод getErrorEvents() должен возвращать события, которые завершились
ошибкой.
4.7. Метод getNumberOfAttemptToSolveTask() должен возвращать количество попыток
решить определенную задачу.
4.8. Метод getNumberOfSuccessfulAttemptToSolveTask() должен возвращать количество
успешных решений определенной задачи.
4.9. Метод getAllSolvedTasksAndTheirNumber() должен возвращать мапу (номер_задачи:
количество_попыток_решить_ее).
4.10. Метод getAllDoneTasksAndTheirNumber() должен возвращать мапу (номер_задачи:
сколько_раз_ее_решили).


package com.javarush.test.level39.lesson09.big01;

import com.javarush.test.level39.lesson09.big01.query.DateQuery;
import com.javarush.test.level39.lesson09.big01.query.EventQuery;
import com.javarush.test.level39.lesson09.big01.query.IPQuery;
import com.javarush.test.level39.lesson09.big01.query.UserQuery;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LogParser implements IPQuery, UserQuery, DateQuery, EventQuery
{
    private Path logDir;

    public LogParser(Path logDir)
    {
        this.logDir = logDir;
    }

    private ArrayList<Log> getLogsBetweenDates(Date after, Date before)
    {
        File[] logFiles = logDir.toFile().listFiles(new FilenameFilter()
        {
            @Override
            public boolean accept(File dir, String name)
            {
                return name.endsWith(".log");
            }
        });

        ArrayList<Log> listLogs = new ArrayList<>();
        for (File logFile : logFiles)
        {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(Files.newInputStream(logFile.toPath()))))
            {
                while (reader.ready())
                {
                    try
                    {
                        String string = reader.readLine();
                        Log log = parseStringToLog(string);

                        if ((after == null || after.getTime() <= log.getDate().getTime()) && (before == null || log.getDate().getTime() <= before.getTime()))
                        {
                            listLogs.add(log);
                        }
                    }
                    catch (Exception e)
                    {

                    }
                }
            }
            catch (IOException e)
            {

            }
        }
        return listLogs;
    }

    private Log parseStringToLog(String string)throws Exception
    {
        //146.34.15.5	Eduard Petrovich Morozko	05.01.2021 20:22:55	DONE_TASK 48	FAILED
        SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");                                                                      //05.01.2021 20:22:55
        Pattern pattern = Pattern.compile("(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\s" +                                                     //IP
                "(\\D*)\\s" +                                                                                          //userName
                "(\\d{2}\\.\\d{2}\\.\\d{4}\\s\\d{2}\\:\\d{2}\\:\\d{2})\\s" +                                           //Date
                "(\\w*)\\s?" +                                                                                         //Event
                "(\\d*){0,1}\\s" +                                                                                     //eventValue
                "(\\D*)");                                                                                             //Status

        Matcher matcher = pattern.matcher(string);
        matcher.find();

        String ip = matcher.group(1);
        String userName = matcher.group(2);
        Date date = sdf.parse(matcher.group(3));
        Event event = Event.valueOf(matcher.group(4));
        String eventValue = matcher.group(5);
        Status status = Status.valueOf(matcher.group(6));

        return new Log(ip, userName, date, event, eventValue, status);
    }

    private class Log
    {
        //ip username date event status
        private String ip;
        private String userName;
        private Date date;
        private Event event;
        private String eventValue;
        private Status status;

        public Log(String ip, String userName, Date date, Event event,String eventValue, Status status)
        {
            this.ip = ip;
            this.userName = userName;
            this.date = date;
            this.event = event;
            this.eventValue = eventValue;
            this.status = status;
        }

        public String getIp()
        {
            return ip;
        }

        public String getUserName()
        {
            return userName;
        }

        public Date getDate()
        {
            return date;
        }

        public Event getEvent()
        {
            return event;
        }

        public Status getStatus()
        {
            return status;
        }

        public String getEventValue()
        {
            return eventValue;
        }
    }

    @Override
    public int getNumberOfUniqueIPs(Date after, Date before)
    {
        return getUniqueIPs(after, before).size();
    }

    @Override
    public Set<String> getUniqueIPs(Date after, Date before)
    {
        ArrayList<Log> logs = getLogsBetweenDates(after, before);
        Set<String> uniqIps = new HashSet<>();

        for (Log log : logs)
        {
            if (!uniqIps.contains(log.getIp()))
            {
                uniqIps.add(log.getIp());
            }
        }

        return uniqIps;
    }

    @Override
    public Set<String> getIPsForUser(String user, Date after, Date before)
    {
        Set<String> users = new HashSet<>();
        ArrayList<Log> logs = getLogsBetweenDates(after, before);
        for (Log log : logs)
        {
            if (log.getUserName().equals(user) && !users.contains(log.getIp()))
            {
                users.add(log.getIp());
            }
        }
        return users;
    }

    @Override
    public Set<String> getIPsForEvent(Event event, Date after, Date before)
    {
        Set<String> users = new HashSet<>();
        ArrayList<Log> logs = getLogsBetweenDates(after, before);
        for (Log log : logs)
        {
            if (log.getEvent().equals(event) && !users.contains(log.getIp()))
            {
                users.add(log.getIp());
            }
        }
        return users;
    }

    @Override
    public Set<String> getIPsForStatus(Status status, Date after, Date before)
    {
        Set<String> users = new HashSet<>();
        ArrayList<Log> logs = getLogsBetweenDates(after, before);
        for (Log log : logs)
        {
            if (log.getStatus().equals(status) && !users.contains(log.getIp()))
            {
                users.add(log.getIp());
            }
        }
        return users;
    }

    @Override
    public Set<String> getAllUsers()
    {
        Set<String> users = new HashSet<>();
        ArrayList<Log> logs = getLogsBetweenDates(null, null);
        for (Log log : logs)
        {
            if (!users.contains(log.getUserName()))
            {
                users.add(log.getUserName());
            }
        }
        return users;
    }

    @Override
    public int getNumberOfUsers(Date after, Date before)
    {
        Set<String> users = new HashSet<>();
        ArrayList<Log> logs = getLogsBetweenDates(after, before);
        for (Log log : logs)
        {
            if (!users.contains(log.getUserName()))
            {
                users.add(log.getUserName());
            }
        }
        return users.size();
    }

    @Override
    public int getNumberOfUserEvents(String user, Date after, Date before)
    {
        int i = 0;
        ArrayList<Log> logs = getLogsBetweenDates(after, before);
        for (Log log : logs)
        {
            if (log.getUserName().equals(user))
            {
                i++;
            }
        }
        return i;
    }

    @Override
    public Set<String> getUsersForIP(String ip, Date after, Date before)
    {
        Set<String> users = new HashSet<>();
        ArrayList<Log> logs = getLogsBetweenDates(after, before);
        for (Log log : logs)
        {
            if (log.getIp().equals(ip) && !users.contains(log.getUserName()))
            {
                users.add(log.getUserName());
            }
        }
        return users;
    }

    @Override
    public Set<String> getLoggedUsers(Date after, Date before)
    {
        Set<String> users = new HashSet<>();
        ArrayList<Log> logs = getLogsBetweenDates(after, before);
        for (Log log : logs)
        {
            if (log.getEvent().equals(Event.LOGIN) && !users.contains(log.getUserName()))
            {
                users.add(log.getUserName());
            }
        }
        return users;
    }

    @Override
    public Set<String> getDownloadedPluginUsers(Date after, Date before)
    {
        Set<String> users = new HashSet<>();
        ArrayList<Log> logs = getLogsBetweenDates(after, before);
        for (Log log : logs)
        {
            if (log.getEvent().equals(Event.DOWNLOAD_PLUGIN) && !users.contains(log.getUserName()))
            {
                users.add(log.getUserName());
            }
        }
        return users;
    }

    @Override
    public Set<String> getWroteMessageUsers(Date after, Date before)
    {
        Set<String> users = new HashSet<>();
        ArrayList<Log> logs = getLogsBetweenDates(after, before);
        for (Log log : logs)
        {
            if (log.getEvent().equals(Event.WRITE_MESSAGE) && !users.contains(log.getUserName()))
            {
                users.add(log.getUserName());
            }
        }
        return users;
    }

    @Override
    public Set<String> getSolvedTaskUsers(Date after, Date before)
    {
        Set<String> users = new HashSet<>();
        ArrayList<Log> logs = getLogsBetweenDates(after, before);
        for (Log log : logs)
        {
            if (log.getEvent().equals(Event.SOLVE_TASK) && !users.contains(log.getUserName()))
            {
                users.add(log.getUserName());
            }
        }
        return users;
    }

    @Override
    public Set<String> getSolvedTaskUsers(Date after, Date before, int task)
    {
        Set<String> users = new HashSet<>();
        ArrayList<Log> logs = getLogsBetweenDates(after, before);
        for (Log log : logs)
        {
            if (log.getEvent().equals(Event.SOLVE_TASK) && log.getEventValue().equals(String.valueOf(task)) && !users.contains(log.getIp()))
            {
                users.add(log.getUserName());
            }
        }
        return users;
    }

    @Override
    public Set<String> getDoneTaskUsers(Date after, Date before)
    {
        Set<String> users = new HashSet<>();
        ArrayList<Log> logs = getLogsBetweenDates(after, before);
        for (Log log : logs)
        {
            if (log.getEvent().equals(Event.DONE_TASK) && !users.contains(log.getUserName()))
            {
                users.add(log.getUserName());
            }
        }
        return users;
    }

    @Override
    public Set<String> getDoneTaskUsers(Date after, Date before, int task)
    {
        Set<String> users = new HashSet<>();
        ArrayList<Log> logs = getLogsBetweenDates(after, before);
        for (Log log : logs)
        {
            if (log.getEvent().equals(Event.DONE_TASK) && log.getEventValue().equals(String.valueOf(task)) && !users.contains(log.getUserName()))
            {
                users.add(log.getUserName());
            }
        }
        return users;
    }

    @Override
    public Set<Date> getDatesForUserAndEvent(String user, Event event, Date after, Date before)
    {
        Set<Date> dates = new HashSet<>();
        ArrayList<Log> logs = getLogsBetweenDates(after, before);
        for (Log log : logs)
        {
            if (log.getUserName().equals(user) && log.getEvent().equals(event))
            {
                dates.add(log.getDate());
            }
        }
        return dates;
    }

    @Override
    public Set<Date> getDatesWhenSomethingFailed(Date after, Date before)
    {
        Set<Date> dates = new HashSet<>();
        ArrayList<Log> logs = getLogsBetweenDates(after, before);
        for (Log log : logs)
        {
            if (log.getStatus().equals(Status.FAILED) && !dates.contains(log.getDate()))
            {
                dates.add(log.getDate());
            }
        }
        return dates;
    }

    @Override
    public Set<Date> getDatesWhenErrorHappened(Date after, Date before)
    {
        Set<Date> dates = new HashSet<>();
        ArrayList<Log> logs = getLogsBetweenDates(after, before);
        for (Log log : logs)
        {
            if (log.getStatus().equals(Status.ERROR) && !dates.contains(log.getDate()))
            {
                dates.add(log.getDate());
            }
        }
        return dates;
    }

    @Override
    public Date getDateWhenUserLoggedFirstTime(String user, Date after, Date before)
    {
        ArrayList<Log> logs = getLogsBetweenDates(after, before);
        Date date = null;
        for (Log log : logs)
        {
            if (log.getUserName().equals(user) && log.getEvent().equals(Event.LOGIN))
            {
                date = date == null? log.getDate() : date.getTime() > log.getDate().getTime()? log.getDate() : date;
            }
        }
        return date;
    }

    @Override
    public Date getDateWhenUserSolvedTask(String user, int task, Date after, Date before)
    {
        ArrayList<Log> logs = getLogsBetweenDates(after, before);
        Date date = null;
        for (Log log : logs)
        {
            if (log.getUserName().equals(user) && log.getEvent().equals(Event.SOLVE_TASK) && log.getEventValue().equals(String.valueOf(task)))
            {
                date = date == null? log.getDate() : date.getTime() > log.getDate().getTime()? log.getDate() : date;
            }
        }
        return date;
    }

    @Override
    public Date getDateWhenUserDoneTask(String user, int task, Date after, Date before)
    {
        ArrayList<Log> logs = getLogsBetweenDates(after, before);
        Date date = null;
        for (Log log : logs)
        {
            if (log.getUserName().equals(user) && log.getEvent().equals(Event.DONE_TASK) && log.getEventValue().equals(String.valueOf(task)))
            {
                date = date == null? log.getDate() : date.getTime() > log.getDate().getTime()? log.getDate() : date;
            }
        }
        return date;
    }

    @Override
    public Set<Date> getDatesWhenUserWroteMessage(String user, Date after, Date before)
    {
        Set<Date> dates = new HashSet<>();
        ArrayList<Log> logs = getLogsBetweenDates(after, before);
        for (Log log : logs)
        {
            if (log.getUserName().equals(user) && log.getEvent().equals(Event.WRITE_MESSAGE) && !dates.contains(log.getDate()))
            {
                dates.add(log.getDate());
            }
        }
        return dates;
    }

    @Override
    public Set<Date> getDatesWhenUserDownloadedPlugin(String user, Date after, Date before)
    {
        Set<Date> dates = new HashSet<>();
        ArrayList<Log> logs = getLogsBetweenDates(after, before);
        for (Log log : logs)
        {
            if (log.getUserName().equals(user) && log.getEvent().equals(Event.DOWNLOAD_PLUGIN) && !dates.contains(log.getDate()))
            {
                dates.add(log.getDate());
            }
        }
        return dates;
    }

    @Override
    public int getNumberOfAllEvents(Date after, Date before)
    {
        Set<Event> events = new HashSet<>();
        ArrayList<Log> logs = getLogsBetweenDates(after, before);
        for (Log log : logs)
        {
            if (!events.contains(log.getEvent()))
            {
                events.add(log.getEvent());
            }
        }
        return events.size();
    }

    @Override
    public Set<Event> getAllEvents(Date after, Date before)
    {
        Set<Event> events = new HashSet<>();
        ArrayList<Log> logs = getLogsBetweenDates(after, before);
        for (Log log : logs)
        {
            events.add(log.getEvent());
        }
        return events;
    }

    @Override
    public Set<Event> getEventsForIP(String ip, Date after, Date before)
    {
        Set<Event> events = new HashSet<>();
        ArrayList<Log> logs = getLogsBetweenDates(after, before);
        for (Log log : logs)
        {
            if (log.getIp().equals(ip))
            {
                events.add(log.getEvent());
            }
        }
        return events;
    }

    @Override
    public Set<Event> getEventsForUser(String user, Date after, Date before)
    {
        Set<Event> events = new HashSet<>();
        ArrayList<Log> logs = getLogsBetweenDates(after, before);
        for (Log log : logs)
        {
            if (log.getUserName().equals(user))
            {
                events.add(log.getEvent());
            }
        }
        return events;
    }

    @Override
    public Set<Event> getFailedEvents(Date after, Date before)
    {
        Set<Event> events = new HashSet<>();
        ArrayList<Log> logs = getLogsBetweenDates(after, before);
        for (Log log : logs)
        {
            if (log.getStatus().equals(Status.FAILED))
            {
                events.add(log.getEvent());
            }
        }
        return events;
    }

    @Override
    public Set<Event> getErrorEvents(Date after, Date before)
    {
        Set<Event> events = new HashSet<>();
        ArrayList<Log> logs = getLogsBetweenDates(after, before);
        for (Log log : logs)
        {
            if (log.getStatus().equals(Status.ERROR))
            {
                events.add(log.getEvent());
            }
        }
        return events;
    }

    @Override
    public int getNumberOfAttemptToSolveTask(int task, Date after, Date before)
    {
        int i = 0;
        ArrayList<Log> logs = getLogsBetweenDates(after, before);
        for (Log log : logs)
        {
            if (log.getEvent().equals(Event.SOLVE_TASK) && log.getEventValue().equals(String.valueOf(task)))
            {
                i++;
            }
        }
        return i;
    }

    @Override
    public int getNumberOfSuccessfulAttemptToSolveTask(int task, Date after, Date before)
    {
        int i = 0;
        ArrayList<Log> logs = getLogsBetweenDates(after, before);
        for (Log log : logs)
        {
            if (log.getEvent().equals(Event.SOLVE_TASK) && log.getEventValue().equals(String.valueOf(task)) && log.getStatus().equals(Status.OK))
            {
                i++;
            }
        }
        return i;
    }

    @Override
    public Map<Integer, Integer> getAllSolvedTasksAndTheirNumber(Date after, Date before)
    {
        Map<Integer, Integer> taskSolved = new HashMap<>();
        ArrayList<Log> logs = getLogsBetweenDates(after, before);
        for (Log log : logs)
        {
            if (log.getEvent().equals(Event.SOLVE_TASK))
            {
                int task = Integer.parseInt(log.getEventValue());
                if (taskSolved.containsKey(task))
                {
                    taskSolved.put(task, taskSolved.get(task) + 1);
                }else
                {
                    taskSolved.put(task, 1);
                }
            }
        }
        return taskSolved;
    }

    @Override
    public Map<Integer, Integer> getAllDoneTasksAndTheirNumber(Date after, Date before)
    {
        Map<Integer, Integer> taskDone = new HashMap<>();
        ArrayList<Log> logs = getLogsBetweenDates(after, before);
        for (Log log : logs)
        {
            if (log.getEvent().equals(Event.DONE_TASK))
            {
                int task = Integer.parseInt(log.getEventValue());
                if (taskDone.containsKey(task))
                {
                    taskDone.put(task, taskDone.get(task) + 1);
                }else
                {
                    taskDone.put(task, 1);
                }
            }
        }
        return taskDone;
    }
}

5 комментариев

DrQ
  • DrQ
  • 0


Удалил все, и случайно нажал на галку. Валидатор просто прекрасен.
DrQ


Я плачу…
vital_63_
private Log parseStringToLog(String string)throws Exception
{
//146.34.15.5 Eduard Petrovich Morozko 05.01.2021 20:22:55

"(\\d{2}\\.\\d{2}\\.\\d{4}\\s\\d{2}\\:\\d{2}\\:\\d{2})\\s"


return new Log(ip, userName, date, event, eventValue, status);
}
Этот ваш метод неправильно парсит время, в котором количество часов записано одной цифрой. Например в третьей строчке лога в образце
146.34.15.5 Eduard Petrovich Morozko 13.09.2013 5:04:50 DOWNLOAD_PLUGIN OK
DrQ
  • DrQ
  • 0
  • Комментарий отредактирован 2016-10-12 01:17:48 пользователем DrQ
Ну вообще я это сделал сознательно, решив что запись часов одной цифрой — опечатка, и во всех предыдущих тестах валидатор это не смущало, что наводит на мысль что это таки она и есть.
vital_63_
public int getNumberOfSuccessfulAttemptToSolveTask(int task, Date after, Date before)
   {
       ...
            if (log.getEvent().equals(Event.SOLVE_TASK) && log.getEventValue().equals(String.valueOf(task)) && log.getStatus().equals(Status.OK))
        ...
    }

В этом методе Вы пытались учесть статус (Это логично). Но я попробовал не учитывать и у меня 4-й пункт прокатил. Кстати, я тоже случайно нажал галку в самом начале выполнения 4-го пункта, когда пытался запустить программу на выполнение (Обе иконки зеленые, можно ошибиться, если невнимательно нажимать). Но у меня валидатор задание не принял при этом. ))
Только зарегистрированные и авторизованные пользователи могут оставлять комментарии.