Hello everyone.
I have to create a project with Vaadin as part of my studies at university and am now facing a problem.
Since I am not a professional in Vaadin, I have no idea what my error means or how it came about, nor how I can get rid of it.
Perhaps for context: users can send each other friend requests, accept these requests, reject them, etc.
There is a separate view for managing these applications. The functionalities actually all work. However, when I log in to the website with an Incocnito tab with another user while the other window is still open to accept the request, I get the following error message:
There was an exception while trying to navigate to 'friends' with the root cause 'java.lang.IllegalStateException: Cannot access state in VaadinSession or UI without locking the session.'
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'softwareprojekt.spielepartner.views.friends.FriendsView': Failed to instantiate [softwareprojekt.spielepartner.views.friends.FriendsView]: Constructor threw exception
[...] etc.
The source code of my friend view looks like this:
@PageTitle("Friends")
@Route(value = "friends", layout = MainLayout.class)
@Uses(Icon.class)
@RolesAllowed({"ADMIN", "USER"})
public class FriendsView extends Composite<HorizontalLayout> {
private static Grid<UserEntity> friendRequestGrid = new Grid<>(UserEntity.class, false);
private static Grid<UserEntity> friendsGrid = new Grid<>(UserEntity.class, false); private static Grid<UserEntity> openFriendsRequestGrid = new Grid<>(UserEntity.class, false);
private static Grid<UserEntity> blockedUsersGrid = new Grid<>(UserEntity.class, false);
private static Div noFriendRequestsHint;
private static Div noFriendsHint; // Neue Div-Komponente für Freundeshinweis
private final UserService userService;
private final AuthenticatedUser authenticatedUser;
private final Button deleteFriendsButton = new Button("Freund entfernen");
private final Button addFriendRequestButton = new Button("Offene Freundschaftsanfragen verwalten");
private final Button unblockUsersButton = new Button("Blockierte User wieder freigeben");
public FriendsView(UserService userService, AuthenticatedUser authenticatedUser) {
this.userService = userService;
this.authenticatedUser = authenticatedUser;
H3 h3 = new H3("Freundesverwaltung");
h3.setWidth("max-content");
H3 h31 = new H3("Freundschaftsanfragen");
h31.setWidth("max-content");
H5 h5 = new H5("Freunde entfernen");
h5.setWidth("max-content");
H5 h51 = new H5("Freundschaftsanfragen an mich");
h51.setWidth("max-content");
H5 h52 = new H5("Meine Freunde");
h52.setWidth("max-content");
Hr horizontalLine1 = new Hr();
Hr horizontalLine2 = new Hr();
HorizontalLayout myFriendsHeaderLayout = new HorizontalLayout();
myFriendsHeaderLayout.setAlignItems(FlexComponent.Alignment.CENTER);
deleteFriendsButton.setIcon(new Icon(VaadinIcon.TRASH));
deleteFriendsButton.addThemeVariants(ButtonVariant.LUMO_ERROR);
deleteFriendsButton.addClickListener(e -> showDeleteFriendDialog());
HorizontalLayout friendRequestHeaderLayout = new HorizontalLayout();
friendRequestHeaderLayout.setAlignItems(FlexComponent.Alignment.CENTER);
addFriendRequestButton.setIcon(new Icon(VaadinIcon.PENCIL));
addFriendRequestButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
addFriendRequestButton.addClickListener(e -> showOpenFriendRequestsDialog());
unblockUsersButton.setIcon(new Icon(VaadinIcon.UNLOCK));
unblockUsersButton.addThemeVariants(ButtonVariant.LUMO_SUCCESS);
unblockUsersButton.addClickListener(e -> unblockUsersDialog());
getContent().setWidthFull();
friendRequestGrid.addThemeVariants(GridVariant.LUMO_COMPACT, GridVariant.LUMO_NO_BORDER);
friendRequestGrid.setWidth("100%");
friendRequestGrid.getStyle().set("flex-grow", "0");
setFriendRequestGridData();
refreshGrid();
friendsGrid.addThemeVariants(GridVariant.LUMO_COMPACT, GridVariant.LUMO_NO_BORDER); // Konfigurieren des neuen Grid
friendsGrid.setWidth("100%");
friendsGrid.getStyle().set("flex-grow", "0");
setFriendsGridData();
refreshFriendsGrid();
//Die Header-Layouts werden mit den jeweiligen Überschriften und Buttons befüllt
myFriendsHeaderLayout.add(h3, deleteFriendsButton, unblockUsersButton);
friendRequestHeaderLayout.add(h31, addFriendRequestButton);
//Das Horizontale Layout der linken Seite wird mit den Komponenten befüllt
VerticalLayout leftSideVerticalLayout = new VerticalLayout();
leftSideVerticalLayout.add(myFriendsHeaderLayout);
leftSideVerticalLayout.add(horizontalLine1);
leftSideVerticalLayout.add(h52);
leftSideVerticalLayout.add(friendsGrid); // Hinzufügen des neuen Grid
leftSideVerticalLayout.add(noFriendsHint); // Hinzufügen des Hinweises, wenn keine Freunde vorhanden sind
//Das Horizontale Layout der rechten Seite wird mit den Komponenten befüllt.
VerticalLayout rightSideVerticalLayout = new VerticalLayout();
rightSideVerticalLayout.add(friendRequestHeaderLayout);
rightSideVerticalLayout.add(horizontalLine2);
rightSideVerticalLayout.add(h51);
rightSideVerticalLayout.add(friendRequestGrid);
rightSideVerticalLayout.add(noFriendRequestsHint);
getContent().add(leftSideVerticalLayout, rightSideVerticalLayout);
}
private void friendSelect(Select<UserEntity> select) {
authenticatedUser.get().ifPresent(user -> {
List<UserEntity> friends = userService.getFreunde(user.getId());
select.setItems(friends);
select.setItemLabelGenerator(friend -> friend.getVorname() + " " + friend.getName() + " (" + friend.getUserCode() + ")");
});
}
// Hilfsmethode zum Erstellen eines Containers mit drei Buttons
private HorizontalLayout createButtonContainer(UserEntity userEntity) {
HorizontalLayout buttonContainer = new HorizontalLayout();
for (int i = 0; i < 3; i++) {
Button button = new Button();
button.addThemeVariants(ButtonVariant.LUMO_ICON, ButtonVariant.LUMO_TERTIARY);
switch (i) {
case 0:
button.setIcon(new Icon(VaadinIcon.CHECK));
button.addClickListener(e -> this.approveFriendshipRequest(userEntity));
button.addThemeVariants(ButtonVariant.LUMO_SUCCESS);
button.setTooltipText("Anfrage annehmen");
break;
case 1:
button.setIcon(new Icon(VaadinIcon.TRASH));
button.addClickListener(e -> this.declineFriendshipRequest(userEntity)); // Aufruf der Methode zum Ablehnen
button.addThemeVariants(ButtonVariant.LUMO_ERROR);
button.setTooltipText("Anfrage ablehnen");
break;
case 2:
button.setIcon(new Icon(VaadinIcon.CLOSE));
button.addClickListener(e -> this.blockUser(userEntity)); // Aufruf der Methode zum Blockieren
button.addThemeVariants(ButtonVariant.LUMO_ERROR);
button.setTooltipText("User blockieren");
break;
}
buttonContainer.add(button);
}
return buttonContainer;
}
private void setFriendRequestGridData() {
friendRequestGrid.addColumn(UserEntity::getUserCode).setHeader("Benutzer-ID");
friendRequestGrid.addColumn(UserEntity::getVorname).setHeader("Vorname");
friendRequestGrid.addColumn(UserEntity::getName).setHeader("Nachname");
friendRequestGrid.addColumn(new ComponentRenderer<>(this::createButtonContainer)).setHeader("Anfrage bearbeiten");
authenticatedUser.get().ifPresent(user -> {
friendRequestGrid.setItems(userService.getAngefragtVon(user.getId()));
});
noFriendRequestsHint = new Div();
noFriendRequestsHint.setText("Du hast keine offenen Freundschaftsanfragen.");
noFriendRequestsHint.getStyle().set("padding", "var(--lumo-size-l)")
.set("text-align", "center").set("font-style", "italic")
.set("color", "var(--lumo-contrast-70pct)");
}
private void setFriendsGridData() {
friendsGrid.addColumn(UserEntity::getUserCode).setHeader("Benutzer-ID");
friendsGrid.addColumn(UserEntity::getVorname).setHeader("Vorname");
friendsGrid.addColumn(UserEntity::getName).setHeader("Nachname");
noFriendsHint = new Div();
noFriendsHint.setText("Du hast noch keine Freunde.");
noFriendsHint.getStyle().set("padding", "var(--lumo-size-l)")
.set("text-align", "center").set("font-style", "italic")
.set("color", "var(--lumo-contrast-70pct)");
}
private void refreshGrid() {
authenticatedUser.get().ifPresent(user -> {
if (userService.getAngefragtVon(user.getId()).size() > 0) {
friendRequestGrid.setVisible(true);
noFriendRequestsHint.setVisible(false);
friendRequestGrid.getDataProvider().refreshAll();
} else {
friendRequestGrid.setVisible(false);
noFriendRequestsHint.setVisible(true);
}
});
}
private void refreshFriendsGrid() {
authenticatedUser.get().ifPresent(user -> {
List<UserEntity> friends = userService.getFreunde(user.getId());
if (friends.isEmpty()) {
friendsGrid.setVisible(false);
noFriendsHint.setVisible(true);
} else {
friendsGrid.setItems(friends);
friendsGrid.setVisible(true);
noFriendsHint.setVisible(false);
}
});
}
public void approveFriendshipRequest(UserEntity anfrager) {
authenticatedUser.get().ifPresent(user -> {
if (anfrager == null)
return;
userService.anfrageAnnehmen(user.getId(), anfrager.getId());
this.refreshGrid();
this.refreshFriendsGrid(); // Freunde-Grid aktualisieren
Notification successNotification = NotificationService.buildSuccessNotification("Anfrage" + anfrager.getUserCode() + " genehmigt", null);
successNotification.open();
});
}
public void declineFriendshipRequest(UserEntity anfrager) {
authenticatedUser.get().ifPresent(user -> {
if (anfrager == null)
return;
userService.anfrageAblehnen(user.getId(), anfrager.getId());
this.refreshGrid();
Notification errorNotification = NotificationService.buildErrorNofification("Anfrage " + anfrager.getUserCode() + " abgelehnt", null);
errorNotification.open();
});
}
public void blockUser(UserEntity anfrager) {
authenticatedUser.get().ifPresent(user -> {
if (anfrager == null)
return;
userService.blockUser(user.getId(), anfrager.getId());
this.refreshGrid();
Notification successNotification = NotificationService.buildSuccessNotification("User " + anfrager.getUserCode() + " blockiert", null);
successNotification.open();
});
}
private void removeSelectedFriend(UserEntity selectedFriend) {
authenticatedUser.get().ifPresent(user -> {
if (selectedFriend != null) {
userService.removeFriend(user.getId(), selectedFriend.getId());
this.refreshFriendsGrid();
Notification successNotification = NotificationService.buildSuccessNotification("Freund " + selectedFriend.getUserCode() + " entfernt", null);
successNotification.open();
} else {
Notification errorNotification = NotificationService.buildErrorNofification("Kein Freund ausgewählt", null);
errorNotification.open();
}
});
}
private void showOpenFriendRequestsDialog(){
Dialog openFriendsRequestDialog = new Dialog();
openFriendsRequestDialog.setHeaderTitle("Offene Freundschaftsanfragen verwalten");
openFriendsRequestDialog.setCloseOnEsc(false);
openFriendsRequestDialog.setCloseOnOutsideClick(false);
openFriendsRequestDialog.setWidth("80%");
VerticalLayout dialogLayout = new VerticalLayout();
Button addFriendRequestButton = new Button("Freundschaftsanfrage senden");
addFriendRequestButton.setIcon(new Icon(VaadinIcon.PLUS));
addFriendRequestButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
addFriendRequestButton.addClickListener(e -> showSendFriendRequestDialog());
Button closeButton = new Button("Schließen", event -> openFriendsRequestDialog.close());
closeButton.addThemeVariants(ButtonVariant.LUMO_TERTIARY);
openFriendsRequestDialog.getFooter().add(closeButton, addFriendRequestButton);
openFriendsRequestGrid.addThemeVariants(GridVariant.LUMO_COMPACT, GridVariant.LUMO_NO_BORDER);
openFriendsRequestGrid.setWidthFull();
openFriendsRequestGrid.addColumn(UserEntity::getUserCode).setHeader("Benutzer-ID");
openFriendsRequestGrid.addColumn(UserEntity::getVorname).setHeader("Vorname");
openFriendsRequestGrid.addColumn(UserEntity::getName).setHeader("Nachname");
openFriendsRequestGrid.addColumn(new ComponentRenderer<>(userEntity -> {
Button undoRequestButton = new Button(new Icon(VaadinIcon.ARROW_BACKWARD));
undoRequestButton.addClickListener(e -> {
undoFriendRequest(userEntity);
populateOpenFriendsRequestGrid(openFriendsRequestGrid);
});
undoRequestButton.setTooltipText("Freundschaftsanfrage zurückziehen");
return undoRequestButton;
})).setHeader("Anfrage zurückziehen");
populateOpenFriendsRequestGrid(openFriendsRequestGrid);
dialogLayout.add(openFriendsRequestGrid);
openFriendsRequestDialog.add(dialogLayout);
openFriendsRequestDialog.open();
}
private void populateOpenFriendsRequestGrid(Grid<UserEntity> openFriendsRequestGrid) {
authenticatedUser.get().ifPresent(user -> {
List<UserEntity> openFriendRequests = userService.getAngefragtAn(user.getId());
openFriendsRequestGrid.setItems(openFriendRequests);
});
}
private void undoFriendRequest(UserEntity userEntity) {
authenticatedUser.get().ifPresent(user -> {
if (userEntity != null) {
userService.undoFriendRequest(user.getId(), userEntity.getId());
this.refreshGrid();
this.refreshFriendsGrid();
Notification successNotification = NotificationService.buildSuccessNotification("Freundschaftsanfrage an " + userEntity.getUserCode() + " zurückgezogen", null);
successNotification.open();
} else {
Notification errorNotification = NotificationService.buildErrorNofification("Kein Benutzer ausgewählt", null);
errorNotification.open();
}
});
}
private void showSendFriendRequestDialog() {
Dialog sendFriendRequestDialog = new Dialog();
sendFriendRequestDialog.setHeaderTitle("Freundschaftsanfrage senden");
sendFriendRequestDialog.setCloseOnEsc(false);
sendFriendRequestDialog.setCloseOnOutsideClick(false);
VerticalLayout dialogLayout = new VerticalLayout();
Button cancelButton = new Button("Abbrechen", event -> sendFriendRequestDialog.close());
Button buttonSendRequest = new Button("Anfrage senden");
sendFriendRequestDialog.getFooter().add(cancelButton, buttonSendRequest);
TextField textFieldRequestId = new TextField("Benutzer-ID");
textFieldRequestId.setPlaceholder("Benutzer-ID eingeben");
textFieldRequestId.setWidthFull();
textFieldRequestId.setInvalid(true);
textFieldRequestId.setErrorMessage("Bitte eingabe tätigen");
buttonSendRequest.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
buttonSendRequest.addClickListener(e -> {
if (!userService.existsByUserCode(textFieldRequestId.getValue())) {
textFieldRequestId.setInvalid(true);
textFieldRequestId.setErrorMessage("Benutzer-ID nicht gefunden");
textFieldRequestId.setValue("");
} else if (textFieldRequestId.getValue().equals(authenticatedUser.get().get().getUserCode())) {
textFieldRequestId.setInvalid(true);
textFieldRequestId.setErrorMessage("Du kannst dir keine Freundschaftsanfrage senden");
textFieldRequestId.setValue("");
} else {
userService.saveUserAnfrage(authenticatedUser.get().get(), userService.findUserByUserCode(textFieldRequestId.getValue()));
Notification successNotification = NotificationService.buildSuccessNotification("Freundschaftsanfrage erfolgreich gesendet", null);
successNotification.open();
textFieldRequestId.setValue("");
sendFriendRequestDialog.close();
populateOpenFriendsRequestGrid(openFriendsRequestGrid);
}
});
dialogLayout.add(textFieldRequestId);
sendFriendRequestDialog.add(dialogLayout);
sendFriendRequestDialog.open();
}
private void showDeleteFriendDialog(){
Dialog deleteFriendsDialog = new Dialog();
deleteFriendsDialog.setHeaderTitle("Freundschaftsanfrage senden");
deleteFriendsDialog.setCloseOnEsc(false);
deleteFriendsDialog.setCloseOnOutsideClick(false);
VerticalLayout dialogLayout = new VerticalLayout();
Button deleteFriendButton = new Button("Freund entfernen");
deleteFriendButton.addThemeVariants(ButtonVariant.LUMO_ERROR);
Button cancelButton = new Button("Abbrechen", event -> deleteFriendsDialog.close());
cancelButton.addThemeVariants(ButtonVariant.LUMO_TERTIARY);
deleteFriendsDialog.getFooter().add(cancelButton, deleteFriendButton);
Select<UserEntity> myFriendsselect = new Select<>();
myFriendsselect.setLabel("Freund auswählen");
friendSelect(myFriendsselect);
deleteFriendButton.addClickListener(e -> {
removeSelectedFriend(myFriendsselect.getValue());
deleteFriendsDialog.close();
});
dialogLayout.add(myFriendsselect);
deleteFriendsDialog.add(dialogLayout);
deleteFriendsDialog.open();
}
private void unblockUsersDialog() {
Dialog unblockUsersDialog = new Dialog();
unblockUsersDialog.setHeaderTitle("Blockierte User wieder freigeben");
unblockUsersDialog.setCloseOnEsc(false);
unblockUsersDialog.setCloseOnOutsideClick(false);
unblockUsersDialog.setWidth("80%");
VerticalLayout dialogLayout = new VerticalLayout();
Button closeButton = new Button("Schließen", event -> unblockUsersDialog.close());
closeButton.addThemeVariants(ButtonVariant.LUMO_TERTIARY);
unblockUsersDialog.getFooter().add(closeButton);
blockedUsersGrid.addThemeVariants(GridVariant.LUMO_COMPACT, GridVariant.LUMO_NO_BORDER);
blockedUsersGrid.setWidthFull();
blockedUsersGrid.addColumn(UserEntity::getUserCode).setHeader("Benutzer-ID");
blockedUsersGrid.addColumn(UserEntity::getVorname).setHeader("Vorname");
blockedUsersGrid.addColumn(UserEntity::getName).setHeader("Nachname");
blockedUsersGrid.addColumn(new ComponentRenderer<>(userEntity -> {
Button undoRequestButton = new Button(new Icon(VaadinIcon.CHECK));
undoRequestButton.addClickListener(e -> {
userService.unblockUser(authenticatedUser.get().get().getId(), userEntity.getId());
populateBlockedUsersGrid(blockedUsersGrid);
});
undoRequestButton.setTooltipText("Blockierung des User wieder aufheben aufheben");
return undoRequestButton;
})).setHeader("Blockierung aufheben");
populateBlockedUsersGrid(blockedUsersGrid);
dialogLayout.add(blockedUsersGrid);
unblockUsersDialog.add(dialogLayout);
unblockUsersDialog.open();
}
private void populateBlockedUsersGrid(Grid<UserEntity> blockedUsersGrid) {
authenticatedUser.get().ifPresent(user -> {
List<UserEntity> blockedUsers = userService.getBlockedUsers(user.getId());
blockedUsersGrid.setItems(blockedUsers);
});
}
}
Since I currently suspect that the problem has something to do with the UserService, here is the code for that:
@Service
public class UserService {
private final UserEntityRepository repository;
private final BefreundetRepository befreundetRepository;
private final BlockedEntityRepository blockedEntityRepository;
@Autowired
public UserService(UserEntityRepository repository, BefreundetRepository befreundetRepository,BlockedEntityRepository blockedEntityRepository ) {
this.repository = repository;
this.befreundetRepository = befreundetRepository;
this.blockedEntityRepository = blockedEntityRepository;
}
public Optional<UserEntity> get(Long id) {
return repository.findById(id);
}
public UserEntity update(UserEntity entity) {
return repository.save(entity);
}
public void delete(Long id) {
repository.deleteById(id);
}
public Page<UserEntity> list(Pageable pageable) {
return repository.findAll(pageable);
}
public Page<UserEntity> list(Pageable pageable, Specification<UserEntity> filter) {
return repository.findAll(filter, pageable);
}
public int count() {
return (int) repository.count();
}
public UserEntity createUser(String userCode, String name, String vorname, String email, String hashedPassword, Set<Role> roles) {
UserEntity user = new UserEntity();
user.setUserCode(userCode);
user.setName(name);
user.setVorname(vorname);
user.setEmail(email);
user.setHashedPassword(hashedPassword);
user.setRoles(roles != null ? roles : new HashSet<>());
return repository.save(user);
}
@Transactional(readOnly = true)
public UserEntity findUserByEmailAndConfirmationCode(String email, String confirmationCode) {
return repository.findByEmailAndConfirmationCode(email, confirmationCode).orElse(null);
}
public UserEntity findUserByEmail(String email) {
return repository.findByEmail(email);
}
@Transactional(readOnly = true)
public boolean existsByEmail(String email) {
return repository.existsByEmail(email);
}
@Transactional(readOnly = true)
public boolean existsnotByEmail(String email) {
boolean wahrheit = repository.existsByEmail(email);
if(wahrheit == true){
return false;
}else{
return true;
}
}
@Transactional(readOnly = true)
public boolean existsByUserCode(String userCode) {
return repository.existsByUserCode(userCode);
}
public UserEntity findUserByUserCode(String userCode) {
return repository.findByUserCode(userCode);
}
@Transactional
public void saveUserAnfrage(UserEntity user, UserEntity angefragterUser) {
// Stellen Sie sicher, dass die übergebenen UserEntity-Objekte verwaltet sind
user = repository.findById(user.getId()).orElseThrow(() -> new EntityNotFoundException("User not found"));
angefragterUser = repository.findById(angefragterUser.getId()).orElseThrow(() -> new EntityNotFoundException("Requested user not found"));
user.addAnfrage(angefragterUser);
repository.save(user);
}
@Transactional(readOnly = true)
public Set<UserEntity> getAngefragtVon(long userId) {
UserEntity user = repository.findById(userId).orElseThrow(() -> new EntityNotFoundException("User not found"));
return user.getAngefragtVon();
}
@Transactional(readOnly = true)
public List<UserEntity> getAngefragtAn(long userId) {
UserEntity user = repository.findById(userId).orElseThrow(() -> new EntityNotFoundException("User not found"));
return user.getAnfrage().stream().collect(Collectors.toList());
}
@Transactional
public void anfrageAnnehmen(long userId, long anfragerId) {
UserEntity user = repository.findById(userId).orElseThrow(() -> new EntityNotFoundException("User not found"));
UserEntity anfrager = repository.findById(anfragerId).orElseThrow(() -> new EntityNotFoundException("Anfrager not found"));
System.out.println("User ID: " + user.getId());
System.out.println("Anfrager ID: " + anfrager.getId());
System.out.println("User: " + user.toString());
System.out.println("Anfrager: " + anfrager.toString());
if (user == null || anfrager == null) {
throw new IllegalStateException("User or Anfrager is null");
}
anfrager.removeAnfrage(user);
repository.save(anfrager);
BefreundetEntity befreundetEntity1 = new BefreundetEntity();
befreundetEntity1.setUser(user);
befreundetEntity1.setFreund(anfrager);
BefreundetEntity befreundetEntity2 = new BefreundetEntity();
befreundetEntity2.setUser(anfrager);
befreundetEntity2.setFreund(user);
if (befreundetEntity1.getUser() == null || befreundetEntity1.getFreund() == null ||
befreundetEntity2.getUser() == null || befreundetEntity2.getFreund() == null) {
throw new IllegalStateException("BefreundetEntity has null user or freund");
}
user.addFreund(befreundetEntity1);
anfrager.addFreund(befreundetEntity2);
befreundetRepository.save(befreundetEntity1);
befreundetRepository.save(befreundetEntity2);
repository.save(user);
repository.save(anfrager);
}
@Transactional(readOnly = true)
public List<UserEntity> getFreunde(long userId) {
UserEntity user = repository.findById(userId).orElseThrow(() -> new EntityNotFoundException("User not found"));
return user.getFreunde().stream().map(BefreundetEntity::getFreund).collect(Collectors.toList());
}
//Löscht Freund aus Liste
@Transactional
public void removeFriend(long userId, long friendId) {
UserEntity user = repository.findById(userId).orElseThrow(() -> new EntityNotFoundException("User not found"));
UserEntity friend = repository.findById(friendId).orElseThrow(() -> new EntityNotFoundException("Friend not found"));
BefreundetEntity befreundetEntity = befreundetRepository.findByUserAndFreund(user, friend);
if (befreundetEntity != null) {
befreundetRepository.delete(befreundetEntity);
}
BefreundetEntity inverseBefreundetEntity = befreundetRepository.findByUserAndFreund(friend, user);
if (inverseBefreundetEntity != null) {
befreundetRepository.delete(inverseBefreundetEntity);
}
}
@Transactional
public void anfrageAblehnen(long userId, long anfragerId) {
UserEntity user = repository.findById(userId)
.orElseThrow(() -> new EntityNotFoundException("User not found"));
UserEntity anfrager = repository.findById(anfragerId)
.orElseThrow(() -> new EntityNotFoundException("Anfrager not found"));
// Anfrage entfernen
anfrager.removeAnfrage(user);
repository.save(anfrager);
}
@Transactional
public void blockUser(long userId, long anfragerId) {
UserEntity user = repository.findById(userId)
.orElseThrow(() -> new EntityNotFoundException("User not found"));
UserEntity anfrager = repository.findById(anfragerId)
.orElseThrow(() -> new EntityNotFoundException("Anfrager not found"));
// Anfrage entfernen
anfrager.removeAnfrage(user);
repository.save(anfrager);
// Blockierung speichern
BlockedEntity blockedEntity = new BlockedEntity();
blockedEntity.setUser(user);
blockedEntity.setBlockedUser(anfrager);
blockedEntityRepository.save(blockedEntity);
}
@Transactional
public void undoFriendRequest(long userId, long friendId) {
UserEntity user = repository.findById(userId).orElseThrow(() -> new EntityNotFoundException("User not found"));
UserEntity friend = repository.findById(friendId).orElseThrow(() -> new EntityNotFoundException("Friend not found"));
user.getAnfrage().remove(friend);
repository.save(user);
}
@Transactional(readOnly = true)
public List<UserEntity> getBlockedUsers(long userId) {
UserEntity user = repository.findById(userId).orElseThrow(() -> new EntityNotFoundException("User not found"));
return new ArrayList<>(user.getBlocked_users());
}
@Transactional
public void unblockUser(long userId, long blockedUserId) {
UserEntity user = repository.findById(userId).orElseThrow(() -> new EntityNotFoundException("User not found"));
UserEntity blockedUser = repository.findById(blockedUserId).orElseThrow(() -> new EntityNotFoundException("Blocked user not found"));
user.getBlocked_users().remove(blockedUser);
repository.save(user);
}
public String generateUniqueRandomCode(int length) {
String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuilder code = new StringBuilder();
// Überprüfen, ob der generierte Code bereits in der Datenbank vorhanden ist
do {
code.setLength(0); // Zurücksetzen des StringBuilder
for (int i = 0; i < length; i++) {
int index = random.nextInt(characters.length());
code.append(characters.charAt(index));
}
} while (repository.existsByUserCode(code.toString()));
return code.toString();
}
}
I hope I’ve come to the right place with my request. In any case, I would be very grateful if someone could help me.
…and sorry for some of the bad English.