-
Notifications
You must be signed in to change notification settings - Fork 0
Возможность назначения имени и поиск пользователей #3
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
Open
Krotkaya
wants to merge
1
commit into
master
Choose a base branch
from
add-search-users
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
53 changes: 53 additions & 0 deletions
53
src/main/java/ru/oop/logic/commands/SearchUserByNameCommand.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| package ru.oop.logic.commands; | ||
|
|
||
| import ru.oop.logic.Request; | ||
| import ru.oop.logic.Response; | ||
| import ru.oop.logic.services.UserService; | ||
| import ru.oop.logic.models.User; | ||
|
|
||
| import java.util.List; | ||
| import java.util.regex.Matcher; | ||
| import java.util.regex.Pattern; | ||
|
|
||
| public class SearchUserByNameCommand implements Command { | ||
| private final UserService userService; | ||
|
|
||
| public SearchUserByNameCommand(UserService userService) { | ||
| this.userService = userService; | ||
| } | ||
|
|
||
| @Override | ||
| public Pattern getCommandPattern() { | ||
| return Pattern.compile("/searchUser (.+)"); | ||
| } | ||
|
|
||
| @Override | ||
| public Response executeCommand(Request request, Matcher matched, User currentUser) { | ||
| try { | ||
| if (currentUser == null) { | ||
| return new Response("Пользователь не найден. Пожалуйста, зарегистрируйтесь."); | ||
| } | ||
|
|
||
| String usernamePart = matched.group(1).trim(); | ||
|
|
||
| if (usernamePart.isEmpty()) { | ||
| return new Response("Имя для поиска не может быть пустым."); | ||
| } | ||
|
|
||
| List<User> matchingUsers = userService.findUsersByUsername(usernamePart); | ||
|
|
||
| if (matchingUsers.isEmpty()) { | ||
| return new Response("Пользователи с именем, содержащим '" + usernamePart + "', не найдены."); | ||
| } | ||
|
|
||
| StringBuilder responseMessage = new StringBuilder("Найдены следующие пользователи:\n"); | ||
| for (User user : matchingUsers) { | ||
| responseMessage.append("- ").append(user.getUsername()).append("\n"); | ||
| } | ||
|
|
||
| return new Response(responseMessage.toString()); | ||
| } catch (Exception e) { | ||
| return new Response("Произошла ошибка при поиске пользователей: " + e.getMessage()); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| package ru.oop.logic.commands; | ||
|
|
||
| import ru.oop.logic.Request; | ||
| import ru.oop.logic.Response; | ||
| import ru.oop.logic.services.UserService; | ||
| import ru.oop.logic.models.User; | ||
|
|
||
| import java.util.regex.Matcher; | ||
| import java.util.regex.Pattern; | ||
|
|
||
| public class StartCommand implements Command { | ||
| private final UserService userService; | ||
|
|
||
| public StartCommand(UserService userService) { | ||
| this.userService = userService; | ||
| } | ||
|
|
||
| @Override | ||
| public Pattern getCommandPattern() { | ||
| return Pattern.compile("/start(?:\\s+(\\w+))?"); | ||
| } | ||
|
|
||
| @Override | ||
| public Response executeCommand(Request request, Matcher matched, User currentUser) { | ||
| try { | ||
| Long telegramId = currentUser.getTelegramId(); | ||
| String argument = matched.group(1); | ||
|
|
||
| if (argument != null) { | ||
| userService.updateUsernameIfChanged(telegramId, argument); | ||
| return new Response("Имя пользователя обновлено на: " + argument); | ||
| } else if (currentUser != null) { | ||
| String actualUsername = currentUser.getUsername(); | ||
| if (actualUsername != null && !actualUsername.isEmpty()) { | ||
| userService.updateUsernameIfChanged(telegramId, actualUsername); | ||
| } | ||
| return new Response("Добро пожаловать, @" + currentUser.getUsername() + "!"); | ||
| } | ||
|
|
||
|
|
||
| return new Response("Добро пожаловать, @" + (currentUser != null ? currentUser.getUsername() : "новый пользователь") + "!"); | ||
| } catch (Exception e) { | ||
| return new Response("Произошла ошибка: " + e.getMessage()); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -7,6 +7,8 @@ | |
| import org.hibernate.query.Query; | ||
| import ru.oop.logic.models.User; | ||
|
|
||
| import java.util.List; | ||
|
|
||
| public class UserRepositoryImpl implements UserRepository { | ||
|
|
||
| private final SessionFactory sessionFactory; | ||
|
|
@@ -37,7 +39,7 @@ public User update(User user) { | |
| Transaction transaction = null; | ||
| try (Session session = sessionFactory.openSession()) { | ||
| transaction = session.beginTransaction(); | ||
| User updatedUser = (User) session.merge(user); | ||
| User updatedUser = session.merge(user); | ||
| transaction.commit(); | ||
| return updatedUser; | ||
| } catch (Exception e) { | ||
|
|
@@ -62,8 +64,7 @@ public User findByTelegramId(Long id) { | |
| try (Session session = sessionFactory.openSession()) { | ||
| String hql = "FROM User u WHERE u.telegramId = :telegramId"; | ||
| Query<User> query = session.createQuery(hql, User.class); | ||
| query.setParameter("telegramId", id); // Замените "name" на имя, которое ищете | ||
| // Возвращает единственного пользователя или null | ||
| query.setParameter("telegramId", id); | ||
| return query.uniqueResult(); | ||
| } catch (Exception e) { | ||
| throw new RuntimeException("Ошибка при поиске User с ID: " + id, e); | ||
|
|
@@ -81,6 +82,17 @@ public User findByUsername(String username) { | |
| } | ||
| } | ||
|
|
||
| public List<User> findByUsernameLike(String usernamePart) { | ||
| try (Session session = sessionFactory.openSession()) { | ||
| String hql = "FROM User u WHERE u.username LIKE :usernamePart"; | ||
| Query<User> query = session.createQuery(hql, User.class); | ||
| query.setParameter("usernamePart", "%" + usernamePart + "%"); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Кажется, что |
||
| return query.list(); | ||
| } catch (Exception e) { | ||
| throw new RuntimeException("Ошибка при поиске пользователей по имени, содержащему: " + usernamePart, e); | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public void deleteById(Long id) { | ||
| Transaction transaction = null; | ||
|
|
@@ -98,8 +110,4 @@ public void deleteById(Long id) { | |
| throw new RuntimeException("Ошибка при удалении User с ID: " + id, e); | ||
| } | ||
| } | ||
|
|
||
| public void close() { | ||
| sessionFactory.close(); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
Лучше всего этот try внести из каждой команды и расположить в месте, где вы вызываете этот метод