Skip to content
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

52 improve code quality bucket related #82

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,44 +1,59 @@
package com.elroykanye.istudybucket.api.controller;

import com.elroykanye.istudybucket.api.dto.BucketDto;
import com.elroykanye.istudybucket.api.dto.response.EntityResponse;
import com.elroykanye.istudybucket.business.service.BucketService;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;
import java.util.List;

@AllArgsConstructor
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/api/bucket")
@Slf4j
public class BucketController {
private final BucketService bucketService;

@PostMapping(value = "", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BucketDto> createBucket(@RequestBody BucketDto newBucket) {
return new ResponseEntity<>(
bucketService.createBucket(newBucket),
HttpStatus.CREATED
);
public ResponseEntity<EntityResponse> addBucket(@RequestBody BucketDto bucketDto) {
log.info("Adding bucket: {}", bucketDto);
return new ResponseEntity<>(bucketService.createBucket(bucketDto), HttpStatus.CREATED);
}

@GetMapping(value = "")
public ResponseEntity<List<BucketDto>> getAll() {
return new ResponseEntity<>(
bucketService.getAllBuckets(),
HttpStatus.OK
);
public ResponseEntity<List<BucketDto>> getBuckets() {
log.info("Getting all buckets");
return ResponseEntity.ok(bucketService.getAllBuckets());
}

@GetMapping(value = "/{bucketId}")
public ResponseEntity<BucketDto> getById(@PathVariable(value = "bucketId") Long bucketId) {
return new ResponseEntity<>(
bucketService.getBucketById(bucketId),
HttpStatus.OK
);
public ResponseEntity<BucketDto> getBucket(@NotNull @PathVariable Long bucketId) {
log.info("Getting bucket by id: {}", bucketId);
return ResponseEntity.ok(bucketService.getBucketById(bucketId));
}

@PutMapping(value = "/{bucketId}")
public ResponseEntity<EntityResponse> updateBucket(@NotNull @PathVariable Long bucketId, @RequestBody BucketDto bucketDto) {
log.info("Updating bucket with id: {}", bucketId);
return ResponseEntity.ok(bucketService.updateBucket(bucketId, bucketDto));
}

@DeleteMapping(value = "/{bucketId}")
public ResponseEntity<Void> deleteById(@NotNull @PathVariable Long bucketId) {;
log.info("Deleting bucket by id: {}", bucketId);
return ResponseEntity.ok(bucketService.deleteBucketById(bucketId));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import lombok.NoArgsConstructor;
import lombok.Setter;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;

@Getter
Expand All @@ -20,14 +22,20 @@ public class BucketDto {
private Long id;

@JsonProperty(value = "bucket_title")
@NotBlank
private String title;

@JsonProperty(value = "bucket_desc")
@NotNull
private String description;

@JsonProperty(value = "creation_date")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime creationDate;
@JsonProperty(value = "created_at")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy HH:mm:ss")
private LocalDateTime createdAt;

@JsonProperty(value = "updated_at")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy HH:mm:ss")
private LocalDateTime updatedAt;

@JsonProperty(value = "group_image")
private String groupImage;
Expand All @@ -37,8 +45,9 @@ public class BucketDto {

// from relationships
@JsonProperty("creator_id")
@NotNull
private Long creatorId;

@JsonProperty("chat_id")
private Long chatId;
@JsonProperty("default_chat_id")
private Long defaultChatId;
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import lombok.Setter;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Getter
Expand Down Expand Up @@ -39,6 +40,7 @@ public class ChatDto {
@JsonProperty(value = "bucket_id")
private Long bucketId;

@Builder.Default
@JsonProperty(value = "participants")
private List<Long> participants;
private List<Long> participants = new ArrayList<>();
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,12 @@
@NoArgsConstructor
@AllArgsConstructor
public class EntityResponse {
@JsonProperty("id")
@JsonProperty(value = "id")
private Long id;
@JsonProperty("message")

@JsonProperty(value = "message")
private String message;

@JsonProperty(value = "entity")
private String entity;
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@ public interface BucketMapper {
@Mappings({
@Mapping(target = "memberCount", expression = "java(bucket.getMemberships().size())"),
@Mapping(target = "creatorId", expression = "java(bucket.getCreator().getId())"),
@Mapping(target = "chatId", expression = "java(bucket.getChatRoom().getId())"),
})
BucketDto mapBucketToDto(Bucket bucket);

@InheritInverseConfiguration
@Mappings({
@Mapping(target = "memberships", ignore = true),
@Mapping(target = "creationDate", ignore = true),
@Mapping(target = "chatRoom", ignore = true),
@Mapping(target = "createdAt", ignore = true),
@Mapping(target = "updatedAt", ignore = true),
@Mapping(target = "chatRooms", ignore = true),
@Mapping(target = "creator", ignore = true),
})
Bucket mapDtoToBucket(BucketDto bucketDto);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,23 @@
package com.elroykanye.istudybucket.business.service;

import com.elroykanye.istudybucket.api.dto.BucketDto;
import com.elroykanye.istudybucket.api.dto.response.EntityResponse;
import com.elroykanye.istudybucket.data.entity.Bucket;

import java.util.List;

public interface BucketService {
BucketDto createBucket(BucketDto newBucket);
EntityResponse createBucket(BucketDto newBucket);

List<BucketDto> getAllBuckets();

BucketDto getBucketById(Long bucketId);

EntityResponse updateBucket(Long bucketId, BucketDto bucketDto);
Void deleteBucketById(Long bucketId);
// entity
Bucket getBucket(Long id);
Bucket getBucketEntity(Long id);
List<Bucket> getBuckets();


}
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,5 @@ public interface ChatService {
EntityResponse updateChat(Long id, ChatDto chatDto);

// entity methods
Chat getChatById(Long id);
Chat getChatEntity(Long id);
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
public interface UserService {
Long saveUser(UserDto userDto);

User getUser(Long id);
User getUser(String username);
User getUserEntity(Long id);
User getUserEntity(String username);

UserDto getUserById(Long id);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ public boolean verifyAccount(String verificationTokenValue, String username) {
verTokenValid.set(verificationToken.getUsername().equals(username));

// get the Optional value for the user from the userRep object
User userToBeVerified = userService.getUser(verificationToken.getUsername());
User userToBeVerified = userService.getUserEntity(verificationToken.getUsername());

// if user is present, perform the action declared,
// pass call to update the user's verification
Expand Down
Original file line number Diff line number Diff line change
@@ -1,30 +1,96 @@
package com.elroykanye.istudybucket.business.service.impl;

import com.elroykanye.istudybucket.api.dto.BucketDto;
import com.elroykanye.istudybucket.api.dto.response.EntityResponse;
import com.elroykanye.istudybucket.business.mapper.BucketMapper;
import com.elroykanye.istudybucket.business.service.BucketService;
import com.elroykanye.istudybucket.business.service.UserService;
import com.elroykanye.istudybucket.data.entity.Bucket;
import com.elroykanye.istudybucket.data.entity.Chat;
import com.elroykanye.istudybucket.data.entity.User;
import com.elroykanye.istudybucket.data.entity.composite.UserInChatKey;
import com.elroykanye.istudybucket.data.entity.relation.UserInChat;
import com.elroykanye.istudybucket.data.enums.ChatType;
import com.elroykanye.istudybucket.data.repository.BucketRepository;
import com.elroykanye.istudybucket.data.repository.ChatRepository;
import com.elroykanye.istudybucket.data.repository.UserInChatRepository;
import com.elroykanye.istudybucket.excetion.EntityException;
import lombok.AllArgsConstructor;
import com.elroykanye.istudybucket.excetion.IStudyBucketException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
@AllArgsConstructor
@RequiredArgsConstructor
public class BucketServiceImpl implements BucketService {
private final BucketRepository bucketRepository;
private final BucketMapper bucketMapper;
private final UserService userService;

private final ChatRepository chatRepository;
private final UserInChatRepository userInChatRepository;

@Override
@Transactional
public BucketDto createBucket(BucketDto bucketDto) {
Bucket savedBucket = bucketRepository.save(bucketMapper.mapDtoToBucket(bucketDto));
bucketDto.setId(savedBucket.getId());
return bucketDto;
public EntityResponse createBucket(BucketDto bucketDto) {
Bucket bucket = bucketMapper.mapDtoToBucket(bucketDto);
User bucketCreator;
Chat defaultChatRoom;
{
if (bucketDto.getCreatorId() == null) {
log.error("creator id is required");
throw new IStudyBucketException.IllegalArgumentException("Creator id is required", HttpStatus.BAD_REQUEST);
}
bucketCreator = userService.getUserEntity(bucketDto.getCreatorId());
}
{
if (bucketDto.getDefaultChatId() != null) {
defaultChatRoom = chatRepository.findById(bucket.getDefaultChatId())
.orElseThrow(() -> new EntityException.EntityNotFoundException("chat", bucketDto.getDefaultChatId()));
if (defaultChatRoom.getBucket() != null) {
throw new EntityException.EntityAlreadyExistsException("bucket chat", defaultChatRoom.getId());
}
if(!Objects.equals(defaultChatRoom.getCreator().getId(), bucketDto.getCreatorId())) {
throw new IStudyBucketException.IllegalStateException("chat creator is not the same as bucket creator", HttpStatus.BAD_REQUEST);
}
} else {
defaultChatRoom = chatRepository.save(Chat.builder()
.bucket(null).createdAt(LocalDateTime.now()).creator(bucketCreator)
.title(bucketDto.getTitle()).description(bucketDto.getDescription())
.type(ChatType.GROUP_PRIVATE)
.build()
);
}
bucket.getChatRooms().add(defaultChatRoom);
bucket.setDefaultChatId(defaultChatRoom.getId());

}


bucket.setCreator(bucketCreator);
bucket.setId(null);
bucket.setCreatedAt(LocalDateTime.now()); bucket.setUpdatedAt(LocalDateTime.now());
bucket = bucketRepository.save(bucket);

// save the chat room
defaultChatRoom.setBucket(bucket);
chatRepository.save(defaultChatRoom);

// save the relation between creator and chatroom
userInChatRepository.save(UserInChat.builder().chat(defaultChatRoom).participant(bucketCreator).joinedAt(LocalDateTime.now())
.userInChatKey(UserInChatKey.builder().userId(bucketCreator.getId()).chatId(defaultChatRoom.getId()).build())
.build());
log.info("Successfully added bucket: {}", bucketDto);
return EntityResponse.builder().id(bucket.getId())
.message("Bucket added successfully").entity("bucket").build();
}

@Override
Expand All @@ -34,21 +100,50 @@ public List<BucketDto> getAllBuckets() {
}

@Override
@Transactional(readOnly = true)
public BucketDto getBucketById(Long bucketId) {
return bucketMapper.mapBucketToDto(getBucket(bucketId));
return bucketMapper.mapBucketToDto(getBucketEntity(bucketId));
}

@Override
public Bucket getBucket(Long id) {
@Transactional
public EntityResponse updateBucket(Long bucketId, BucketDto bucketDto) {
if (bucketId == null || !bucketId.equals(bucketDto.getId())) {
throw new IStudyBucketException.IllegalArgumentException("Bucket id for update not valid");
}
Bucket bucket = getBucketEntity(bucketId);
{
if (!Objects.equals(bucketDto.getTitle(), bucket.getTitle())) {
bucket.setTitle(bucketDto.getTitle());
}
if(!Objects.equals(bucketDto.getDescription(), bucket.getDescription())) {
bucket.setDescription(bucketDto.getDescription());
}
bucket.setUpdatedAt(LocalDateTime.now());
}
return EntityResponse.builder().id(bucketId).message("Updated bucket successfully").entity("bucket").build();
}

@Override
@Transactional(readOnly = true)
public Bucket getBucketEntity(Long id) {
return bucketRepository.findById(id).orElseThrow(() -> {
log.error("Bucket with id {} not found", id);
throw new EntityException.EntityNotFoundException("bucket", id);
});
}

@Override
@Transactional(readOnly = true)
public List<Bucket> getBuckets() {
return bucketRepository.findAll();
}

@Override
@Transactional
public Void deleteBucketById(Long bucketId) {
bucketRepository.findById(bucketId).ifPresentOrElse(bucketRepository::delete, () -> {
throw new EntityException.EntityNotFoundException("bucket", bucketId);
});
return null;
}
}
Loading