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);
}
}
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;
}
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;
}
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";
}
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;
}
Aggregations