Search in sources :

Example 1 with Sample

use of ca.corefacility.bioinformatics.irida.model.sample.Sample in project irida by phac-nml.

the class AnalysisController method getSistrAnalysis.

/**
 * Get the sistr analysis information to display
 *
 * @param id ID of the analysis submission
 * @return Json results for the SISTR analysis
 */
@SuppressWarnings("resource")
@RequestMapping("/ajax/sistr/{id}")
@ResponseBody
public Map<String, Object> getSistrAnalysis(@PathVariable Long id) {
    AnalysisSubmission submission = analysisSubmissionService.read(id);
    Collection<Sample> samples = sampleService.getSamplesForAnalysisSubmission(submission);
    Map<String, Object> result = ImmutableMap.of("parse_results_error", true);
    final String sistrFileKey = "sistr-predictions";
    // Get details about the workflow
    UUID workflowUUID = submission.getWorkflowId();
    IridaWorkflow iridaWorkflow;
    try {
        iridaWorkflow = workflowsService.getIridaWorkflow(workflowUUID);
    } catch (IridaWorkflowNotFoundException e) {
        logger.error("Error finding workflow, ", e);
        throw new EntityNotFoundException("Couldn't find workflow for submission " + submission.getId(), e);
    }
    AnalysisType analysisType = iridaWorkflow.getWorkflowDescription().getAnalysisType();
    if (analysisType.equals(AnalysisType.SISTR_TYPING)) {
        Analysis analysis = submission.getAnalysis();
        Path path = analysis.getAnalysisOutputFile(sistrFileKey).getFile();
        try {
            String json = new Scanner(new BufferedReader(new FileReader(path.toFile()))).useDelimiter("\\Z").next();
            // verify file is proper json file
            ObjectMapper mapper = new ObjectMapper();
            List<Map<String, Object>> sistrResults = mapper.readValue(json, new TypeReference<List<Map<String, Object>>>() {
            });
            if (sistrResults.size() > 0) {
                // should only ever be one sample for these results
                if (samples.size() == 1) {
                    Sample sample = samples.iterator().next();
                    result = sistrResults.get(0);
                    result.put("parse_results_error", false);
                    result.put("sample_name", sample.getSampleName());
                } else {
                    logger.error("Invalid number of associated samles for submission " + submission);
                }
            } else {
                logger.error("SISTR results for file [" + path + "] are not correctly formatted");
            }
        } catch (FileNotFoundException e) {
            logger.error("File [" + path + "] not found", e);
        } catch (JsonParseException | JsonMappingException e) {
            logger.error("Error attempting to parse file [" + path + "] as JSON", e);
        } catch (IOException e) {
            logger.error("Error reading file [" + path + "]", e);
        }
    }
    return result;
}
Also used : AnalysisType(ca.corefacility.bioinformatics.irida.model.enums.AnalysisType) IridaWorkflow(ca.corefacility.bioinformatics.irida.model.workflow.IridaWorkflow) AnalysisSubmission(ca.corefacility.bioinformatics.irida.model.workflow.submission.AnalysisSubmission) JsonParseException(com.fasterxml.jackson.core.JsonParseException) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Path(java.nio.file.Path) Sample(ca.corefacility.bioinformatics.irida.model.sample.Sample) EntityNotFoundException(ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException) IridaWorkflowNotFoundException(ca.corefacility.bioinformatics.irida.exceptions.IridaWorkflowNotFoundException) Analysis(ca.corefacility.bioinformatics.irida.model.workflow.analysis.Analysis) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 2 with Sample

use of ca.corefacility.bioinformatics.irida.model.sample.Sample in project irida by phac-nml.

the class ProjectSamplesController method downloadSamples.

/**
 * Download a set of sequence files from selected samples within a project
 *
 * @param projectId Id for a {@link Project}
 * @param ids       List of ids ofr {@link Sample} within the project
 * @param response  {@link HttpServletResponse}
 * @throws IOException if we fail to read a file from the filesystem.
 */
@RequestMapping(value = "/projects/{projectId}/download/files")
public void downloadSamples(@PathVariable Long projectId, @RequestParam(value = "ids[]") List<Long> ids, HttpServletResponse response) throws IOException {
    Project project = projectService.read(projectId);
    List<Sample> samples = (List<Sample>) sampleService.readMultiple(ids);
    // Add the appropriate headers
    response.setContentType("application/zip");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + project.getName() + ".zip\"");
    response.setHeader("Transfer-Encoding", "chunked");
    // storing used file names to ensure we don't have a conflict
    Set<String> usedFileNames = new HashSet<>();
    try (ZipOutputStream outputStream = new ZipOutputStream(response.getOutputStream())) {
        for (Sample sample : samples) {
            Collection<SampleSequencingObjectJoin> sequencingObjectsForSample = sequencingObjectService.getSequencingObjectsForSample(sample);
            for (SampleSequencingObjectJoin join : sequencingObjectsForSample) {
                for (SequenceFile file : join.getObject().getFiles()) {
                    Path path = file.getFile();
                    String fileName = project.getName() + "/" + sample.getSampleName() + "/" + path.getFileName().toString();
                    if (usedFileNames.contains(fileName)) {
                        fileName = handleDuplicate(fileName, usedFileNames);
                    }
                    final ZipEntry entry = new ZipEntry(fileName);
                    // set the file creation time on the zip entry to be
                    // whatever the creation time is on the filesystem
                    final BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
                    entry.setCreationTime(attr.creationTime());
                    entry.setLastModifiedTime(attr.creationTime());
                    outputStream.putNextEntry(entry);
                    usedFileNames.add(fileName);
                    Files.copy(path, outputStream);
                    outputStream.closeEntry();
                }
            }
        }
        outputStream.finish();
    } catch (IOException e) {
        // this generally means that the user has cancelled the download
        // from their web browser; we can safely ignore this
        logger.debug("This *probably* means that the user cancelled the download, " + "but it might be something else, see the stack trace below for more information.", e);
    } catch (Exception e) {
        logger.error("Download failed...", e);
    } finally {
        // close the response outputStream so that we're not leaking
        // streams.
        response.getOutputStream().close();
    }
}
Also used : Path(java.nio.file.Path) Sample(ca.corefacility.bioinformatics.irida.model.sample.Sample) ZipEntry(java.util.zip.ZipEntry) IOException(java.io.IOException) EntityExistsException(ca.corefacility.bioinformatics.irida.exceptions.EntityExistsException) EntityNotFoundException(ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException) IOException(java.io.IOException) AccessDeniedException(org.springframework.security.access.AccessDeniedException) ConstraintViolationException(javax.validation.ConstraintViolationException) Project(ca.corefacility.bioinformatics.irida.model.project.Project) SequenceFile(ca.corefacility.bioinformatics.irida.model.sequenceFile.SequenceFile) ZipOutputStream(java.util.zip.ZipOutputStream) SampleSequencingObjectJoin(ca.corefacility.bioinformatics.irida.model.sample.SampleSequencingObjectJoin) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Example 3 with Sample

use of ca.corefacility.bioinformatics.irida.model.sample.Sample in project irida by phac-nml.

the class ProjectSamplesController method ajaxSamplesMerge.

/**
 * Merges a list of samples into either the first sample in the list with a new name if provided, or into the
 * selected sample based on the id.
 *
 * @param projectId
 * 		The id for the current {@link Project}
 * @param mergeSampleId
 * 		An id for a {@link Sample} to merge the other samples into.
 * @param sampleIds
 * 		A list of ids for {@link Sample} to merge together.
 * @param sampleName
 * 		An optional new name for the {@link Sample}.
 * @param locale
 * 		The {@link Locale} of the current user.
 *
 * @return a map of {@link Sample} properties representing the merged sample.
 */
@RequestMapping(value = "/projects/{projectId}/ajax/samples/merge", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Map<String, Object> ajaxSamplesMerge(@PathVariable Long projectId, @RequestParam Long mergeSampleId, @RequestParam(value = "sampleIds[]") List<Long> sampleIds, @RequestParam String sampleName, Locale locale) {
    Map<String, Object> result = new HashMap<>();
    int samplesMergeCount = sampleIds.size();
    Project project = projectService.read(projectId);
    // Determine which sample to merge into
    Sample mergeIntoSample = sampleService.read(mergeSampleId);
    sampleIds.remove(mergeSampleId);
    if (!Strings.isNullOrEmpty(sampleName)) {
        try {
            mergeIntoSample.setSampleName(sampleName);
            mergeIntoSample = sampleService.update(mergeIntoSample);
        } catch (ConstraintViolationException e) {
            logger.error(e.getLocalizedMessage());
            result.put("result", "error");
            result.put("warnings", getErrorsFromViolationException(e));
            return result;
        }
    }
    // Create an update map
    List<Sample> mergeSamples = sampleIds.stream().map(sampleService::read).collect(Collectors.toList());
    // Merge the samples
    sampleService.mergeSamples(project, mergeIntoSample, mergeSamples);
    result.put("result", "success");
    result.put("message", messageSource.getMessage("project.samples.combine-success", new Object[] { samplesMergeCount, mergeIntoSample.getSampleName() }, locale));
    return result;
}
Also used : Project(ca.corefacility.bioinformatics.irida.model.project.Project) Sample(ca.corefacility.bioinformatics.irida.model.sample.Sample) ConstraintViolationException(javax.validation.ConstraintViolationException)

Example 4 with Sample

use of ca.corefacility.bioinformatics.irida.model.sample.Sample in project irida by phac-nml.

the class ProjectSamplesController method getMergeSamplesInProjectModal.

/**
 * Create a modal dialog to merge samples in a project.
 *
 * @param projectId current {@link Project} identifier
 * @param ids       {@link List} List of {@link Long} identifiers for {@link Sample} to merge.
 * @param model     UI Model
 * @return Path to merge modal template
 */
@RequestMapping(value = "/projects/{projectId}/templates/merge-modal", produces = MediaType.TEXT_HTML_VALUE)
public String getMergeSamplesInProjectModal(@PathVariable Long projectId, @RequestParam(name = "sampleIds[]") List<Long> ids, Model model) {
    Project project = projectService.read(projectId);
    List<Sample> samples = new ArrayList<>();
    List<Sample> locked = new ArrayList<>();
    // check for locked samples
    ids.forEach(i -> {
        ProjectSampleJoin join = sampleService.getSampleForProject(project, i);
        samples.add(join.getObject());
        if (!join.isOwner()) {
            locked.add(join.getObject());
        }
    });
    model.addAttribute("project", project);
    model.addAttribute("samples", samples);
    model.addAttribute("locked", locked);
    return PROJECT_TEMPLATE_DIR + "merge-modal.tmpl";
}
Also used : ProjectSampleJoin(ca.corefacility.bioinformatics.irida.model.joins.impl.ProjectSampleJoin) Project(ca.corefacility.bioinformatics.irida.model.project.Project) Sample(ca.corefacility.bioinformatics.irida.model.sample.Sample)

Example 5 with Sample

use of ca.corefacility.bioinformatics.irida.model.sample.Sample in project irida by phac-nml.

the class ProjectSamplesController method getSampleNamesNotInProject.

/**
 * Get a listing of sample names not found in the current project based on a list.
 *
 * @param projectId   {@link Project} identifier for project
 * @param sampleNames {@link List} of sample names
 * @param projects    List of associated {@link Project} identifiers
 * @param locale      {@link Locale} local of current user
 * @return {@link Map} of Samples not in the current project
 */
@RequestMapping("/projects/{projectId}/ajax/samples/missing")
@ResponseBody
public Map<String, Object> getSampleNamesNotInProject(@PathVariable Long projectId, @RequestParam(value = "projects[]", defaultValue = "") List<Long> projects, @RequestParam(value = "sampleNames[]") List<String> sampleNames, Locale locale) {
    // Need to keep the count for comparison after.
    int originalCount = sampleNames.size();
    // Get a list of all samples for all projects
    projects.add(0, projectId);
    for (Long id : projects) {
        List<Join<Project, Sample>> psj = sampleService.getSamplesForProject(projectService.read(id));
        // See if the name is there
        for (Join<Project, Sample> join : psj) {
            Sample sample = join.getObject();
            if (sampleNames.contains(sample.getLabel())) {
                sampleNames.remove(sample.getLabel());
            }
            if (sampleNames.size() == 0) {
                break;
            }
        }
        if (sampleNames.size() == 0) {
            break;
        }
    }
    Map<String, Object> result = new HashMap<>();
    if (sampleNames.size() > 0) {
        result.put("missingNames", sampleNames);
        result.put("message", messageSource.getMessage("project.sample.filterByFile.error", new Object[] { originalCount - sampleNames.size(), originalCount }, locale));
    } else {
        result.put("success", messageSource.getMessage("project.sample.filterByFile.success", new Object[] {}, locale));
    }
    return result;
}
Also used : Project(ca.corefacility.bioinformatics.irida.model.project.Project) Sample(ca.corefacility.bioinformatics.irida.model.sample.Sample) RelatedProjectJoin(ca.corefacility.bioinformatics.irida.model.joins.impl.RelatedProjectJoin) Join(ca.corefacility.bioinformatics.irida.model.joins.Join) ProjectSampleJoin(ca.corefacility.bioinformatics.irida.model.joins.impl.ProjectSampleJoin) SampleSequencingObjectJoin(ca.corefacility.bioinformatics.irida.model.sample.SampleSequencingObjectJoin)

Aggregations

Sample (ca.corefacility.bioinformatics.irida.model.sample.Sample)243 Test (org.junit.Test)162 Project (ca.corefacility.bioinformatics.irida.model.project.Project)114 WithMockUser (org.springframework.security.test.context.support.WithMockUser)71 ProjectSampleJoin (ca.corefacility.bioinformatics.irida.model.joins.impl.ProjectSampleJoin)62 SampleSequencingObjectJoin (ca.corefacility.bioinformatics.irida.model.sample.SampleSequencingObjectJoin)53 SingleEndSequenceFile (ca.corefacility.bioinformatics.irida.model.sequenceFile.SingleEndSequenceFile)53 SequenceFile (ca.corefacility.bioinformatics.irida.model.sequenceFile.SequenceFile)41 Join (ca.corefacility.bioinformatics.irida.model.joins.Join)33 SequencingObject (ca.corefacility.bioinformatics.irida.model.sequenceFile.SequencingObject)33 Path (java.nio.file.Path)28 ModelMap (org.springframework.ui.ModelMap)28 SequenceFilePair (ca.corefacility.bioinformatics.irida.model.sequenceFile.SequenceFilePair)24 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)24 AnalysisSubmission (ca.corefacility.bioinformatics.irida.model.workflow.submission.AnalysisSubmission)23 ArrayList (java.util.ArrayList)22 EntityNotFoundException (ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException)17 User (ca.corefacility.bioinformatics.irida.model.user.User)14 HashMap (java.util.HashMap)14 RelatedProjectJoin (ca.corefacility.bioinformatics.irida.model.joins.impl.RelatedProjectJoin)13