Search in sources :

Example 11 with MetadataTemplateField

use of ca.corefacility.bioinformatics.irida.model.sample.MetadataTemplateField 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 12 with MetadataTemplateField

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

the class ProjectLineListController method saveLinelistTemplate.

/**
 * Save a new line list template.
 *
 * @param projectId    {@link Long} id for the current project
 * @param templateName {@link String} name for the new template
 * @param fields       The fields to save to the template
 * @return The result of saving.
 */
@RequestMapping(value = "/linelist-templates/save-template/{templateName}", consumes = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> saveLinelistTemplate(@PathVariable Long projectId, @PathVariable String templateName, @RequestBody List<Map<String, String>> fields) {
    Project project = projectService.read(projectId);
    List<MetadataTemplateField> metadataFields = new ArrayList<>();
    for (Map<String, String> field : fields) {
        String label = field.get("label");
        // Label and identifier are default that are always in the list.
        MetadataTemplateField metadataField;
        if (field.containsKey("identifier")) {
            // Identifier would indicate an existing field.  Therefore we should use the existing field
            // instead of creating a new one.
            metadataField = metadataTemplateService.readMetadataField(Long.parseLong(field.get("identifier")));
        } else {
            // Check to see if the field already exists
            metadataField = metadataTemplateService.readMetadataFieldByLabel(label);
            if (metadataField == null) {
                metadataField = new MetadataTemplateField(label, field.get("type"));
                metadataTemplateService.saveMetadataField(metadataField);
            }
        }
        metadataFields.add(metadataField);
    }
    MetadataTemplate metadataTemplate = new MetadataTemplate(templateName, metadataFields);
    ProjectMetadataTemplateJoin projectMetadataTemplateJoin = metadataTemplateService.createMetadataTemplateInProject(metadataTemplate, project);
    return ImmutableMap.of("templateId", projectMetadataTemplateJoin.getObject().getId());
}
Also used : Project(ca.corefacility.bioinformatics.irida.model.project.Project) MetadataTemplate(ca.corefacility.bioinformatics.irida.model.sample.MetadataTemplate) ProjectMetadataTemplateJoin(ca.corefacility.bioinformatics.irida.model.joins.impl.ProjectMetadataTemplateJoin) MetadataTemplateField(ca.corefacility.bioinformatics.irida.model.sample.MetadataTemplateField)

Example 13 with MetadataTemplateField

use of ca.corefacility.bioinformatics.irida.model.sample.MetadataTemplateField 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 14 with MetadataTemplateField

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

the class ProjectSamplesMetadataTemplateController method downloadTemplate.

/**
 * Download a {@link MetadataTemplate} as an Excel file.
 *
 * @param templateId
 * 		{@link Long} identifier for a {@link MetadataTemplate}
 * @param response
 * 		{@link HttpServletResponse}
 *
 * @throws IOException
 * 		thrown if output stream cannot be used.
 */
@RequestMapping(value = "/{templateId}/excel")
public void downloadTemplate(@PathVariable Long templateId, HttpServletResponse response) throws IOException {
    MetadataTemplate template = metadataTemplateService.read(templateId);
    List<MetadataTemplateField> fields = template.getFields();
    List<String> headers = fields.stream().map(MetadataTemplateField::getLabel).collect(Collectors.toList());
    String label = template.getLabel().replace(" ", "_");
    // Blank workbook
    XSSFWorkbook workbook = new XSSFWorkbook();
    // Create a blank sheet
    XSSFSheet worksheet = workbook.createSheet(label);
    // Write the headers
    XSSFRow headerRow = worksheet.createRow(0);
    for (int i = 0; i < headers.size(); i++) {
        XSSFCell cell = headerRow.createCell(i);
        cell.setCellValue(headers.get(i));
    }
    response.setHeader("Content-Disposition", "attachment; filename=\"" + label + ".xlsx\"");
    ServletOutputStream stream = response.getOutputStream();
    workbook.write(stream);
    stream.flush();
}
Also used : XSSFSheet(org.apache.poi.xssf.usermodel.XSSFSheet) MetadataTemplate(ca.corefacility.bioinformatics.irida.model.sample.MetadataTemplate) UIMetadataTemplate(ca.corefacility.bioinformatics.irida.ria.web.models.UIMetadataTemplate) XSSFRow(org.apache.poi.xssf.usermodel.XSSFRow) ServletOutputStream(javax.servlet.ServletOutputStream) XSSFWorkbook(org.apache.poi.xssf.usermodel.XSSFWorkbook) XSSFCell(org.apache.poi.xssf.usermodel.XSSFCell) MetadataTemplateField(ca.corefacility.bioinformatics.irida.model.sample.MetadataTemplateField) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 15 with MetadataTemplateField

use of ca.corefacility.bioinformatics.irida.model.sample.MetadataTemplateField 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

MetadataTemplateField (ca.corefacility.bioinformatics.irida.model.sample.MetadataTemplateField)16 MetadataEntry (ca.corefacility.bioinformatics.irida.model.sample.metadata.MetadataEntry)9 Project (ca.corefacility.bioinformatics.irida.model.project.Project)7 MetadataTemplate (ca.corefacility.bioinformatics.irida.model.sample.MetadataTemplate)6 Sample (ca.corefacility.bioinformatics.irida.model.sample.Sample)6 ProjectMetadataTemplateJoin (ca.corefacility.bioinformatics.irida.model.joins.impl.ProjectMetadataTemplateJoin)5 ImmutableMap (com.google.common.collect.ImmutableMap)4 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)4 AnalysisOutputFile (ca.corefacility.bioinformatics.irida.model.workflow.analysis.AnalysisOutputFile)2 AnalysisSubmission (ca.corefacility.bioinformatics.irida.model.workflow.submission.AnalysisSubmission)2 UIMetadataTemplate (ca.corefacility.bioinformatics.irida.ria.web.models.UIMetadataTemplate)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 IOException (java.io.IOException)2 Path (java.nio.file.Path)2 Test (org.junit.Test)2 EntityNotFoundException (ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException)1 PostProcessingException (ca.corefacility.bioinformatics.irida.exceptions.PostProcessingException)1 Join (ca.corefacility.bioinformatics.irida.model.joins.Join)1 PipelineProvidedMetadataEntry (ca.corefacility.bioinformatics.irida.model.sample.metadata.PipelineProvidedMetadataEntry)1 SequencingObject (ca.corefacility.bioinformatics.irida.model.sequenceFile.SequencingObject)1