Search in sources :

Example 6 with MetadataEntry

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

the class SISTRSampleUpdater method update.

/**
 * Add SISTR results to the metadata of the given {@link Sample}s
 *
 * @param samples  The samples to update.
 * @param analysis the {@link AnalysisSubmission} to apply to the samples
 * @throws PostProcessingException if the method cannot read the "sistr-predictions" output file
 */
@Override
public void update(Collection<Sample> samples, AnalysisSubmission analysis) throws PostProcessingException {
    AnalysisOutputFile sistrFile = analysis.getAnalysis().getAnalysisOutputFile(SISTR_FILE);
    Path filePath = sistrFile.getFile();
    Map<String, MetadataEntry> stringEntries = new HashMap<>();
    try {
        // Read the JSON file from SISTR output
        @SuppressWarnings("resource") String jsonFile = new Scanner(new BufferedReader(new FileReader(filePath.toFile()))).useDelimiter("\\Z").next();
        // map the results into a Map
        ObjectMapper mapper = new ObjectMapper();
        List<Map<String, Object>> sistrResults = mapper.readValue(jsonFile, new TypeReference<List<Map<String, Object>>>() {
        });
        if (sistrResults.size() > 0) {
            Map<String, Object> result = sistrResults.get(0);
            // loop through each of the requested fields and save the entries
            SISTR_FIELDS.entrySet().forEach(e -> {
                if (result.containsKey(e.getKey()) && result.get(e.getKey()) != null) {
                    String value = result.get(e.getKey()).toString();
                    PipelineProvidedMetadataEntry metadataEntry = new PipelineProvidedMetadataEntry(value, "text", analysis);
                    stringEntries.put(e.getValue(), metadataEntry);
                }
            });
            // convert string map into metadata fields
            Map<MetadataTemplateField, MetadataEntry> metadataMap = metadataTemplateService.getMetadataMap(stringEntries);
            // save metadata back to sample
            samples.forEach(s -> {
                s.mergeMetadata(metadataMap);
                sampleService.updateFields(s.getId(), ImmutableMap.of("metadata", s.getMetadata()));
            });
        } else {
            throw new PostProcessingException("SISTR results for file are not correctly formatted");
        }
    } catch (IOException e) {
        throw new PostProcessingException("Error parsing JSON from SISTR results", e);
    }
}
Also used : Path(java.nio.file.Path) IOException(java.io.IOException) PipelineProvidedMetadataEntry(ca.corefacility.bioinformatics.irida.model.sample.metadata.PipelineProvidedMetadataEntry) PostProcessingException(ca.corefacility.bioinformatics.irida.exceptions.PostProcessingException) BufferedReader(java.io.BufferedReader) PipelineProvidedMetadataEntry(ca.corefacility.bioinformatics.irida.model.sample.metadata.PipelineProvidedMetadataEntry) MetadataEntry(ca.corefacility.bioinformatics.irida.model.sample.metadata.MetadataEntry) FileReader(java.io.FileReader) MetadataTemplateField(ca.corefacility.bioinformatics.irida.model.sample.MetadataTemplateField) AnalysisOutputFile(ca.corefacility.bioinformatics.irida.model.workflow.analysis.AnalysisOutputFile) ImmutableMap(com.google.common.collect.ImmutableMap) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 7 with MetadataEntry

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

the class SampleRemoteRepositoryImpl method getSampleMetadata.

/**
 * {@inheritDoc}
 */
public Map<String, MetadataEntry> getSampleMetadata(Sample sample) {
    logger.trace("Requesting sample metadata for sample " + sample.getSelfHref());
    RemoteAPI remoteAPI = sample.getRemoteStatus().getApi();
    OAuthTokenRestTemplate restTemplate = new OAuthTokenRestTemplate(tokenService, remoteAPI);
    // get the metadata link
    Link metadataLink = sample.getLink(METADATA_REL);
    // request metadata response
    ResponseEntity<ResourceWrapper<SampleMetadataWrapper>> exchange = restTemplate.exchange(metadataLink.getHref(), HttpMethod.GET, HttpEntity.EMPTY, metadataTypeReference);
    // pull metadata response from request
    Map<String, MetadataEntry> resource = exchange.getBody().getResource().getMetadata();
    return resource;
}
Also used : RemoteAPI(ca.corefacility.bioinformatics.irida.model.RemoteAPI) ResourceWrapper(ca.corefacility.bioinformatics.irida.model.remote.resource.ResourceWrapper) ListResourceWrapper(ca.corefacility.bioinformatics.irida.model.remote.resource.ListResourceWrapper) MetadataEntry(ca.corefacility.bioinformatics.irida.model.sample.metadata.MetadataEntry) Link(org.springframework.hateoas.Link) OAuthTokenRestTemplate(ca.corefacility.bioinformatics.irida.repositories.remote.resttemplate.OAuthTokenRestTemplate)

Example 8 with MetadataEntry

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

the class MetadataTemplateServiceImpl method getMetadataMap.

@Override
@Transactional
@PreAuthorize("permitAll()")
public Map<MetadataTemplateField, MetadataEntry> getMetadataMap(Map<String, MetadataEntry> metadataMap) {
    Map<MetadataTemplateField, MetadataEntry> metadata = new HashMap<>();
    metadataMap.entrySet().forEach(e -> {
        // get the metadatatemplatefield if it exists
        MetadataTemplateField field = readMetadataFieldByLabel(e.getKey());
        // if not, create a new one
        if (field == null) {
            field = new MetadataTemplateField(e.getKey(), "text");
            field = saveMetadataField(field);
        }
        metadata.put(field, e.getValue());
    });
    return metadata;
}
Also used : HashMap(java.util.HashMap) MetadataEntry(ca.corefacility.bioinformatics.irida.model.sample.metadata.MetadataEntry) MetadataTemplateField(ca.corefacility.bioinformatics.irida.model.sample.MetadataTemplateField) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) Transactional(javax.transaction.Transactional)

Example 9 with MetadataEntry

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

the class ProjectLineListController method getLineListPage.

/**
 * Get the page to display the project samples linelist.
 *
 * @param projectId
 * 		{@link Long} identifier for the current {@link Project}
 * @param templateId
 * 		{@link Long} id for the current template
 * @param model
 * 		{@link Model}
 * @param locale
 * 		{@link Locale}
 * @param principal
 * 		{@link Principal} currently logged in user.
 *
 * @return {@link String} path to the current page.
 */
@RequestMapping("")
public String getLineListPage(@PathVariable Long projectId, @RequestParam(required = false) Long templateId, Model model, Locale locale, Principal principal) {
    // Set up the template information
    Project project = projectService.read(projectId);
    projectControllerUtils.getProjectTemplateDetails(model, principal, project);
    model.addAttribute("activeNav", "linelist");
    // spreadsheet and is being redirected to this page.
    if (templateId != null) {
        model.addAttribute("currentTemplate", templateId);
    }
    // Get the headers (metadata fields)
    List<String> headers = getAllProjectMetadataFields(projectId, locale);
    model.addAttribute("headers", headers);
    // Get all the metadata for each sample in the project
    List<Join<Project, Sample>> samplesForProject = sampleService.getSamplesForProject(project);
    List<Map<String, Object>> metadataList = new ArrayList<>(samplesForProject.size());
    for (Join<Project, Sample> join : samplesForProject) {
        Sample sample = join.getObject();
        Map<String, Object> fullMetadata = new HashMap<>();
        if (!sample.getMetadata().isEmpty()) {
            Map<MetadataTemplateField, MetadataEntry> metadata = sample.getMetadata();
            Map<String, MetadataEntry> stringMetadata = new HashMap<>();
            metadata.forEach((key, value) -> stringMetadata.put(key.getLabel(), value));
            for (String header : headers) {
                fullMetadata.put(header, stringMetadata.getOrDefault(header, new MetadataEntry("", "")));
            }
            // Id and Label must be defaults in all metadata.
            fullMetadata.put("id", ImmutableMap.of("value", sample.getId()));
            fullMetadata.put("irida-sample-name", ImmutableMap.of("value", sample.getSampleName()));
            // Put this here to avoid showing samples that do not have
            // any metadata associated with them.
            metadataList.add(fullMetadata);
        }
    }
    model.addAttribute("metadataList", metadataList);
    return "projects/project_linelist";
}
Also used : Sample(ca.corefacility.bioinformatics.irida.model.sample.Sample) ProjectMetadataTemplateJoin(ca.corefacility.bioinformatics.irida.model.joins.impl.ProjectMetadataTemplateJoin) Join(ca.corefacility.bioinformatics.irida.model.joins.Join) Project(ca.corefacility.bioinformatics.irida.model.project.Project) MetadataEntry(ca.corefacility.bioinformatics.irida.model.sample.metadata.MetadataEntry) MetadataTemplateField(ca.corefacility.bioinformatics.irida.model.sample.MetadataTemplateField) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 10 with MetadataEntry

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

the class SamplesController method updateSample.

/**
 * Update the details of a sample
 *
 * @param model
 *            Spring {@link Model}
 * @param sampleId
 *            The id for the sample
 * @param collectionDate
 *            Date the sample was collected (Optional)
 * @param metadataString
 *            A JSON string representation of the {@link MetadataEntry} to
 *            set on the sample
 * @param params
 *            Map of fields to update. See FIELDS.
 * @param request
 *            a reference to the current request.
 * @return The name of the details page.
 */
@RequestMapping(value = { "/samples/{sampleId}/edit", "/projects/{projectId}/samples/{sampleId}/edit" }, method = RequestMethod.POST)
public String updateSample(final Model model, @PathVariable Long sampleId, @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date collectionDate, @RequestParam(name = "metadata") String metadataString, @RequestParam Map<String, String> params, HttpServletRequest request) {
    logger.debug("Updating sample [" + sampleId + "]");
    Map<String, Object> updatedValues = new HashMap<>();
    for (String field : FIELDS) {
        String fieldValue = params.get(field);
        if (!Strings.isNullOrEmpty(fieldValue)) {
            updatedValues.put(field, fieldValue);
            model.addAttribute(field, fieldValue);
        }
    }
    // Special case because it is a date field.
    if (collectionDate != null) {
        updatedValues.put(COLLECTION_DATE, collectionDate);
        model.addAttribute(COLLECTION_DATE, collectionDate);
    }
    /**
     * If there's sample metadata to add, add it here.
     */
    Map<String, MetadataEntry> metadataMap;
    if (!Strings.isNullOrEmpty(metadataString)) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            metadataMap = mapper.readValue(metadataString, new TypeReference<Map<String, MetadataEntry>>() {
            });
        } catch (IOException e) {
            throw new IllegalArgumentException("Could not map metadata to sample object", e);
        }
    } else {
        metadataMap = new HashMap<>();
    }
    Map<MetadataTemplateField, MetadataEntry> metadata = metadataTemplateService.getMetadataMap(metadataMap);
    updatedValues.put("metadata", metadata);
    if (updatedValues.size() > 0) {
        try {
            sampleService.updateFields(sampleId, updatedValues);
        } catch (ConstraintViolationException e) {
            model.addAttribute(MODEL_ERROR_ATTR, getErrorsFromViolationException(e));
            return getEditSampleSpecificPage(model, sampleId);
        }
    }
    // this used to read request.getURI(), but request.getURI() includes the
    // context path. When issuing a redirect: return, the redirect: string
    // should **not** contain the context path.
    // HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE contains the
    // matched URL without the context path.
    final String url = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
    final String redirectUrl = url.substring(0, url.indexOf("/edit")) + "/details";
    return "redirect:" + redirectUrl;
}
Also used : IOException(java.io.IOException) MetadataEntry(ca.corefacility.bioinformatics.irida.model.sample.metadata.MetadataEntry) ConstraintViolationException(javax.validation.ConstraintViolationException) SequencingObject(ca.corefacility.bioinformatics.irida.model.sequenceFile.SequencingObject) TypeReference(com.fasterxml.jackson.core.type.TypeReference) MetadataTemplateField(ca.corefacility.bioinformatics.irida.model.sample.MetadataTemplateField) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

MetadataEntry (ca.corefacility.bioinformatics.irida.model.sample.metadata.MetadataEntry)11 MetadataTemplateField (ca.corefacility.bioinformatics.irida.model.sample.MetadataTemplateField)9 Sample (ca.corefacility.bioinformatics.irida.model.sample.Sample)6 ImmutableMap (com.google.common.collect.ImmutableMap)4 Project (ca.corefacility.bioinformatics.irida.model.project.Project)2 AnalysisOutputFile (ca.corefacility.bioinformatics.irida.model.workflow.analysis.AnalysisOutputFile)2 AnalysisSubmission (ca.corefacility.bioinformatics.irida.model.workflow.submission.AnalysisSubmission)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 IOException (java.io.IOException)2 Path (java.nio.file.Path)2 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)2 EntityNotFoundException (ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException)1 PostProcessingException (ca.corefacility.bioinformatics.irida.exceptions.PostProcessingException)1 RemoteAPI (ca.corefacility.bioinformatics.irida.model.RemoteAPI)1 Join (ca.corefacility.bioinformatics.irida.model.joins.Join)1 ProjectMetadataTemplateJoin (ca.corefacility.bioinformatics.irida.model.joins.impl.ProjectMetadataTemplateJoin)1 ListResourceWrapper (ca.corefacility.bioinformatics.irida.model.remote.resource.ListResourceWrapper)1 ResourceWrapper (ca.corefacility.bioinformatics.irida.model.remote.resource.ResourceWrapper)1 PipelineProvidedMetadataEntry (ca.corefacility.bioinformatics.irida.model.sample.metadata.PipelineProvidedMetadataEntry)1 SequencingObject (ca.corefacility.bioinformatics.irida.model.sequenceFile.SequencingObject)1