Search in sources :

Example 26 with EntityNotFoundException

use of de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException in project ArTEMiS by ls1intum.

the class TextSubmissionResource method getTextSubmissionWithResults.

/**
 * GET /text-submissions/:id : get the "id" textSubmission.
 *
 * @param submissionId the id of the textSubmission to retrieve
 * @return the ResponseEntity with status 200 (OK) and with body the textSubmission, or with status 404 (Not Found)
 */
@GetMapping("/text-submissions/{submissionId}")
@PreAuthorize("hasRole('USER')")
public ResponseEntity<TextSubmission> getTextSubmissionWithResults(@PathVariable Long submissionId) {
    log.debug("REST request to get TextSubmission : {}", submissionId);
    var textSubmission = textSubmissionRepository.findWithEagerResultsById(submissionId).orElseThrow(() -> new EntityNotFoundException("TextSubmission", submissionId));
    if (!authCheckService.isAtLeastTeachingAssistantForExercise(textSubmission.getParticipation().getExercise())) {
        // anonymize and throw exception if not authorized to view submission
        plagiarismService.anonymizeSubmissionForStudent(textSubmission, userRepository.getUser().getLogin());
        return ResponseEntity.ok(textSubmission);
    }
    // Add the jwt token as a header to the response for tutor-assessment tracking to the request if the athene profile is set
    final ResponseEntity.BodyBuilder bodyBuilder = ResponseEntity.ok();
    if (textSubmission.getLatestResult() != null) {
        this.atheneTrackingTokenProvider.ifPresent(atheneTrackingTokenProvider -> atheneTrackingTokenProvider.addTokenToResponseEntity(bodyBuilder, textSubmission.getLatestResult()));
    }
    return bodyBuilder.body(textSubmission);
}
Also used : ResponseEntity(org.springframework.http.ResponseEntity) EntityNotFoundException(de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Example 27 with EntityNotFoundException

use of de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException in project ArTEMiS by ls1intum.

the class UserResource method updateUser.

/**
 * PUT users : Updates an existing User.
 *
 * @param managedUserVM the user to update
 * @return the ResponseEntity with status 200 (OK) and with body the updated user
 * @throws EmailAlreadyUsedException 400 (Bad Request) if the email is already in use
 * @throws LoginAlreadyUsedException 400 (Bad Request) if the login is already in use
 */
@PutMapping("users")
@PreAuthorize("hasRole('ADMIN')")
public ResponseEntity<UserDTO> updateUser(@Valid @RequestBody ManagedUserVM managedUserVM) {
    checkUsernameAndPasswordValidity(managedUserVM.getLogin(), managedUserVM.getPassword());
    log.debug("REST request to update User : {}", managedUserVM);
    var existingUserByEmail = userRepository.findOneByEmailIgnoreCase(managedUserVM.getEmail());
    if (existingUserByEmail.isPresent() && (!existingUserByEmail.get().getId().equals(managedUserVM.getId()))) {
        throw new EmailAlreadyUsedException();
    }
    var existingUserByLogin = userRepository.findOneWithGroupsAndAuthoritiesByLogin(managedUserVM.getLogin().toLowerCase());
    if (existingUserByLogin.isPresent() && (!existingUserByLogin.get().getId().equals(managedUserVM.getId()))) {
        throw new LoginAlreadyUsedException();
    }
    if (managedUserVM.getGroups().stream().anyMatch(group -> !artemisAuthenticationProvider.isGroupAvailable(group))) {
        throw new EntityNotFoundException("Not all groups are available: " + managedUserVM.getGroups());
    }
    var existingUser = userRepository.findByIdWithGroupsAndAuthoritiesAndOrganizationsElseThrow(managedUserVM.getId());
    final boolean shouldActivateUser = !existingUser.getActivated() && managedUserVM.isActivated();
    final var oldUserLogin = existingUser.getLogin();
    final var oldGroups = existingUser.getGroups();
    var updatedUser = userCreationService.updateUser(existingUser, managedUserVM);
    userService.updateUserInConnectorsAndAuthProvider(updatedUser, oldUserLogin, oldGroups, managedUserVM.getPassword());
    if (shouldActivateUser) {
        userService.activateUser(updatedUser);
    }
    return ResponseEntity.ok().headers(HeaderUtil.createAlert(applicationName, "userManagement.updated", managedUserVM.getLogin())).body(new UserDTO(updatedUser));
}
Also used : UserDTO(de.tum.in.www1.artemis.service.dto.UserDTO) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Example 28 with EntityNotFoundException

use of de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException in project Artemis by ls1intum.

the class TutorParticipationService method addExampleSubmission.

/**
 * Given an exercise, it adds to the tutor participation of that exercise the example submission passed as argument.
 * If it is valid (e.g: if it is an example submission used for tutorial, we check the result is close enough to the one of the instructor)
 *
 * @param exercise               - the exercise we are referring to
 * @param tutorExampleSubmission - the example submission to add
 * @param user                   - the user who invokes this request
 * @return the updated tutor participation
 * @throws EntityNotFoundException if example submission or tutor participation is not found
 * @throws BadRequestAlertException if tutor didn't review the instructions before assessing example submissions
 */
public TutorParticipation addExampleSubmission(Exercise exercise, ExampleSubmission tutorExampleSubmission, User user) throws EntityNotFoundException, BadRequestAlertException {
    TutorParticipation existingTutorParticipation = this.findByExerciseAndTutor(exercise, user);
    // Do not trust the user input
    Optional<ExampleSubmission> exampleSubmissionFromDatabase = exampleSubmissionRepository.findByIdWithResultsAndTutorParticipations(tutorExampleSubmission.getId());
    if (existingTutorParticipation == null || exampleSubmissionFromDatabase.isEmpty()) {
        throw new EntityNotFoundException("There isn't such example submission, or there isn't any tutor participation for this exercise");
    }
    ExampleSubmission originalExampleSubmission = exampleSubmissionFromDatabase.get();
    // Cannot start an example submission if the tutor hasn't participated in the exercise yet
    if (existingTutorParticipation.getStatus() == NOT_PARTICIPATED) {
        throw new BadRequestAlertException("The tutor needs review the instructions before assessing example submissions", ENTITY_NAME, "wrongStatus");
    }
    // Check if it is a tutorial or not
    boolean isTutorial = Boolean.TRUE.equals(originalExampleSubmission.isUsedForTutorial());
    // If it is a tutorial we check the assessment
    if (isTutorial) {
        validateTutorialExampleSubmission(tutorExampleSubmission);
    }
    List<ExampleSubmission> alreadyAssessedSubmissions = new ArrayList<>(existingTutorParticipation.getTrainedExampleSubmissions());
    // If the example submission was already assessed, we do not assess it again, we just return the current participation
    if (alreadyAssessedSubmissions.contains(tutorExampleSubmission)) {
        return existingTutorParticipation;
    }
    long numberOfExampleSubmissionsForTutor = exampleSubmissionRepository.findAllWithResultByExerciseId(exercise.getId()).stream().filter(exSub -> exSub.getSubmission() != null && exSub.getSubmission().getLatestResult() != null && Boolean.TRUE.equals(exSub.getSubmission().getLatestResult().isExampleResult())).count();
    // +1 because we haven't added yet the one we just did
    int numberOfAlreadyAssessedSubmissions = alreadyAssessedSubmissions.size() + 1;
    /*
         * When the tutor has read and assessed all the exercises, the tutor status goes to the next step.
         */
    if (numberOfAlreadyAssessedSubmissions >= numberOfExampleSubmissionsForTutor) {
        existingTutorParticipation.setStatus(TRAINED);
    }
    // keep example submission set reference with loaded submission.results to reconnect after save response from DB
    var exampleSubmissionSet = existingTutorParticipation.getTrainedExampleSubmissions();
    existingTutorParticipation = existingTutorParticipation.addTrainedExampleSubmissions(originalExampleSubmission);
    exampleSubmissionService.save(originalExampleSubmission);
    existingTutorParticipation = tutorParticipationRepository.saveAndFlush(existingTutorParticipation);
    existingTutorParticipation.setTrainedExampleSubmissions(exampleSubmissionSet);
    existingTutorParticipation.getTrainedExampleSubmissions().add(originalExampleSubmission);
    return existingTutorParticipation;
}
Also used : BadRequestAlertException(de.tum.in.www1.artemis.web.rest.errors.BadRequestAlertException) java.util(java.util) JsonProcessingException(org.springframework.cloud.cloudfoundry.com.fasterxml.jackson.core.JsonProcessingException) Logger(org.slf4j.Logger) BadRequestAlertException(de.tum.in.www1.artemis.web.rest.errors.BadRequestAlertException) FeedbackCorrectionErrorType(de.tum.in.www1.artemis.service.TutorParticipationService.FeedbackCorrectionErrorType) ObjectMapper(org.springframework.cloud.cloudfoundry.com.fasterxml.jackson.databind.ObjectMapper) LoggerFactory(org.slf4j.LoggerFactory) Collectors(java.util.stream.Collectors) EntityNotFoundException(de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException) Stream(java.util.stream.Stream) de.tum.in.www1.artemis.domain(de.tum.in.www1.artemis.domain) Service(org.springframework.stereotype.Service) TutorParticipationStatus(de.tum.in.www1.artemis.domain.enumeration.TutorParticipationStatus) ExampleSubmissionRepository(de.tum.in.www1.artemis.repository.ExampleSubmissionRepository) TutorParticipation(de.tum.in.www1.artemis.domain.participation.TutorParticipation) TutorParticipationRepository(de.tum.in.www1.artemis.repository.TutorParticipationRepository) FeedbackType(de.tum.in.www1.artemis.domain.enumeration.FeedbackType) TutorParticipation(de.tum.in.www1.artemis.domain.participation.TutorParticipation) EntityNotFoundException(de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException)

Example 29 with EntityNotFoundException

use of de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException in project Artemis by ls1intum.

the class QuizSubmissionService method saveSubmissionForExamMode.

/**
 * Updates a submission for the exam mode
 *
 * @param quizExercise      the quiz exercise for which the submission for the exam mode should be done
 * @param quizSubmission    the quiz submission includes the submitted answers by the student
 * @param user              the student who wants to submit the quiz during the exam
 * @return                  the updated quiz submission after it has been saved to the database
 */
public QuizSubmission saveSubmissionForExamMode(QuizExercise quizExercise, QuizSubmission quizSubmission, String user) {
    // update submission properties
    quizSubmission.setSubmitted(true);
    quizSubmission.setType(SubmissionType.MANUAL);
    quizSubmission.setSubmissionDate(ZonedDateTime.now());
    Optional<StudentParticipation> optionalParticipation = participationService.findOneByExerciseAndStudentLoginAnyState(quizExercise, user);
    if (optionalParticipation.isEmpty()) {
        log.warn("The participation for quiz exercise {}, quiz submission {} and user {} was not found", quizExercise.getId(), quizSubmission.getId(), user);
        // TODO: think of better way to handle failure
        throw new EntityNotFoundException("Participation for quiz exercise " + quizExercise.getId() + " and quiz submission " + quizSubmission.getId() + " for user " + user + " was not found!");
    }
    StudentParticipation studentParticipation = optionalParticipation.get();
    quizSubmission.setParticipation(studentParticipation);
    // remove result from submission (in the unlikely case it is passed here), so that students cannot inject a result
    quizSubmission.setResults(new ArrayList<>());
    quizSubmissionRepository.save(quizSubmission);
    // versioning of submission
    try {
        submissionVersionService.saveVersionForIndividual(quizSubmission, user);
    } catch (Exception ex) {
        log.error("Quiz submission version could not be saved", ex);
    }
    log.debug("submit exam quiz finished: {}", quizSubmission);
    return quizSubmission;
}
Also used : EntityNotFoundException(de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException) StudentParticipation(de.tum.in.www1.artemis.domain.participation.StudentParticipation) QuizSubmissionException(de.tum.in.www1.artemis.exception.QuizSubmissionException) EntityNotFoundException(de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException)

Example 30 with EntityNotFoundException

use of de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException in project Artemis by ls1intum.

the class ResultService method createNewExampleResultForSubmissionWithExampleSubmission.

/**
 * Create a new example result for the provided submission ID.
 *
 * @param submissionId The ID of the submission (that is connected to an example submission) for which a result should get created
 * @param isProgrammingExerciseWithFeedback defines if the programming exercise contains feedback
 * @return The newly created (and empty) example result
 */
public Result createNewExampleResultForSubmissionWithExampleSubmission(long submissionId, boolean isProgrammingExerciseWithFeedback) {
    final var submission = submissionRepository.findById(submissionId).orElseThrow(() -> new EntityNotFoundException("No example submission with ID " + submissionId + " found!"));
    if (!submission.isExampleSubmission()) {
        throw new IllegalArgumentException("Submission is no example submission! Example results are not allowed!");
    }
    final var newResult = new Result();
    newResult.setSubmission(submission);
    newResult.setExampleResult(true);
    return createNewRatedManualResult(newResult, isProgrammingExerciseWithFeedback);
}
Also used : EntityNotFoundException(de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException)

Aggregations

EntityNotFoundException (de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException)96 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)42 StudentParticipation (de.tum.in.www1.artemis.domain.participation.StudentParticipation)20 BadRequestAlertException (de.tum.in.www1.artemis.web.rest.errors.BadRequestAlertException)20 StudentExam (de.tum.in.www1.artemis.domain.exam.StudentExam)16 AccessForbiddenException (de.tum.in.www1.artemis.web.rest.errors.AccessForbiddenException)12 Exam (de.tum.in.www1.artemis.domain.exam.Exam)10 QuizExercise (de.tum.in.www1.artemis.domain.quiz.QuizExercise)10 AuditEvent (org.springframework.boot.actuate.audit.AuditEvent)10 User (de.tum.in.www1.artemis.domain.User)9 ExerciseGroup (de.tum.in.www1.artemis.domain.exam.ExerciseGroup)8 ModelingExercise (de.tum.in.www1.artemis.domain.modeling.ModelingExercise)8 java.util (java.util)8 Collectors (java.util.stream.Collectors)8 Logger (org.slf4j.Logger)8 LoggerFactory (org.slf4j.LoggerFactory)8 Service (org.springframework.stereotype.Service)8 de.tum.in.www1.artemis.domain (de.tum.in.www1.artemis.domain)6 Course (de.tum.in.www1.artemis.domain.Course)6 Result (de.tum.in.www1.artemis.domain.Result)6