Search in sources :

Example 1 with Attachment

use of de.tum.in.www1.artemis.domain.Attachment in project Artemis by ls1intum.

the class LectureUnitResource method updateLectureUnitsOrder.

/**
 * PUT /lectures/:lectureId/lecture-units-order
 *
 * @param lectureId           the id of the lecture for which to update the lecture unit order
 * @param orderedLectureUnits ordered lecture units
 * @return the ResponseEntity with status 200 (OK) and with body the ordered lecture units
 */
@PutMapping("/lectures/{lectureId}/lecture-units-order")
@PreAuthorize("hasRole('EDITOR')")
public ResponseEntity<List<LectureUnit>> updateLectureUnitsOrder(@PathVariable Long lectureId, @RequestBody List<LectureUnit> orderedLectureUnits) {
    log.debug("REST request to update the order of lecture units of lecture: {}", lectureId);
    Optional<Lecture> lectureOptional = lectureRepository.findByIdWithPostsAndLectureUnitsAndLearningGoals(lectureId);
    if (lectureOptional.isEmpty()) {
        throw new EntityNotFoundException("Lecture", lectureId);
    }
    Lecture lecture = lectureOptional.get();
    if (lecture.getCourse() == null) {
        return conflict();
    }
    authorizationCheckService.checkHasAtLeastRoleInCourseElseThrow(Role.EDITOR, lecture.getCourse(), null);
    // Ensure that exactly as many lecture units have been received as are currently related to the lecture
    if (orderedLectureUnits.size() != lecture.getLectureUnits().size()) {
        return conflict();
    }
    // Ensure that all received lecture units are already related to the lecture
    for (LectureUnit lectureUnit : orderedLectureUnits) {
        if (!lecture.getLectureUnits().contains(lectureUnit)) {
            return conflict();
        }
        // Set the lecture manually as it won't be included in orderedLectureUnits
        lectureUnit.setLecture(lecture);
        // keep bidirectional mapping between attachment unit and attachment
        if (lectureUnit instanceof AttachmentUnit) {
            ((AttachmentUnit) lectureUnit).getAttachment().setAttachmentUnit((AttachmentUnit) lectureUnit);
        }
    }
    lecture.setLectureUnits(orderedLectureUnits);
    Lecture persistedLecture = lectureRepository.save(lecture);
    return ResponseEntity.ok(persistedLecture.getLectureUnits());
}
Also used : Lecture(de.tum.in.www1.artemis.domain.Lecture) LectureUnit(de.tum.in.www1.artemis.domain.lecture.LectureUnit) AttachmentUnit(de.tum.in.www1.artemis.domain.lecture.AttachmentUnit) EntityNotFoundException(de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Example 2 with Attachment

use of de.tum.in.www1.artemis.domain.Attachment in project ArTEMiS by ls1intum.

the class DatabaseUtilService method createCoursesWithExercisesAndLectures.

public List<Course> createCoursesWithExercisesAndLectures(boolean withParticipations) throws Exception {
    ZonedDateTime pastTimestamp = ZonedDateTime.now().minusDays(5);
    ZonedDateTime futureTimestamp = ZonedDateTime.now().plusDays(5);
    ZonedDateTime futureFutureTimestamp = ZonedDateTime.now().plusDays(8);
    Course course1 = ModelFactory.generateCourse(null, pastTimestamp, futureTimestamp, new HashSet<>(), "tumuser", "tutor", "editor", "instructor");
    Course course2 = ModelFactory.generateCourse(null, ZonedDateTime.now().minusDays(8), pastTimestamp, new HashSet<>(), "tumuser", "tutor", "editor", "instructor");
    ModelingExercise modelingExercise = ModelFactory.generateModelingExercise(pastTimestamp, futureTimestamp, futureFutureTimestamp, DiagramType.ClassDiagram, course1);
    modelingExercise.setGradingInstructions("some grading instructions");
    modelingExercise.setExampleSolutionModel("Example solution model");
    modelingExercise.setExampleSolutionExplanation("Example Solution");
    addGradingInstructionsToExercise(modelingExercise);
    modelingExercise.getCategories().add("Modeling");
    modelingExercise.setKnowledge(modelAssessmentKnowledgeService.createNewKnowledge());
    course1.addExercises(modelingExercise);
    TextExercise textExercise = ModelFactory.generateTextExercise(pastTimestamp, futureTimestamp, futureFutureTimestamp, course1);
    textExercise.setGradingInstructions("some grading instructions");
    textExercise.setExampleSolution("Example Solution");
    addGradingInstructionsToExercise(textExercise);
    textExercise.getCategories().add("Text");
    textExercise.setKnowledge(textAssessmentKnowledgeService.createNewKnowledge());
    course1.addExercises(textExercise);
    FileUploadExercise fileUploadExercise = ModelFactory.generateFileUploadExercise(pastTimestamp, futureTimestamp, futureFutureTimestamp, "png", course1);
    fileUploadExercise.setGradingInstructions("some grading instructions");
    fileUploadExercise.setExampleSolution("Example Solution");
    addGradingInstructionsToExercise(fileUploadExercise);
    fileUploadExercise.getCategories().add("File");
    course1.addExercises(fileUploadExercise);
    ProgrammingExercise programmingExercise = ModelFactory.generateProgrammingExercise(pastTimestamp, futureTimestamp, course1);
    programmingExercise.setGradingInstructions("some grading instructions");
    addGradingInstructionsToExercise(programmingExercise);
    programmingExercise.getCategories().add("Programming");
    course1.addExercises(programmingExercise);
    QuizExercise quizExercise = ModelFactory.generateQuizExercise(pastTimestamp, futureTimestamp, course1);
    programmingExercise.getCategories().add("Quiz");
    course1.addExercises(quizExercise);
    Lecture lecture1 = ModelFactory.generateLecture(pastTimestamp, futureFutureTimestamp, course1);
    Attachment attachment1 = ModelFactory.generateAttachment(pastTimestamp, lecture1);
    lecture1.addAttachments(attachment1);
    course1.addLectures(lecture1);
    Lecture lecture2 = ModelFactory.generateLecture(pastTimestamp, futureFutureTimestamp, course1);
    Attachment attachment2 = ModelFactory.generateAttachment(pastTimestamp, lecture2);
    lecture2.addAttachments(attachment2);
    course1.addLectures(lecture2);
    course1 = courseRepo.save(course1);
    course2 = courseRepo.save(course2);
    lectureRepo.save(lecture1);
    lectureRepo.save(lecture2);
    attachmentRepo.save(attachment1);
    attachmentRepo.save(attachment2);
    modelingExercise = exerciseRepo.save(modelingExercise);
    textExercise = exerciseRepo.save(textExercise);
    exerciseRepo.save(fileUploadExercise);
    exerciseRepo.save(programmingExercise);
    exerciseRepo.save(quizExercise);
    if (withParticipations) {
        // create 5 tutor participations and 5 example submissions and connect all of them (to test the many-to-many relationship)
        var tutorParticipations = new ArrayList<TutorParticipation>();
        for (int i = 1; i < 6; i++) {
            var tutorParticipation = new TutorParticipation().tutor(getUserByLogin("tutor" + i));
            tutorParticipationRepo.save(tutorParticipation);
            tutorParticipations.add(tutorParticipation);
        }
        for (int i = 0; i < 5; i++) {
            String validModel = FileUtils.loadFileFromResources("test-data/model-submission/model.54727.json");
            var exampleSubmission = addExampleSubmission(generateExampleSubmission(validModel, modelingExercise, true));
            exampleSubmission.assessmentExplanation("exp");
            for (var tutorParticipation : tutorParticipations) {
                exampleSubmission.addTutorParticipations(tutorParticipation);
            }
            exampleSubmissionRepo.save(exampleSubmission);
        }
        User user = (userRepo.findOneByLogin("student1")).get();
        StudentParticipation participation1 = ModelFactory.generateStudentParticipation(InitializationState.INITIALIZED, modelingExercise, user);
        StudentParticipation participation2 = ModelFactory.generateStudentParticipation(InitializationState.FINISHED, textExercise, user);
        StudentParticipation participation3 = ModelFactory.generateStudentParticipation(InitializationState.UNINITIALIZED, modelingExercise, user);
        Submission modelingSubmission1 = ModelFactory.generateModelingSubmission("model1", true);
        Submission modelingSubmission2 = ModelFactory.generateModelingSubmission("model2", true);
        Submission textSubmission = ModelFactory.generateTextSubmission("text", Language.ENGLISH, true);
        Result result1 = ModelFactory.generateResult(true, 10D);
        Result result2 = ModelFactory.generateResult(true, 12D);
        Result result3 = ModelFactory.generateResult(false, 0D);
        participation1 = studentParticipationRepo.save(participation1);
        participation2 = studentParticipationRepo.save(participation2);
        participation3 = studentParticipationRepo.save(participation3);
        submissionRepository.save(modelingSubmission1);
        submissionRepository.save(modelingSubmission2);
        submissionRepository.save(textSubmission);
        modelingSubmission1.setParticipation(participation1);
        textSubmission.setParticipation(participation2);
        modelingSubmission2.setParticipation(participation3);
        result1.setParticipation(participation1);
        result2.setParticipation(participation3);
        result3.setParticipation(participation2);
        result1 = resultRepo.save(result1);
        result2 = resultRepo.save(result2);
        result3 = resultRepo.save(result3);
        result1.setSubmission(modelingSubmission1);
        result2.setSubmission(modelingSubmission2);
        result3.setSubmission(textSubmission);
        modelingSubmission1.addResult(result1);
        modelingSubmission2.addResult(result2);
        textSubmission.addResult(result3);
        submissionRepository.save(modelingSubmission1);
        submissionRepository.save(modelingSubmission2);
        submissionRepository.save(textSubmission);
    }
    return Arrays.asList(course1, course2);
}
Also used : ModelingSubmission(de.tum.in.www1.artemis.domain.modeling.ModelingSubmission) ModelingExercise(de.tum.in.www1.artemis.domain.modeling.ModelingExercise) JsonParser.parseString(com.google.gson.JsonParser.parseString) ExerciseHint(de.tum.in.www1.artemis.domain.hestia.ExerciseHint) TextPlagiarismResult(de.tum.in.www1.artemis.domain.plagiarism.text.TextPlagiarismResult) ModelingPlagiarismResult(de.tum.in.www1.artemis.domain.plagiarism.modeling.ModelingPlagiarismResult) ZonedDateTime(java.time.ZonedDateTime)

Example 3 with Attachment

use of de.tum.in.www1.artemis.domain.Attachment in project ArTEMiS by ls1intum.

the class LectureImportService method cloneLectureUnit.

/**
 * This helper function clones the {@code importedLectureUnit} and returns it
 *
 * @param importedLectureUnit The original lecture unit to be copied
 * @param newLecture The new lecture to which the lecture units are appended
 * @return The cloned lecture unit
 */
private LectureUnit cloneLectureUnit(final LectureUnit importedLectureUnit, final Lecture newLecture) {
    log.debug("Creating a new LectureUnit from lecture unit {}", importedLectureUnit);
    if (importedLectureUnit instanceof TextUnit) {
        TextUnit textUnit = new TextUnit();
        textUnit.setName(importedLectureUnit.getName());
        textUnit.setReleaseDate(importedLectureUnit.getReleaseDate());
        textUnit.setContent(((TextUnit) importedLectureUnit).getContent());
        return textUnit;
    } else if (importedLectureUnit instanceof VideoUnit) {
        VideoUnit videoUnit = new VideoUnit();
        videoUnit.setName(importedLectureUnit.getName());
        videoUnit.setReleaseDate(importedLectureUnit.getReleaseDate());
        videoUnit.setDescription(((VideoUnit) importedLectureUnit).getDescription());
        videoUnit.setSource(((VideoUnit) importedLectureUnit).getSource());
        return videoUnit;
    } else if (importedLectureUnit instanceof AttachmentUnit) {
        // Create and save the attachment unit, then the attachment itself, as the id is needed for file handling
        AttachmentUnit attachmentUnit = new AttachmentUnit();
        attachmentUnit.setDescription(((AttachmentUnit) importedLectureUnit).getDescription());
        attachmentUnit.setLecture(newLecture);
        lectureUnitRepository.save(attachmentUnit);
        Attachment attachment = cloneAttachment(((AttachmentUnit) importedLectureUnit).getAttachment());
        attachment.setAttachmentUnit(attachmentUnit);
        attachmentRepository.save(attachment);
        attachmentUnit.setAttachment(attachment);
        return attachmentUnit;
    } else if (importedLectureUnit instanceof ExerciseUnit) {
        // We have a dedicated exercise import system, so this is left out for now
        return null;
    }
    return null;
}
Also used : Attachment(de.tum.in.www1.artemis.domain.Attachment)

Example 4 with Attachment

use of de.tum.in.www1.artemis.domain.Attachment in project ArTEMiS by ls1intum.

the class LectureImportService method cloneAttachment.

/**
 * This helper function clones the {@code importedAttachment} (and duplicates its file) and returns it
 *
 * @param importedAttachment The original attachment to be copied
 * @return The cloned attachment with the file also duplicated to the temp directory on disk
 */
private Attachment cloneAttachment(final Attachment importedAttachment) {
    log.debug("Creating a new Attachment from attachment {}", importedAttachment);
    Attachment attachment = new Attachment();
    attachment.setName(importedAttachment.getName());
    attachment.setUploadDate(importedAttachment.getUploadDate());
    attachment.setReleaseDate(importedAttachment.getReleaseDate());
    attachment.setVersion(importedAttachment.getVersion());
    attachment.setAttachmentType(importedAttachment.getAttachmentType());
    Path oldPath = Path.of(fileService.actualPathForPublicPath(importedAttachment.getLink()));
    Path tempPath = Path.of(FilePathService.getTempFilePath(), oldPath.getFileName().toString());
    try {
        log.debug("Copying attachment file from {} to {}", oldPath, tempPath);
        Files.copy(oldPath, tempPath, StandardCopyOption.REPLACE_EXISTING);
        // File was copied to a temp directory and will be moved once we persist the attachment
        attachment.setLink(fileService.publicPathForActualPath(tempPath.toString(), null));
    } catch (IOException e) {
        log.error("Error while copying file", e);
    }
    return attachment;
}
Also used : Path(java.nio.file.Path) Attachment(de.tum.in.www1.artemis.domain.Attachment) IOException(java.io.IOException)

Example 5 with Attachment

use of de.tum.in.www1.artemis.domain.Attachment in project ArTEMiS by ls1intum.

the class AttachmentUnitResource method getAttachmentUnit.

/**
 * GET /lectures/:lectureId/attachment-units/:attachmentUnitId : gets the attachment unit with the specified id
 *
 * @param attachmentUnitId the id of the attachmentUnit to retrieve
 * @param lectureId the id of the lecture to which the unit belongs
 * @return the ResponseEntity with status 200 (OK) and with body the attachment unit, or with status 404 (Not Found)
 */
@GetMapping("/lectures/{lectureId}/attachment-units/{attachmentUnitId}")
@PreAuthorize("hasRole('EDITOR')")
public ResponseEntity<AttachmentUnit> getAttachmentUnit(@PathVariable Long attachmentUnitId, @PathVariable Long lectureId) {
    log.debug("REST request to get AttachmentUnit : {}", attachmentUnitId);
    AttachmentUnit attachmentUnit = attachmentUnitRepository.findByIdElseThrow(attachmentUnitId);
    if (attachmentUnit.getLecture() == null || attachmentUnit.getLecture().getCourse() == null) {
        throw new ConflictException("Lecture unit must be associated to a lecture of a course", "AttachmentUnit", "lectureOrCourseMissing");
    }
    if (!attachmentUnit.getLecture().getId().equals(lectureId)) {
        throw new ConflictException("Requested lecture unit is not part of the specified lecture", "AttachmentUnit", "lectureIdMismatch");
    }
    authorizationCheckService.checkHasAtLeastRoleInCourseElseThrow(Role.EDITOR, attachmentUnit.getLecture().getCourse(), null);
    return ResponseEntity.ok().body(attachmentUnit);
}
Also used : ConflictException(de.tum.in.www1.artemis.web.rest.errors.ConflictException) AttachmentUnit(de.tum.in.www1.artemis.domain.lecture.AttachmentUnit) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Aggregations

PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)16 Attachment (de.tum.in.www1.artemis.domain.Attachment)14 Lecture (de.tum.in.www1.artemis.domain.Lecture)12 AttachmentUnit (de.tum.in.www1.artemis.domain.lecture.AttachmentUnit)8 ConflictException (de.tum.in.www1.artemis.web.rest.errors.ConflictException)8 LectureUnit (de.tum.in.www1.artemis.domain.lecture.LectureUnit)6 URI (java.net.URI)6 BadRequestException (javax.ws.rs.BadRequestException)6 Test (org.junit.jupiter.api.Test)6 WithMockUser (org.springframework.security.test.context.support.WithMockUser)6 AbstractSpringIntegrationBambooBitbucketJiraTest (de.tum.in.www1.artemis.AbstractSpringIntegrationBambooBitbucketJiraTest)4 Course (de.tum.in.www1.artemis.domain.Course)4 ExerciseGroup (de.tum.in.www1.artemis.domain.exam.ExerciseGroup)4 ExerciseUnit (de.tum.in.www1.artemis.domain.lecture.ExerciseUnit)4 AnswerPost (de.tum.in.www1.artemis.domain.metis.AnswerPost)4 Post (de.tum.in.www1.artemis.domain.metis.Post)4 BadRequestAlertException (de.tum.in.www1.artemis.web.rest.errors.BadRequestAlertException)4 BeforeEach (org.junit.jupiter.api.BeforeEach)4 JsonParser.parseString (com.google.gson.JsonParser.parseString)2 User (de.tum.in.www1.artemis.domain.User)2