Search in sources :

Example 1 with SampleMetadataStorage

use of ca.corefacility.bioinformatics.irida.ria.utilities.SampleMetadataStorage in project irida by phac-nml.

the class ProjectSampleMetadataController method saveProjectSampleMetadata.

/**
 * Save uploaded metadata to the
 *
 * @param locale
 * 		{@link Locale} of the current user.
 * @param session
 * 		{@link HttpSession}
 * @param projectId
 * 		{@link Long} identifier for the current project
 *
 * @return {@link Map} of potential errors.
 */
@RequestMapping(value = "/upload/save", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> saveProjectSampleMetadata(Locale locale, HttpSession session, @PathVariable long projectId) {
    Map<String, Object> errors = new HashMap<>();
    Project project = projectService.read(projectId);
    SampleMetadataStorage stored = (SampleMetadataStorage) session.getAttribute("pm-" + projectId);
    if (stored == null) {
        errors.put("stored-error", true);
    }
    List<Sample> samplesToUpdate = new ArrayList<>();
    List<Map<String, String>> found = stored.getFound();
    if (found != null) {
        // Lets try to get a sample
        String sampleNameColumn = stored.getSampleNameColumn();
        List<String> errorList = new ArrayList<>();
        try {
            for (Map<String, String> row : found) {
                String name = row.get(sampleNameColumn);
                Sample sample = sampleService.getSampleBySampleName(project, name);
                row.remove(sampleNameColumn);
                Map<MetadataTemplateField, MetadataEntry> newData = new HashMap<>();
                // Need to overwrite duplicate keys
                for (Entry<String, String> entry : row.entrySet()) {
                    MetadataTemplateField key = metadataTemplateService.readMetadataFieldByLabel(entry.getKey());
                    if (key == null) {
                        key = metadataTemplateService.saveMetadataField(new MetadataTemplateField(entry.getKey(), "text"));
                    }
                    newData.put(key, new MetadataEntry(entry.getValue(), "text"));
                }
                sample.mergeMetadata(newData);
                // Save metadata back to the sample
                samplesToUpdate.add(sample);
            }
            sampleService.updateMultiple(samplesToUpdate);
        } catch (EntityNotFoundException e) {
            // This really should not happen, but hey, you never know!
            errorList.add(messageSource.getMessage("metadata.results.save.sample-not-found", new Object[] { e.getMessage() }, locale));
        }
        if (errorList.size() > 0) {
            errors.put("save-errors", errorList);
        }
    } else {
        errors.put("found-error", messageSource.getMessage("metadata.results.save.found-error", new Object[] {}, locale));
    }
    if (errors.size() == 0) {
        return ImmutableMap.of("success", messageSource.getMessage("metadata.results.save.success", new Object[] { found.size() }, locale));
    }
    return errors;
}
Also used : Sample(ca.corefacility.bioinformatics.irida.model.sample.Sample) EntityNotFoundException(ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException) Project(ca.corefacility.bioinformatics.irida.model.project.Project) SampleMetadataStorage(ca.corefacility.bioinformatics.irida.ria.utilities.SampleMetadataStorage) MetadataEntry(ca.corefacility.bioinformatics.irida.model.sample.metadata.MetadataEntry) MetadataTemplateField(ca.corefacility.bioinformatics.irida.model.sample.MetadataTemplateField) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 2 with SampleMetadataStorage

use of ca.corefacility.bioinformatics.irida.ria.utilities.SampleMetadataStorage in project irida by phac-nml.

the class ProjectSampleMetadataController method createProjectSampleMetadata.

/**
 * Upload Excel file containing sample metadata and extract the headers.  The file is stored in the session until
 * the column that corresponds to a {@link Sample} identifier has been sent.
 *
 * @param session   {@link HttpSession}
 * @param projectId {@link Long} identifier for the current {@link Project}
 * @param file      {@link MultipartFile} The excel file containing the metadata.
 * @return {@link Map} of headers and rows from the excel file for the user to select the header corresponding the
 * {@link Sample} identifier.
 */
@RequestMapping(value = "/upload/file", method = RequestMethod.POST)
@ResponseBody
public SampleMetadataStorage createProjectSampleMetadata(HttpSession session, @PathVariable long projectId, @RequestParam("file") MultipartFile file) {
    // We want to return a list of the table headers back to the UI.
    SampleMetadataStorage storage = new SampleMetadataStorage();
    try {
        // Need an input stream
        String filename = file.getOriginalFilename();
        byte[] byteArr = file.getBytes();
        InputStream fis = new ByteArrayInputStream(byteArr);
        Workbook workbook;
        String extension = Files.getFileExtension(filename);
        // Check the type of workbook
        switch(extension) {
            case "xlsx":
                workbook = new XSSFWorkbook(fis);
                break;
            case "xls":
                workbook = new HSSFWorkbook(fis);
                break;
            default:
                // Should never reach here as the uploader limits to .xlsx and .xlx files.
                throw new MetadataImportFileTypeNotSupportedError(extension);
        }
        // Only look at the first sheet in the workbook as this should be the file we want.
        Sheet sheet = workbook.getSheetAt(0);
        Iterator<Row> rowIterator = sheet.iterator();
        List<String> headers = getWorkbookHeaders(rowIterator.next());
        storage.saveHeaders(headers);
        // Get the metadata out of the table.
        List<Map<String, String>> rows = new ArrayList<>();
        while (rowIterator.hasNext()) {
            Map<String, String> rowMap = new HashMap<>();
            Row row = rowIterator.next();
            Iterator<Cell> cellIterator = row.cellIterator();
            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                int columnIndex = cell.getColumnIndex();
                if (columnIndex < headers.size()) {
                    String header = headers.get(columnIndex);
                    if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
                        rowMap.put(header, "");
                    } else {
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        rowMap.put(header, cell.getStringCellValue());
                    }
                }
            }
            rows.add(rowMap);
        }
        storage.saveRows(rows);
        fis.close();
    } catch (FileNotFoundException e) {
        logger.debug("No file found for uploading an excel file of metadata.");
    } catch (IOException e) {
        logger.error("Error opening file" + file.getOriginalFilename());
    }
    session.setAttribute("pm-" + projectId, storage);
    return storage;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) XSSFWorkbook(org.apache.poi.xssf.usermodel.XSSFWorkbook) Workbook(org.apache.poi.ss.usermodel.Workbook) HSSFWorkbook(org.apache.poi.hssf.usermodel.HSSFWorkbook) HSSFWorkbook(org.apache.poi.hssf.usermodel.HSSFWorkbook) SampleMetadataStorage(ca.corefacility.bioinformatics.irida.ria.utilities.SampleMetadataStorage) MetadataImportFileTypeNotSupportedError(ca.corefacility.bioinformatics.irida.exceptions.MetadataImportFileTypeNotSupportedError) ByteArrayInputStream(java.io.ByteArrayInputStream) XSSFWorkbook(org.apache.poi.xssf.usermodel.XSSFWorkbook) Row(org.apache.poi.ss.usermodel.Row) Sheet(org.apache.poi.ss.usermodel.Sheet) ImmutableMap(com.google.common.collect.ImmutableMap) Cell(org.apache.poi.ss.usermodel.Cell)

Example 3 with SampleMetadataStorage

use of ca.corefacility.bioinformatics.irida.ria.utilities.SampleMetadataStorage in project irida by phac-nml.

the class ProjectSampleMetadataController method setProjectSampleMetadataSampleId.

/**
 * Add the metadata to specific {@link Sample} based on the selected column to correspond to the {@link Sample} id.
 *
 * @param session
 * 		{@link HttpSession}.
 * @param projectId
 * 		{@link Long} identifier for the current {@link Project}.
 * @param sampleNameColumn
 * 		{@link String} the header to used to represent the {@link Sample} identifier.
 *
 * @return {@link Map} containing
 */
@RequestMapping(value = "/upload/setSampleColumn", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> setProjectSampleMetadataSampleId(HttpSession session, @PathVariable long projectId, @RequestParam String sampleNameColumn) {
    // Attempt to get the metadata from the sessions
    SampleMetadataStorage stored = (SampleMetadataStorage) session.getAttribute("pm-" + projectId);
    if (stored != null) {
        stored.setSampleNameColumn(sampleNameColumn);
        Project project = projectService.read(projectId);
        List<Map<String, String>> rows = stored.getRows();
        // Remove 'rows' since they are now going to be sorted into found and not found.
        stored.removeRows();
        List<Map<String, String>> found = new ArrayList<>();
        List<Map<String, String>> missing = new ArrayList<>();
        // Get the metadata out of the table.
        for (Map<String, String> row : rows) {
            try {
                // If this throws an error than the sample does not exist.
                sampleService.getSampleBySampleName(project, row.get(sampleNameColumn));
                found.add(row);
            } catch (EntityNotFoundException e) {
                missing.add(row);
            }
        }
        stored.saveFound(found);
        stored.saveMissing(missing);
    }
    return ImmutableMap.of("result", "complete");
}
Also used : SampleMetadataStorage(ca.corefacility.bioinformatics.irida.ria.utilities.SampleMetadataStorage) Project(ca.corefacility.bioinformatics.irida.model.project.Project) EntityNotFoundException(ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException) ImmutableMap(com.google.common.collect.ImmutableMap)

Aggregations

SampleMetadataStorage (ca.corefacility.bioinformatics.irida.ria.utilities.SampleMetadataStorage)3 ImmutableMap (com.google.common.collect.ImmutableMap)3 EntityNotFoundException (ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException)2 Project (ca.corefacility.bioinformatics.irida.model.project.Project)2 MetadataImportFileTypeNotSupportedError (ca.corefacility.bioinformatics.irida.exceptions.MetadataImportFileTypeNotSupportedError)1 MetadataTemplateField (ca.corefacility.bioinformatics.irida.model.sample.MetadataTemplateField)1 Sample (ca.corefacility.bioinformatics.irida.model.sample.Sample)1 MetadataEntry (ca.corefacility.bioinformatics.irida.model.sample.metadata.MetadataEntry)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 FileNotFoundException (java.io.FileNotFoundException)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 HSSFWorkbook (org.apache.poi.hssf.usermodel.HSSFWorkbook)1 Cell (org.apache.poi.ss.usermodel.Cell)1 Row (org.apache.poi.ss.usermodel.Row)1 Sheet (org.apache.poi.ss.usermodel.Sheet)1 Workbook (org.apache.poi.ss.usermodel.Workbook)1 XSSFWorkbook (org.apache.poi.xssf.usermodel.XSSFWorkbook)1