Search in sources :

Example 6 with Exercise

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

the class ExerciseService method archive.

// does not delete anything
@Transactional
public java.io.File archive(Long id) {
    Exercise exercise = findOneLoadParticipations(id);
    log.info("Request to archive all participations repositories for Exercise : {}", exercise.getTitle());
    List<Path> zippedRepoFiles = new ArrayList<>();
    Path finalZipFilePath = null;
    if (Optional.ofNullable(exercise).isPresent() && exercise instanceof ProgrammingExercise) {
        exercise.getParticipations().forEach(participation -> {
            try {
                if (participation.getRepositoryUrl() != null) {
                    // ignore participations without repository URL
                    // 1. clone the repository
                    Repository repo = gitService.get().getOrCheckoutRepository(participation);
                    // 2. zip repository and collect the zip file
                    log.info("Create temporary zip file for repository " + repo.getLocalPath().toString());
                    Path zippedRepoFile = gitService.get().zipRepository(repo);
                    zippedRepoFiles.add(zippedRepoFile);
                    // 3. delete the locally cloned repo again
                    gitService.get().deleteLocalRepository(participation);
                }
            } catch (IOException | GitAPIException ex) {
                log.error("Archiving and deleting the repository " + participation.getRepositoryUrlAsUrl() + " did not work as expected");
            }
        });
        if (!exercise.getParticipations().isEmpty() && !zippedRepoFiles.isEmpty()) {
            try {
                // create a large zip file with all zipped repos and provide it for download
                log.info("Create zip file for all repositories");
                finalZipFilePath = Paths.get(zippedRepoFiles.get(0).getParent().toString(), exercise.getCourse().getTitle() + " " + exercise.getTitle() + " Student Repositories.zip");
                createZipFile(finalZipFilePath, zippedRepoFiles);
                scheduleForDeletion(finalZipFilePath, 300);
                log.info("Delete all temporary zip repo files");
                // delete the temporary zipped repo files
                for (Path zippedRepoFile : zippedRepoFiles) {
                    Files.delete(zippedRepoFile);
                }
            } catch (IOException ex) {
                log.error("Archiving and deleting the local repositories did not work as expected");
            }
        } else {
            log.info("The zip file could not be created. Ignoring the request to archive repositories", id);
            return null;
        }
    } else {
        log.info("Exercise with id {} is not an instance of ProgrammingExercise. Ignoring the request to archive repositories", id);
        return null;
    }
    return new java.io.File(finalZipFilePath.toString());
}
Also used : Path(java.nio.file.Path) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) ExerciseRepository(de.tum.in.www1.artemis.repository.ExerciseRepository) IOException(java.io.IOException) Transactional(org.springframework.transaction.annotation.Transactional)

Example 7 with Exercise

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

the class ProgrammingExerciseResource method createProgrammingExercise.

/**
 * POST  /programming-exercises : Create a new programmingExercise.
 *
 * @param programmingExercise the programmingExercise to create
 * @return the ResponseEntity with status 201 (Created) and with body the new programmingExercise, or with status 400 (Bad Request) if the programmingExercise has already an ID
 * @throws URISyntaxException if the Location URI syntax is incorrect
 */
@PostMapping("/programming-exercises")
@PreAuthorize("hasAnyRole('TA', 'INSTRUCTOR', 'ADMIN')")
@Timed
public ResponseEntity<ProgrammingExercise> createProgrammingExercise(@RequestBody ProgrammingExercise programmingExercise) throws URISyntaxException {
    log.debug("REST request to save ProgrammingExercise : {}", programmingExercise);
    if (programmingExercise.getId() != null) {
        return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new programmingExercise cannot already have an ID")).body(null);
    }
    // fetch course from database to make sure client didn't change groups
    Course course = courseService.findOne(programmingExercise.getCourse().getId());
    if (course == null) {
        return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "courseNotFound", "The course belonging to this programming exercise does not exist")).body(null);
    }
    User user = userService.getUserWithGroupsAndAuthorities();
    if (!authCheckService.isTeachingAssistantInCourse(course, user) && !authCheckService.isInstructorInCourse(course, user) && !authCheckService.isAdmin()) {
        return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
    }
    ResponseEntity<ProgrammingExercise> errorResponse = checkProgrammingExerciseForError(programmingExercise);
    if (errorResponse != null) {
        return errorResponse;
    }
    ProgrammingExercise result = programmingExerciseRepository.save(programmingExercise);
    return ResponseEntity.created(new URI("/api/programming-exercises/" + result.getId())).headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString())).body(result);
}
Also used : User(de.tum.in.www1.artemis.domain.User) ProgrammingExercise(de.tum.in.www1.artemis.domain.ProgrammingExercise) Course(de.tum.in.www1.artemis.domain.Course) URI(java.net.URI) Timed(com.codahale.metrics.annotation.Timed) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Example 8 with Exercise

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

the class ExerciseResource method createExercise.

/**
 * POST  /exercises : Create a new exercise.
 *
 * @param exercise the exercise to create
 * @return the ResponseEntity with status 201 (Created) and with body the new exercise, or with status 400 (Bad Request) if the exercise has already an ID
 * @throws URISyntaxException if the Location URI syntax is incorrect
 */
@PostMapping("/exercises")
@PreAuthorize("hasAnyRole('TA', 'INSTRUCTOR', 'ADMIN')")
@Timed
public // TODO: test if it still works with abstract entity in body
ResponseEntity<Exercise> createExercise(@RequestBody Exercise exercise) throws URISyntaxException {
    log.debug("REST request to save Exercise : {}", exercise);
    Course course = exercise.getCourse();
    User user = userService.getUserWithGroupsAndAuthorities();
    if (!authCheckService.isTeachingAssistantInCourse(course, user) && !authCheckService.isInstructorInCourse(course, user) && !authCheckService.isAdmin()) {
        return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
    }
    if (exercise.getId() != null) {
        throw new BadRequestAlertException("A new exercise cannot already have an ID", ENTITY_NAME, "idexists");
    }
    if (exercise instanceof ProgrammingExercise) {
        ResponseEntity<Exercise> errorResponse = checkProgrammingExerciseForError((ProgrammingExercise) exercise);
        if (errorResponse != null) {
            return errorResponse;
        }
    }
    Exercise result = exerciseRepository.save(exercise);
    return ResponseEntity.created(new URI("/api/exercises/" + result.getId())).headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString())).body(result);
}
Also used : BadRequestAlertException(de.tum.in.www1.artemis.web.rest.errors.BadRequestAlertException) URI(java.net.URI) Timed(com.codahale.metrics.annotation.Timed) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Example 9 with Exercise

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

the class QuizSubmissionService method submitForPractice.

/**
 * Submit the given submission for practice
 *
 * @param quizSubmission the submission to submit
 * @param quizExercise the exercise to submit in
 * @param participation the participation where the result should be saved
 * @return the result entity
 */
@Transactional
public Result submitForPractice(QuizSubmission quizSubmission, QuizExercise quizExercise, Participation participation) {
    // update submission properties
    quizSubmission.setSubmitted(true);
    quizSubmission.setType(SubmissionType.MANUAL);
    // calculate scores
    quizSubmission.calculateAndUpdateScores(quizExercise);
    // create and save result
    Result result = new Result().participation(participation).submission(quizSubmission);
    result.setRated(false);
    result.setCompletionDate(ZonedDateTime.now());
    // calculate score and update result accordingly
    result.evaluateSubmission();
    // save result
    resultRepository.save(result);
    // replace proxy with submission, because of Lazy-fetching
    result.setSubmission(quizSubmission);
    // add result to statistics
    QuizScheduleService.addResultToStatistic(quizExercise.getId(), result);
    return result;
}
Also used : Result(de.tum.in.www1.artemis.domain.Result) Transactional(org.springframework.transaction.annotation.Transactional)

Example 10 with Exercise

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

the class ExerciseResourceIntTest method updateExercise.

@Test
@Transactional
public void updateExercise() throws Exception {
    // Initialize the database
    exerciseRepository.saveAndFlush(exercise);
    int databaseSizeBeforeUpdate = exerciseRepository.findAll().size();
    // Update the exercise
    Exercise updatedExercise = exerciseRepository.findOne(exercise.getId());
    updatedExercise.title(UPDATED_TITLE).releaseDate(UPDATED_RELEASE_DATE).dueDate(UPDATED_DUE_DATE);
    restExerciseMockMvc.perform(put("/api/exercises").contentType(TestUtil.APPLICATION_JSON_UTF8).content(TestUtil.convertObjectToJsonBytes(updatedExercise))).andExpect(status().isOk());
    // Validate the Exercise in the database
    List<Exercise> exerciseList = exerciseRepository.findAll();
    assertThat(exerciseList).hasSize(databaseSizeBeforeUpdate);
    Exercise testExercise = exerciseList.get(exerciseList.size() - 1);
    assertThat(testExercise.getTitle()).isEqualTo(UPDATED_TITLE);
    assertThat(testExercise.getReleaseDate()).isEqualTo(UPDATED_RELEASE_DATE);
    assertThat(testExercise.getDueDate()).isEqualTo(UPDATED_DUE_DATE);
}
Also used : ProgrammingExercise(de.tum.in.www1.artemis.domain.ProgrammingExercise) Exercise(de.tum.in.www1.artemis.domain.Exercise) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

ProgrammingExercise (de.tum.in.www1.artemis.domain.ProgrammingExercise)6 Transactional (org.springframework.transaction.annotation.Transactional)6 Timed (com.codahale.metrics.annotation.Timed)4 Exercise (de.tum.in.www1.artemis.domain.Exercise)4 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)4 Course (de.tum.in.www1.artemis.domain.Course)3 User (de.tum.in.www1.artemis.domain.User)3 IOException (java.io.IOException)3 Test (org.junit.Test)3 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)3 ExerciseRepository (de.tum.in.www1.artemis.repository.ExerciseRepository)2 URI (java.net.URI)2 Path (java.nio.file.Path)2 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)2 Result (de.tum.in.www1.artemis.domain.Result)1 BambooException (de.tum.in.www1.artemis.exception.BambooException)1 LtiLaunchRequestDTO (de.tum.in.www1.artemis.web.rest.dto.LtiLaunchRequestDTO)1 BadRequestAlertException (de.tum.in.www1.artemis.web.rest.errors.BadRequestAlertException)1