Skip to content

Commit

Permalink
feat: UserAlgorithm controllers
Browse files Browse the repository at this point in the history
  • Loading branch information
Sirnilin committed Aug 18, 2024
1 parent 42e2493 commit d61d209
Show file tree
Hide file tree
Showing 7 changed files with 159 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.battlecodes.backend.configurations;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {

@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package com.battlecodes.backend.controllers;

import com.battlecodes.backend.models.UserAlgorithm;
import com.battlecodes.backend.models.UserModel;
import com.battlecodes.backend.models.requests.AlgorithmIdsRequest;
import com.battlecodes.backend.models.requests.UploadAlgorithmRequest;
import com.battlecodes.backend.services.UserAlgorithmService;
import com.battlecodes.backend.services.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.security.Principal;
import java.util.List;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/algorithms")
@Tag(name = "UserAlgorithmController", description = "Контроллер для управления алгоритмами пользователей")
public class UserAlgorithmController {
private final UserAlgorithmService userAlgorithmService;
private final UserService userService;

@Autowired
private RestTemplate restTemplate;

@Operation(summary = "Загрузить алгоритм", description = "Загружает алгоритм для пользователя с ролью STUDENT")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Алгоритм успешно загружен"),
@ApiResponse(responseCode = "400", description = "Ошибка загрузки алгоритма"),
@ApiResponse(responseCode = "403", description = "Пользователь не состоит в группе")
})
@PostMapping("/upload")
@PreAuthorize("hasRole('ROLE_STUDENT')")
public ResponseEntity<?> uploadAlgorithm(@RequestBody UploadAlgorithmRequest request, Principal principal) {
UserModel user = userService.getUserByEmail(principal.getName());

if (user.getGroup() == null) {
return ResponseEntity.status(403).body("User is not part of any group");
}

if (userAlgorithmService.saveAlgorithm(user, request.getFile(), request.getLanguage())) {
return ResponseEntity.ok().build();
}
return ResponseEntity.badRequest().build();
}

@Operation(summary = "Получить алгоритмы группы", description = "Получает все алгоритмы пользователей в указанной группе для пользователя с ролью TEACHER")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Список алгоритмов",
content = @Content(mediaType = "application/json",
schema = @Schema(implementation = UserAlgorithm.class))),
@ApiResponse(responseCode = "403", description = "Доступ запрещен")
})
@GetMapping("/group/{groupId}/algorithms")
@PreAuthorize("hasRole('ROLE_TEACHER')")
public ResponseEntity<?> getAlgorithmsByGroup(@PathVariable Long groupId, Principal principal) {
List<Long> algorithmIds = userAlgorithmService.getAlgorithmsByGroupId(groupId);

AlgorithmIdsRequest algorithmIdsRequest = new AlgorithmIdsRequest();
algorithmIdsRequest.setAlgorithmIds(algorithmIds);

ResponseEntity<?> response = restTemplate.postForEntity("http://other-microservice/api/process", algorithmIdsRequest, String.class);

return ResponseEntity.status(response.getStatusCode()).body(response.getBody());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ public class UserAlgorithm {
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "user_id")
private Long userId;

@Column(name = "group_id")
private Long groupId;

@Column(name = "language")
private String language;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.battlecodes.backend.models.requests;

import lombok.Data;

import java.util.List;

@Data
public class AlgorithmIdsRequest {
private List<Long> algorithmIds;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.battlecodes.backend.models.requests;

import lombok.Data;

@Data
public class UploadAlgorithmRequest {
private String language;
private byte[] file;
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
import com.battlecodes.backend.models.UserAlgorithm;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface UserAlgorithmRepositories extends JpaRepository<UserAlgorithm, Long> {

List<UserAlgorithm> findAllByGroupId(Long groupId);

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.battlecodes.backend.services;

import com.battlecodes.backend.models.ERole;
import com.battlecodes.backend.models.GroupModel;
import com.battlecodes.backend.models.UserAlgorithm;
import com.battlecodes.backend.models.UserModel;
import com.battlecodes.backend.repositories.GroupRepositories;
import com.battlecodes.backend.repositories.UserAlgorithmRepositories;
import com.battlecodes.backend.repositories.UserRepositories;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class UserAlgorithmService {
final private UserAlgorithmRepositories userAlgorithmRepositories;

public boolean saveAlgorithm(UserModel user, byte[] bytes, String language) {
log.info("Saving algorithm for user {}", user.getId());

UserAlgorithm userAlgorithm = new UserAlgorithm();
userAlgorithm.setUserId(user.getId());
userAlgorithm.setGroupId(user.getGroup().getId());
userAlgorithm.setBytes(bytes);
userAlgorithm.setLanguage(language);

userAlgorithmRepositories.save(userAlgorithm);
return true;
}

public List<Long> getAlgorithmsByGroupId(Long groupId) {
log.info("Getting algorithms for group {}", groupId);
return userAlgorithmRepositories.findAllByGroupId(groupId).stream().map(UserAlgorithm::getId).collect(Collectors.toList());
}
}

0 comments on commit d61d209

Please sign in to comment.