Search in sources :

Example 11 with de.tum.in.www1.artemis.domain.participation

use of de.tum.in.www1.artemis.domain.participation 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 12 with de.tum.in.www1.artemis.domain.participation

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

the class LtiService method onNewBuildResult.

/**
 * This method is pinged on new build results.
 * It sends an message to the LTI consumer with the new score.
 *
 * @param participation
 */
public void onNewBuildResult(Participation participation) {
    // Get the LTI outcome URL
    Optional<LtiOutcomeUrl> ltiOutcomeUrl = ltiOutcomeUrlRepository.findByUserAndExercise(participation.getStudent(), participation.getExercise());
    ltiOutcomeUrl.ifPresent(ltiOutcomeUrl1 -> {
        String score = "0.00";
        // Get the latest result
        Optional<Result> latestResult = resultRepository.findFirstByParticipationIdOrderByCompletionDateDesc(participation.getId());
        if (latestResult.isPresent() && latestResult.get().getScore() != null) {
            // LTI scores needs to be formatted as String between "0.00" and "1.00"
            score = String.format(Locale.ROOT, "%.2f", latestResult.get().getScore().floatValue() / 100);
        }
        log.debug("Reporting to LTI consumer: Score {} for Participation {}", score, participation);
        try {
            // Using PatchedIMSPOXRequest until they fixed the problem: https://github.com/IMSGlobal/basiclti-util-java/issues/27
            HttpPost request = PatchedIMSPOXRequest.buildReplaceResult(ltiOutcomeUrl1.getUrl(), OAUTH_KEY, OAUTH_SECRET, ltiOutcomeUrl1.getSourcedId(), score, null, false);
            HttpClient client = HttpClientBuilder.create().build();
            HttpResponse response = client.execute(request);
            String responseString = new BasicResponseHandler().handleResponse(response);
            log.debug("Response from LTI consumer: {}", responseString);
            if (response.getStatusLine().getStatusCode() >= 400) {
                throw new HttpResponseException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());
            }
        } catch (Exception e) {
            log.error("Reporting to LTI consumer failed: {}", e);
        }
    });
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpClient(org.apache.http.client.HttpClient) BasicResponseHandler(org.apache.http.impl.client.BasicResponseHandler) HttpResponse(org.apache.http.HttpResponse) HttpResponseException(org.apache.http.client.HttpResponseException) LtiVerificationException(org.imsglobal.lti.launch.LtiVerificationException) InternalAuthenticationServiceException(org.springframework.security.authentication.InternalAuthenticationServiceException) AuthenticationException(org.springframework.security.core.AuthenticationException) HttpResponseException(org.apache.http.client.HttpResponseException) ArtemisAuthenticationException(de.tum.in.www1.artemis.exception.ArtemisAuthenticationException) LtiVerificationResult(org.imsglobal.lti.launch.LtiVerificationResult)

Example 13 with de.tum.in.www1.artemis.domain.participation

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

the class ParticipationResource method getParticipationRepositoryWebUrl.

@GetMapping(value = "/participations/{id}/repositoryWebUrl")
@PreAuthorize("hasAnyRole('USER', 'TA', 'INSTRUCTOR', 'ADMIN')")
public ResponseEntity<String> getParticipationRepositoryWebUrl(@PathVariable Long id, Authentication authentication) {
    log.debug("REST request to get Participation : {}", id);
    Participation participation = participationService.findOne(id);
    Course course = participation.getExercise().getCourse();
    if (!authCheckService.isOwnerOfParticipation(participation)) {
        if (!courseService.userHasTAPermissions(course)) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
    }
    URL url = versionControlService.get().getRepositoryWebUrl(participation);
    return Optional.ofNullable(url).map(result -> new ResponseEntity<>(url.toString(), HttpStatus.OK)).orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
Also used : de.tum.in.www1.artemis.service(de.tum.in.www1.artemis.service) Logger(org.slf4j.Logger) BadRequestAlertException(de.tum.in.www1.artemis.web.rest.errors.BadRequestAlertException) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) LoggerFactory(org.slf4j.LoggerFactory) Timed(com.codahale.metrics.annotation.Timed) HttpStatus(org.springframework.http.HttpStatus) List(java.util.List) de.tum.in.www1.artemis.domain(de.tum.in.www1.artemis.domain) Principal(java.security.Principal) AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) MappingJacksonValue(org.springframework.http.converter.json.MappingJacksonValue) org.springframework.web.bind.annotation(org.springframework.web.bind.annotation) Optional(java.util.Optional) ResponseEntity(org.springframework.http.ResponseEntity) URI(java.net.URI) Authentication(org.springframework.security.core.Authentication) HeaderUtil(de.tum.in.www1.artemis.web.rest.util.HeaderUtil) ResponseEntity(org.springframework.http.ResponseEntity) URL(java.net.URL) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Example 14 with de.tum.in.www1.artemis.domain.participation

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

the class ParticipationResource method getParticipationBuildPlanWebUrl.

@GetMapping(value = "/participations/{id}/buildPlanWebUrl")
@PreAuthorize("hasAnyRole('USER', 'TA', 'INSTRUCTOR', 'ADMIN')")
public ResponseEntity<String> getParticipationBuildPlanWebUrl(@PathVariable Long id) {
    log.debug("REST request to get Participation : {}", id);
    Participation participation = participationService.findOne(id);
    Course course = participation.getExercise().getCourse();
    if (!authCheckService.isOwnerOfParticipation(participation)) {
        if (!courseService.userHasTAPermissions(course)) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
    }
    URL url = continuousIntegrationService.get().getBuildPlanWebUrl(participation);
    return Optional.ofNullable(url).map(result -> new ResponseEntity<>(url.toString(), HttpStatus.OK)).orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
Also used : de.tum.in.www1.artemis.service(de.tum.in.www1.artemis.service) Logger(org.slf4j.Logger) BadRequestAlertException(de.tum.in.www1.artemis.web.rest.errors.BadRequestAlertException) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) LoggerFactory(org.slf4j.LoggerFactory) Timed(com.codahale.metrics.annotation.Timed) HttpStatus(org.springframework.http.HttpStatus) List(java.util.List) de.tum.in.www1.artemis.domain(de.tum.in.www1.artemis.domain) Principal(java.security.Principal) AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) MappingJacksonValue(org.springframework.http.converter.json.MappingJacksonValue) org.springframework.web.bind.annotation(org.springframework.web.bind.annotation) Optional(java.util.Optional) ResponseEntity(org.springframework.http.ResponseEntity) URI(java.net.URI) Authentication(org.springframework.security.core.Authentication) HeaderUtil(de.tum.in.www1.artemis.web.rest.util.HeaderUtil) ResponseEntity(org.springframework.http.ResponseEntity) URL(java.net.URL) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Example 15 with de.tum.in.www1.artemis.domain.participation

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

the class RepositoryResource method getStatus.

/**
 * GET /repository/{id}: Get the "clean" status of the repository. Clean = No uncommitted changes.
 *
 * @param id Participation ID
 * @param request
 * @param authentication
 * @return
 * @throws IOException
 * @throws GitAPIException
 */
@GetMapping(value = "/repository/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<RepositoryStatusDTO> getStatus(@PathVariable Long id, HttpServletRequest request, AbstractAuthenticationToken authentication) throws IOException, GitAPIException {
    log.debug("REST request to get clean status for Repository for Participation : {}", id);
    Participation participation = participationService.findOne(id);
    if (!userHasPermissions(participation))
        return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
    if (!Optional.ofNullable(participation).isPresent()) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
    Repository repository = gitService.get().getOrCheckoutRepository(participation);
    RepositoryStatusDTO status = new RepositoryStatusDTO();
    status.isClean = gitService.get().isClean(repository);
    if (status.isClean) {
        gitService.get().pull(repository);
    }
    return new ResponseEntity<>(status, HttpStatus.OK);
}
Also used : ResponseEntity(org.springframework.http.ResponseEntity) RepositoryStatusDTO(de.tum.in.www1.artemis.web.rest.dto.RepositoryStatusDTO)

Aggregations

Participation (de.tum.in.www1.artemis.domain.Participation)14 Test (org.junit.Test)14 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)14 Repository (de.tum.in.www1.artemis.domain.Repository)7 Transactional (org.springframework.transaction.annotation.Transactional)7 Result (de.tum.in.www1.artemis.domain.Result)5 Timed (com.codahale.metrics.annotation.Timed)4 BadRequestAlertException (de.tum.in.www1.artemis.web.rest.errors.BadRequestAlertException)4 URI (java.net.URI)4 ResponseEntity (org.springframework.http.ResponseEntity)4 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)4 de.tum.in.www1.artemis.domain (de.tum.in.www1.artemis.domain)3 de.tum.in.www1.artemis.service (de.tum.in.www1.artemis.service)3 HeaderUtil (de.tum.in.www1.artemis.web.rest.util.HeaderUtil)3 URISyntaxException (java.net.URISyntaxException)3 URL (java.net.URL)3 Logger (org.slf4j.Logger)3 LoggerFactory (org.slf4j.LoggerFactory)3 HttpStatus (org.springframework.http.HttpStatus)3 Authentication (org.springframework.security.core.Authentication)3