Author: echatellier Date: 2012-07-17 11:06:44 +0200 (Tue, 17 Jul 2012) New Revision: 1016 Url: http://forge.codelutin.com/repositories/revision/coser/1016 Log: Refactor service to prevent infinite loop Added: trunk/coser-business/src/main/java/fr/ifremer/coser/services/CommonService.java trunk/coser-business/src/test/java/fr/ifremer/coser/services/CommonServiceTest.java Removed: trunk/coser-business/src/main/java/fr/ifremer/coser/services/ImportService.java trunk/coser-business/src/test/java/fr/ifremer/coser/services/ImportServiceTest.java Modified: trunk/coser-business/src/main/java/fr/ifremer/coser/services/ProjectService.java trunk/coser-business/src/main/java/fr/ifremer/coser/services/PublicationService.java trunk/coser-business/src/main/java/fr/ifremer/coser/services/WebService.java trunk/coser-ui/src/main/java/fr/ifremer/coser/Coser.java trunk/coser-ui/src/main/java/fr/ifremer/coser/ui/control/ControlHandler.java Copied: trunk/coser-business/src/main/java/fr/ifremer/coser/services/CommonService.java (from rev 1014, trunk/coser-business/src/main/java/fr/ifremer/coser/services/ImportService.java) =================================================================== --- trunk/coser-business/src/main/java/fr/ifremer/coser/services/CommonService.java (rev 0) +++ trunk/coser-business/src/main/java/fr/ifremer/coser/services/CommonService.java 2012-07-17 09:06:44 UTC (rev 1016) @@ -0,0 +1,532 @@ +/* + * #%L + * Coser :: Business + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2010 - 2012 Ifremer, Codelutin, Chatellier Eric + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ + +package fr.ifremer.coser.services; + +import static org.nuiton.i18n.I18n._; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.Reader; +import java.io.Writer; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.StringUtils; +import org.nuiton.util.ArrayUtil; + +import au.com.bytecode.opencsv.CSVReader; +import au.com.bytecode.opencsv.CSVWriter; +import fr.ifremer.coser.CoserBusinessConfig; +import fr.ifremer.coser.CoserBusinessException; +import fr.ifremer.coser.CoserConstants; +import fr.ifremer.coser.CoserUtils; +import fr.ifremer.coser.CoserConstants.Category; +import fr.ifremer.coser.bean.Project; +import fr.ifremer.coser.data.AbstractDataEntity; +import fr.ifremer.coser.data.Catch; +import fr.ifremer.coser.data.Haul; +import fr.ifremer.coser.data.Length; +import fr.ifremer.coser.data.Strata; +import fr.ifremer.coser.storage.DataStorage; +import fr.ifremer.coser.storage.MemoryDataStorage; +import fr.ifremer.coser.util.ProgressMonitor; +import fr.ifremer.coser.util.ProgressReader; + +/** + * Common methods used by others services only. + * + * <ul> + * <li>csv import/export</li> + * <li>file name management</li> + * <li>utilities methods</li> + * </ul> + * + * @author chatellier + * @version $Revision$ + * + * Last update : $Date$ + * By : $Author$ + */ +public class CommonService { + + protected CoserBusinessConfig config; + + CommonService(CoserBusinessConfig config) { + this.config = config; + } + + /** + * Load file as csv. Check and affect data in project depending on category type. + * + * @param project project + * @param category category + * @param file file to load + * @return data storage with file content + * @throws CoserBusinessException + */ + public DataStorage loadCSVFile(Project project, Category category, File file) throws CoserBusinessException { + return loadCSVFile(project, category, file, null); + } + + /** + * Load file as csv. Check and affect data in project depending on category type. + * + * @param project project + * @param category category + * @param file file to load + * @param progress progress monitor (can be null) + * @return data storage with file content + * @throws CoserBusinessException + */ + public DataStorage loadCSVFile(Project project, Category category, File file, ProgressMonitor progress) throws CoserBusinessException { + return loadCSVFile(project, category, file, null, false); + } + + /** + * Load file as csv. Check and affect data in project depending on category type. + * + * @param project project + * @param category category + * @param file file to load + * @param progress progress monitor (can be null) + * @param originalLoading dans le cas d'un reload, la colonne "line" est a prendre en compte + * pour les data (elle est absente dans les jeux de données originaux) + * @return data storage with file content + * @throws CoserBusinessException + */ + public DataStorage loadCSVFile(Project project, Category category, File file, ProgressMonitor progress, boolean originalLoading) throws CoserBusinessException { + + DataStorage content = new MemoryDataStorage(); + + CSVReader csvReader = null; + try { + + InputStream stream = new FileInputStream(file); + Reader reader = new BufferedReader(new InputStreamReader(stream, CoserConstants.CSV_FILE_ENCODING)); + if (progress != null) { + reader = new ProgressReader(reader, progress); + } + csvReader = new CSVReader(reader, CoserConstants.CSV_SEPARATOR_CHAR); + + // check header + String[] line = csvReader.readNext(); + if (line == null || line.length <= 1) { + throw new CoserBusinessException(_("Can't read file '%s'. Check CSV file separator", + file.getAbsolutePath())); + } + else { + if (originalLoading) { + checkFileHeader(file, category, line); + if (category.isDataCategory()) { + line = (String[])ArrayUtil.concat(new String[]{AbstractDataEntity.PROPERTY_LINE}, line); + } + } + content.add(line); + } + + // pour alimenter la line index (si non reloading) + // dans coser, la numérotation des lignes commence à 1 + int lineIndex = 1; + while ((line = csvReader.readNext()) != null) { + if (line.length>1) { + if (originalLoading && category.isDataCategory()) { + // ajout de la colonne "line" en debut (seulement pour les data) + line = (String[])ArrayUtil.concat(new String[]{String.valueOf(lineIndex)}, line); + lineIndex++; + } + content.add(line); + } + } + } catch (IOException ex) { + throw new CoserBusinessException("Can't read file", ex); + } + finally { + IOUtils.closeQuietly(csvReader); + } + + return content; + } + + /** + * Check csv file header names and order depending on file category. + * + * @param file file + * @param category category + * @param line header line to ckeck + * @throws CoserBusinessException + */ + protected void checkFileHeader(File file, Category category, String[] line) throws CoserBusinessException { + + String[] enHeaders = null; + String[] frHeaders = null; + + switch (category) { + case CATCH: + enHeaders = Catch.EN_HEADERS; + frHeaders = Catch.FR_HEADERS; + break; + case HAUL: + enHeaders = Haul.EN_HEADERS; + frHeaders = Haul.FR_HEADERS; + break; + case LENGTH: + enHeaders = Length.EN_HEADERS; + frHeaders = Length.FR_HEADERS; + break; + case STRATA: + enHeaders = Strata.EN_HEADERS; + frHeaders = Strata.FR_HEADERS; + break; + case REFTAX_SPECIES: + enHeaders = Project.REFTAX_SPECIES_HEADER; + break; + case TYPE_ESPECES: + enHeaders = Project.TYPE_ESPECE_HEADER; + break; + } + + if (frHeaders != null) { + if (!Arrays.equals(line, enHeaders) && !Arrays.equals(line, frHeaders)) { + throw new CoserBusinessException(_("Wrong header detected in file %s. Found : %s, expected %s or %s", + file.getName(), + StringUtils.join(line, ", "), + StringUtils.join(frHeaders, ", "), + StringUtils.join(enHeaders, ", "))); + } + } + else { + if (!Arrays.equals(line, enHeaders)) { + throw new CoserBusinessException(_("Wrong header detected in file %s. Found : %s, expected %s", + file.getName(), + StringUtils.join(line, ", "), + StringUtils.join(enHeaders, ", "))); + } + } + } + + /** + * Get empty storage for category (filled with just header) + * + * @param project project + * @param category category + * @return initialized storage + */ + public DataStorage getEmptyStorage(Project project, Category category) { + + DataStorage dataStorage = new MemoryDataStorage(); + switch (category) { + case CATCH: + dataStorage.add(Catch.EN_HEADERS); + break; + case HAUL: + dataStorage.add(Haul.EN_HEADERS); + break; + case LENGTH: + dataStorage.add(Length.EN_HEADERS); + break; + case STRATA: + dataStorage.add(Strata.EN_HEADERS); + break; + } + + return dataStorage; + } + + /** + * Store project category data in specified file as csv. + * + * @param content content to save + * @param file file to save to + * @throws CoserBusinessException + */ + public void storeData(DataStorage content, File file) throws CoserBusinessException { + + // save content + CSVWriter csvWriter = null; + try { + Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), CoserConstants.CSV_FILE_ENCODING)); + + csvWriter = new CSVWriter(writer, CoserConstants.CSV_SEPARATOR_CHAR); + Iterator<String[]> itContent = content.iterator(); + while (itContent.hasNext()) { + csvWriter.writeNext(itContent.next()); + } + } catch (IOException ex) { + throw new CoserBusinessException("Can't save data", ex); + } + finally { + IOUtils.closeQuietly(csvWriter); + } + } + + /** + * Store data without quoting every columns with "" (r specific demand). + * + * @param content content to save + * @param file file to save to + * + * @throws CoserBusinessException + */ + public void storeDataWhithoutQuote(DataStorage content, File file) throws CoserBusinessException { + // save content + Writer writer = null; + try { + writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), CoserConstants.CSV_FILE_ENCODING)); + + Iterator<String[]> itContent = content.iterator(); + while (itContent.hasNext()) { + String[] contentDatas = itContent.next(); + + // start at 1 to not output "line" column + for (int i = 1 ; i < contentDatas.length ; i++) { + + if (i != 1) { + writer.write(CoserConstants.CSV_SEPARATOR_CHAR); + } + + String contentData = contentDatas[i]; + if (contentData.indexOf(CoserConstants.CSV_SEPARATOR_CHAR) > -1) { + writer.write("\"" + contentData + "\""); + } + else { + writer.write(contentData); + } + } + writer.write("\n"); + } + } catch (IOException ex) { + throw new CoserBusinessException("Can't save data", ex); + } + finally { + IOUtils.closeQuietly(writer); + } + } + + /** + * Lit le fichier demandé et sauve dans une map les lignes demandées. + * + * @param file file to read + * @param lines lines to save content + * @return saved content + * @throws CoserBusinessException + */ + public Map<String, String[]> getOriginalFileContent(File file, Collection<String> lines) throws CoserBusinessException { + Map<String, String[]> content = new HashMap<String, String[]>(); + + CSVReader csvReader = null; + try { + + Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), CoserConstants.CSV_FILE_ENCODING)); + csvReader = new CSVReader(reader, CoserConstants.CSV_SEPARATOR_CHAR); + + // skip header + String[] line = csvReader.readNext(); + + // pour alimenter la line index (si non reloading) + // dans coser, la numérotation des lignes commence à 1 + int lineIndex = 1; + while ((line = csvReader.readNext()) != null) { + String stringLine = String.valueOf(lineIndex); + if (lines.contains(stringLine)) { + content.put(stringLine, line); + } + lineIndex++; + } + } + catch (IOException ex) { + throw new CoserBusinessException("Can't read file", ex); + } + finally { + IOUtils.closeQuietly(csvReader); + } + + return content; + } + + /** + * Charge un fichier csv (estcomind/estpopind ...) mais sans verification. + * C'est a peu pret le meme code qu'au dessus, sauf que le storage est + * simplement retourné et que les séparateurs ne sont pas les même. + * + * @param file file to load + * @return data storage with file content + * @throws CoserBusinessException + */ + public DataStorage loadCSVFile(File file) throws CoserBusinessException { + return loadCSVFile(file, CoserConstants.CSV_SEPARATOR_CHAR); + } + + /** + * Charge un fichier csv (estcomind/estpopind ...) mais sans verification. + * C'est a peu pret le meme code qu'au dessus, sauf que le storage est + * simplement retourné et que les séparateurs ne sont pas les même. + * + * @param file file to load + * @param separator separator to use to load file + * @return data storage with file content + * @throws CoserBusinessException + */ + public DataStorage loadCSVFile(File file, char separator) throws CoserBusinessException { + + DataStorage content = new MemoryDataStorage(); + + CSVReader csvReader = null; + try { + + InputStream stream = new FileInputStream(file); + Reader reader = new BufferedReader(new InputStreamReader(stream, CoserConstants.CSV_FILE_ENCODING)); + csvReader = new CSVReader(reader, separator); + + // check header + String[] line = csvReader.readNext(); + if (line == null || line.length <= 1) { + throw new CoserBusinessException(_("Can't read file '%s'. Check CSV file separator", + file.getAbsolutePath())); + } + else { + content.add(line); + } + + while ((line = csvReader.readNext()) != null) { + if (line.length>1) { + content.add(line); + } + } + } catch (IOException ex) { + throw new CoserBusinessException("Can't read file", ex); + } + finally { + IOUtils.closeQuietly(csvReader); + } + + return content; + } + + /** + * Retourne le nom de stockage d'un fichier de données suivant la categories + * de fichier demandé. Les fichiers sont stockés avec leurs noms originaux + * (sauf les fichiers de réference) donc il n'est pas fixe. + * + * @param project project (containing originals file names) + * @param category category to get file name + * @param suffix suffix to add into file name + * @return storage file name + */ + protected String getDataStorageFileName(Project project, Category category, String suffix) { + + String result = null; + + switch (category) { + case CATCH: + result = project.getCatchFileName(); + break; + case HAUL: + result = project.getHaulFileName(); + break; + case LENGTH: + result = project.getLengthFileName(); + break; + case STRATA: + result = project.getStrataFileName(); + break; + } + + if (suffix != null) { + result = CoserUtils.addSuffixBeforeExtension(result, suffix); + } + + return result; + } + + /** + * Lit tout le fichier associé à la categorie demandé, mais ne retourne + * que les données correspondant au numéro de lignes demandée. + * + * Le contenu retourné ne contient pas le numéro de ligne. + * + * @param project project + * @param category category + * @param lines lines to get content + * @return content for lines + * @throws CoserBusinessException + */ + public Map<String, String[]> getOriginalContent(Project project, Category category, Collection<String> lines) throws CoserBusinessException { + + // ne lit pas un fichier entier pour ne rien chercher + if (CollectionUtils.isEmpty(lines)) { + return new HashMap<String, String[]>(); + } + + File projectsDirectory = config.getProjectsDirectory(); + File projectDirectory = new File(projectsDirectory, project.getName()); + File originalDirectory = new File(projectDirectory, CoserConstants.STORAGE_ORIGINAL_DIRECTORY); + String storageFileName = getDataStorageFileName(project, category, null); + File dataFile = new File(originalDirectory, storageFileName); + + Map<String, String[]> contents = getOriginalFileContent(dataFile, lines); + + return contents; + } + + /** + * Retourne le nom d'affichage d'une especes. + * + * @param project project + * @param species species code + * @return species display name + */ + public String getSpeciesDisplayName(Project project, String species) { + String displayName = null; + + // load reftax in memory + Iterator<String[]> reftax = project.getRefTaxSpecies().iterator(true); + while (reftax.hasNext()) { + String[] tuple = reftax.next(); + + // "C_Perm","NumSys","NivSys","C_VALIDE","L_VALIDE","AA_VALIDE","C_TxP\u00E8re","Taxa" + String speciesCode = tuple[3]; + if (speciesCode.equals(species)) { + // nom + auteur (sans ajout de parenthese : important) + displayName = tuple[4] + " " + tuple[5]; + break; + } + } + + return displayName; + } +} Deleted: trunk/coser-business/src/main/java/fr/ifremer/coser/services/ImportService.java =================================================================== --- trunk/coser-business/src/main/java/fr/ifremer/coser/services/ImportService.java 2012-07-17 07:09:32 UTC (rev 1015) +++ trunk/coser-business/src/main/java/fr/ifremer/coser/services/ImportService.java 2012-07-17 09:06:44 UTC (rev 1016) @@ -1,431 +0,0 @@ -/* - * #%L - * Coser :: Business - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2010 Ifremer, Codelutin, Chatellier Eric - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package fr.ifremer.coser.services; - -import static org.nuiton.i18n.I18n._; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.Reader; -import java.io.Writer; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.StringUtils; -import org.nuiton.util.ArrayUtil; - -import au.com.bytecode.opencsv.CSVReader; -import au.com.bytecode.opencsv.CSVWriter; -import fr.ifremer.coser.CoserBusinessConfig; -import fr.ifremer.coser.CoserBusinessException; -import fr.ifremer.coser.CoserConstants; -import fr.ifremer.coser.CoserConstants.Category; -import fr.ifremer.coser.bean.Project; -import fr.ifremer.coser.data.AbstractDataEntity; -import fr.ifremer.coser.data.Catch; -import fr.ifremer.coser.data.Haul; -import fr.ifremer.coser.data.Length; -import fr.ifremer.coser.data.Strata; -import fr.ifremer.coser.storage.DataStorage; -import fr.ifremer.coser.storage.MemoryDataStorage; -import fr.ifremer.coser.util.ProgressMonitor; -import fr.ifremer.coser.util.ProgressReader; - -/** - * File import/export service. - * - * @author chatellier - * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ - */ -public class ImportService { - - protected CoserBusinessConfig config; - - public ImportService(CoserBusinessConfig config) { - this.config = config; - } - - /** - * Load file as csv. Check and affect data in project depending on category type. - * - * @param project project - * @param category category - * @param file file to load - * @return data storage with file content - * @throws CoserBusinessException - */ - public DataStorage loadCSVFile(Project project, Category category, File file) throws CoserBusinessException { - return loadCSVFile(project, category, file, null); - } - - /** - * Load file as csv. Check and affect data in project depending on category type. - * - * @param project project - * @param category category - * @param file file to load - * @param progress progress monitor (can be null) - * @return data storage with file content - * @throws CoserBusinessException - */ - public DataStorage loadCSVFile(Project project, Category category, File file, ProgressMonitor progress) throws CoserBusinessException { - return loadCSVFile(project, category, file, null, false); - } - - /** - * Load file as csv. Check and affect data in project depending on category type. - * - * @param project project - * @param category category - * @param file file to load - * @param progress progress monitor (can be null) - * @param originalLoading dans le cas d'un reload, la colonne "line" est a prendre en compte - * pour les data (elle est absente dans les jeux de données originaux) - * @return data storage with file content - * @throws CoserBusinessException - */ - public DataStorage loadCSVFile(Project project, Category category, File file, ProgressMonitor progress, boolean originalLoading) throws CoserBusinessException { - - DataStorage content = new MemoryDataStorage(); - - CSVReader csvReader = null; - try { - - InputStream stream = new FileInputStream(file); - Reader reader = new BufferedReader(new InputStreamReader(stream, CoserConstants.CSV_FILE_ENCODING)); - if (progress != null) { - reader = new ProgressReader(reader, progress); - } - csvReader = new CSVReader(reader, CoserConstants.CSV_SEPARATOR_CHAR); - - // check header - String[] line = csvReader.readNext(); - if (line == null || line.length <= 1) { - throw new CoserBusinessException(_("Can't read file '%s'. Check CSV file separator", - file.getAbsolutePath())); - } - else { - if (originalLoading) { - checkFileHeader(file, category, line); - if (category.isDataCategory()) { - line = (String[])ArrayUtil.concat(new String[]{AbstractDataEntity.PROPERTY_LINE}, line); - } - } - content.add(line); - } - - // pour alimenter la line index (si non reloading) - // dans coser, la numérotation des lignes commence à 1 - int lineIndex = 1; - while ((line = csvReader.readNext()) != null) { - if (line.length>1) { - if (originalLoading && category.isDataCategory()) { - // ajout de la colonne "line" en debut (seulement pour les data) - line = (String[])ArrayUtil.concat(new String[]{String.valueOf(lineIndex)}, line); - lineIndex++; - } - content.add(line); - } - } - } catch (IOException ex) { - throw new CoserBusinessException("Can't read file", ex); - } - finally { - IOUtils.closeQuietly(csvReader); - } - - return content; - } - - /** - * Check csv file header names and order depending on file category. - * - * @param file file - * @param category category - * @param line header line to ckeck - * @throws CoserBusinessException - */ - protected void checkFileHeader(File file, Category category, String[] line) throws CoserBusinessException { - - String[] enHeaders = null; - String[] frHeaders = null; - - switch (category) { - case CATCH: - enHeaders = Catch.EN_HEADERS; - frHeaders = Catch.FR_HEADERS; - break; - case HAUL: - enHeaders = Haul.EN_HEADERS; - frHeaders = Haul.FR_HEADERS; - break; - case LENGTH: - enHeaders = Length.EN_HEADERS; - frHeaders = Length.FR_HEADERS; - break; - case STRATA: - enHeaders = Strata.EN_HEADERS; - frHeaders = Strata.FR_HEADERS; - break; - case REFTAX_SPECIES: - enHeaders = Project.REFTAX_SPECIES_HEADER; - break; - case TYPE_ESPECES: - enHeaders = Project.TYPE_ESPECE_HEADER; - break; - } - - if (frHeaders != null) { - if (!Arrays.equals(line, enHeaders) && !Arrays.equals(line, frHeaders)) { - throw new CoserBusinessException(_("Wrong header detected in file %s. Found : %s, expected %s or %s", - file.getName(), - StringUtils.join(line, ", "), - StringUtils.join(frHeaders, ", "), - StringUtils.join(enHeaders, ", "))); - } - } - else { - if (!Arrays.equals(line, enHeaders)) { - throw new CoserBusinessException(_("Wrong header detected in file %s. Found : %s, expected %s", - file.getName(), - StringUtils.join(line, ", "), - StringUtils.join(enHeaders, ", "))); - } - } - } - - /** - * Get empty storage for category (filled with just header) - * - * @param project project - * @param category category - * @return initialized storage - */ - public DataStorage getEmptyStorage(Project project, Category category) { - - DataStorage dataStorage = new MemoryDataStorage(); - switch (category) { - case CATCH: - dataStorage.add(Catch.EN_HEADERS); - break; - case HAUL: - dataStorage.add(Haul.EN_HEADERS); - break; - case LENGTH: - dataStorage.add(Length.EN_HEADERS); - break; - case STRATA: - dataStorage.add(Strata.EN_HEADERS); - break; - } - - return dataStorage; - } - - /** - * Store project category data in specified file as csv. - * - * @param content content to save - * @param file file to save to - * @throws CoserBusinessException - */ - public void storeData(DataStorage content, File file) throws CoserBusinessException { - - // save content - CSVWriter csvWriter = null; - try { - Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), CoserConstants.CSV_FILE_ENCODING)); - - csvWriter = new CSVWriter(writer, CoserConstants.CSV_SEPARATOR_CHAR); - Iterator<String[]> itContent = content.iterator(); - while (itContent.hasNext()) { - csvWriter.writeNext(itContent.next()); - } - } catch (IOException ex) { - throw new CoserBusinessException("Can't save data", ex); - } - finally { - IOUtils.closeQuietly(csvWriter); - } - } - - /** - * Store data without quoting every columns with "" (r specific demand). - * - * @param content content to save - * @param file file to save to - * - * @throws CoserBusinessException - */ - public void storeDataWhithoutQuote(DataStorage content, File file) throws CoserBusinessException { - // save content - Writer writer = null; - try { - writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), CoserConstants.CSV_FILE_ENCODING)); - - Iterator<String[]> itContent = content.iterator(); - while (itContent.hasNext()) { - String[] contentDatas = itContent.next(); - - // start at 1 to not output "line" column - for (int i = 1 ; i < contentDatas.length ; i++) { - - if (i != 1) { - writer.write(CoserConstants.CSV_SEPARATOR_CHAR); - } - - String contentData = contentDatas[i]; - if (contentData.indexOf(CoserConstants.CSV_SEPARATOR_CHAR) > -1) { - writer.write("\"" + contentData + "\""); - } - else { - writer.write(contentData); - } - } - writer.write("\n"); - } - } catch (IOException ex) { - throw new CoserBusinessException("Can't save data", ex); - } - finally { - IOUtils.closeQuietly(writer); - } - } - - /** - * Lit le fichier demandé et sauve dans une map les lignes demandées. - * - * @param file file to read - * @param lines lines to save content - * @return saved content - * @throws CoserBusinessException - */ - public Map<String, String[]> getOriginalFileContent(File file, Collection<String> lines) throws CoserBusinessException { - Map<String, String[]> content = new HashMap<String, String[]>(); - - CSVReader csvReader = null; - try { - - Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), CoserConstants.CSV_FILE_ENCODING)); - csvReader = new CSVReader(reader, CoserConstants.CSV_SEPARATOR_CHAR); - - // skip header - String[] line = csvReader.readNext(); - - // pour alimenter la line index (si non reloading) - // dans coser, la numérotation des lignes commence à 1 - int lineIndex = 1; - while ((line = csvReader.readNext()) != null) { - String stringLine = String.valueOf(lineIndex); - if (lines.contains(stringLine)) { - content.put(stringLine, line); - } - lineIndex++; - } - } - catch (IOException ex) { - throw new CoserBusinessException("Can't read file", ex); - } - finally { - IOUtils.closeQuietly(csvReader); - } - - return content; - } - - /** - * Charge un fichier csv (estcomind/estpopind ...) mais sans verification. - * C'est a peu pret le meme code qu'au dessus, sauf que le storage est - * simplement retourné et que les séparateurs ne sont pas les même. - * - * @param file file to load - * @return data storage with file content - * @throws CoserBusinessException - */ - public DataStorage loadCSVFile(File file) throws CoserBusinessException { - return loadCSVFile(file, CoserConstants.CSV_SEPARATOR_CHAR); - } - - /** - * Charge un fichier csv (estcomind/estpopind ...) mais sans verification. - * C'est a peu pret le meme code qu'au dessus, sauf que le storage est - * simplement retourné et que les séparateurs ne sont pas les même. - * - * @param file file to load - * @param separator separator to use to load file - * @return data storage with file content - * @throws CoserBusinessException - */ - public DataStorage loadCSVFile(File file, char separator) throws CoserBusinessException { - - DataStorage content = new MemoryDataStorage(); - - CSVReader csvReader = null; - try { - - InputStream stream = new FileInputStream(file); - Reader reader = new BufferedReader(new InputStreamReader(stream, CoserConstants.CSV_FILE_ENCODING)); - csvReader = new CSVReader(reader, separator); - - // check header - String[] line = csvReader.readNext(); - if (line == null || line.length <= 1) { - throw new CoserBusinessException(_("Can't read file '%s'. Check CSV file separator", - file.getAbsolutePath())); - } - else { - content.add(line); - } - - while ((line = csvReader.readNext()) != null) { - if (line.length>1) { - content.add(line); - } - } - } catch (IOException ex) { - throw new CoserBusinessException("Can't read file", ex); - } - finally { - IOUtils.closeQuietly(csvReader); - } - - return content; - } -} Modified: trunk/coser-business/src/main/java/fr/ifremer/coser/services/ProjectService.java =================================================================== --- trunk/coser-business/src/main/java/fr/ifremer/coser/services/ProjectService.java 2012-07-17 07:09:32 UTC (rev 1015) +++ trunk/coser-business/src/main/java/fr/ifremer/coser/services/ProjectService.java 2012-07-17 09:06:44 UTC (rev 1016) @@ -112,14 +112,17 @@ protected CoserBusinessConfig config; - protected ImportService importService; + protected CommonService commonService; protected CommandService commandService; + protected PublicationService publicationService; + public ProjectService(CoserBusinessConfig config) { this.config = config; - importService = new ImportService(config); + commonService = new CommonService(config); commandService = new CommandService(config); + publicationService = new PublicationService(config); } /** @@ -203,13 +206,13 @@ throw new CoserBusinessException(_("Can't read file %s for category %s", dataFile.getAbsolutePath(), _(category.getTranslationKey()))); } - DataStorage dataStorage = importService.loadCSVFile(project, category, dataFile, progress, true); + DataStorage dataStorage = commonService.loadCSVFile(project, category, dataFile, progress, true); addProjectContent(project, control, category, dataStorage, false); // init empty deleted collection if (category.isDataCategory()) { // deleted data - DataStorage dataStorage2 = importService.getEmptyStorage(project, category); + DataStorage dataStorage2 = commonService.getEmptyStorage(project, category); addProjectContent(project, control, category, dataStorage2, true); } } @@ -228,7 +231,7 @@ // les fichiers de donnees sont stockes dans un repertoire // "original" if (category.isDataCategory()) { - String storageFileName = getDataStorageFileName(project, category, null); + String storageFileName = commonService.getDataStorageFileName(project, category, null); File storageDataFile = new File(originalDirectory, storageFileName); FileUtils.copyFile(dataFile, storageDataFile); } @@ -300,7 +303,7 @@ /** * Update project maps with new maps. * - * Thériquement, si les deux listes sont identiques, cette methode ne fait rien. + * Théoriquement, si les deux listes sont identiques, cette methode ne fait rien. * * @param project project to update maps * @param projectDirectory project directory @@ -355,42 +358,6 @@ } /** - * Retourne le nom de stockage d'un fichier de données suivant la categories - * de fichier demandé. Les fichiers sont stockés avec leurs noms originaux - * (sauf les fichiers de réference) donc il n'est pas fixe. - * - * @param project project (containing originals file names) - * @param category category to get file name - * @param suffix suffix to add into file name - * @return storage file name - */ - protected String getDataStorageFileName(Project project, Category category, String suffix) { - - String result = null; - - switch (category) { - case CATCH: - result = project.getCatchFileName(); - break; - case HAUL: - result = project.getHaulFileName(); - break; - case LENGTH: - result = project.getLengthFileName(); - break; - case STRATA: - result = project.getStrataFileName(); - break; - } - - if (suffix != null) { - result = CoserUtils.addSuffixBeforeExtension(result, suffix); - } - - return result; - } - - /** * Open project without loading data. * * Just load non category data (reftax). @@ -433,7 +400,7 @@ category.getStorageFileName()); if (inputFile.isFile()) { - DataStorage dataStorage = importService.loadCSVFile(project, category, inputFile); + DataStorage dataStorage = commonService.loadCSVFile(project, category, inputFile); addProjectContent(project, null, category, dataStorage, false); } else { @@ -625,11 +592,11 @@ // seulement les category de données ici if (category.isDataCategory()) { - String storageFileName = getDataStorageFileName(project, category, CoserConstants.STORAGE_CONTROL_SUFFIX); + String storageFileName = commonService.getDataStorageFileName(project, category, CoserConstants.STORAGE_CONTROL_SUFFIX); File inputFile = new File(controlDirectory, storageFileName); if (inputFile.isFile()) { - DataStorage dataStorage = importService.loadCSVFile(project, category, inputFile); + DataStorage dataStorage = commonService.loadCSVFile(project, category, inputFile); addProjectContent(project, control, category, dataStorage, false); fileLoaded++; } @@ -640,14 +607,14 @@ } // load deleted file if exists - storageFileName = getDataStorageFileName(project, category, CoserConstants.STORAGE_DELECTED_SUFFIX); + storageFileName = commonService.getDataStorageFileName(project, category, CoserConstants.STORAGE_DELECTED_SUFFIX); inputFile = new File(controlDirectory, storageFileName); DataStorage dataStorage = null; if (inputFile.isFile()) { - dataStorage = importService.loadCSVFile(project, category, inputFile); + dataStorage = commonService.loadCSVFile(project, category, inputFile); } else { - dataStorage = importService.getEmptyStorage(project, category); + dataStorage = commonService.getEmptyStorage(project, category); if (log.isDebugEnabled()) { log.debug("Can't find file " + inputFile); } @@ -662,12 +629,12 @@ for (Category category : Category.values()) { if (category.isDataCategory()) { - String storageFileName = getDataStorageFileName(project, category, null); + String storageFileName = commonService.getDataStorageFileName(project, category, null); File storageDataFile = new File(originalDirectory, storageFileName); // main data if (storageDataFile.isFile()) { - DataStorage dataStorage = importService.loadCSVFile(project, category, storageDataFile, null, true); + DataStorage dataStorage = commonService.loadCSVFile(project, category, storageDataFile, null, true); addProjectContent(project, control, category, dataStorage, false); } else { @@ -677,7 +644,7 @@ } // deleted data - DataStorage dataStorage = importService.getEmptyStorage(project, category); + DataStorage dataStorage = commonService.getEmptyStorage(project, category); addProjectContent(project, control, category, dataStorage, true); } } @@ -750,11 +717,11 @@ // seulement les category de données ici if (category.isDataCategory()) { - String storageFileName = getDataStorageFileName(project, category, CoserConstants.STORAGE_SELECTION_SUFFIX); + String storageFileName = commonService.getDataStorageFileName(project, category, CoserConstants.STORAGE_SELECTION_SUFFIX); File inputFile = new File(selectionDirectory, storageFileName); if (inputFile.isFile()) { - DataStorage dataStorage = importService.loadCSVFile(project, category, inputFile); + DataStorage dataStorage = commonService.loadCSVFile(project, category, inputFile); addProjectContent(project, selection, category, dataStorage, false); } else { @@ -810,21 +777,21 @@ if (category.isDataCategory()) { // save main content - String storageFileName = getDataStorageFileName(project, category, CoserConstants.STORAGE_CONTROL_SUFFIX); + String storageFileName = commonService.getDataStorageFileName(project, category, CoserConstants.STORAGE_CONTROL_SUFFIX); File controlFile = new File(controlDirectory, storageFileName); if (log.isDebugEnabled()) { log.debug("Saving control file : " + controlFile); } DataStorage content = getProjectContent(project, control, category, false); - importService.storeData(content, controlFile); + commonService.storeData(content, controlFile); // save deleted content (if needed) DataStorage contentDeleted = getProjectContent(project, control, category, true); // if more content than header if (contentDeleted.size() > 1) { - String deletedFileName = getDataStorageFileName(project, category, CoserConstants.STORAGE_DELECTED_SUFFIX); + String deletedFileName = commonService.getDataStorageFileName(project, category, CoserConstants.STORAGE_DELECTED_SUFFIX); File deletedDataFile = new File(controlDirectory, deletedFileName); - importService.storeData(contentDeleted, deletedDataFile); + commonService.storeData(contentDeleted, deletedDataFile); } } } @@ -851,7 +818,21 @@ } } + + /** + * Marque le controle comme valider et sauve le projet. + * + * Genère également les PDF des rapports de contrôle. + * + * @param project project to save + * @throws CoserBusinessException + */ + public void validControl(Project project) throws CoserBusinessException { + + project.getControl().setValidated(true); + } + /** * Creer une instance de selection "non sauvegardee" avec les données * de control (validée) du projet. @@ -1006,14 +987,14 @@ for (Category category : Category.values()) { if (category.isDataCategory()) { - String storageFileName = getDataStorageFileName(project, category, CoserConstants.STORAGE_SELECTION_SUFFIX); + String storageFileName = commonService.getDataStorageFileName(project, category, CoserConstants.STORAGE_SELECTION_SUFFIX); File dataFile = new File(selectionDirectory, storageFileName); if (log.isDebugEnabled()) { log.debug("Saving selection file : " + dataFile); } DataStorage content = getProjectContent(project, selection, category, false); - importService.storeData(content, dataFile); + commonService.storeData(content, dataFile); // delete data are not saved here // can't delete data in selection @@ -2070,33 +2051,6 @@ } /** - * Retourne le nom d'affichage d'une especes. - * - * @param project project - * @param species species code - * @return species display name - */ - public String getSpeciesDisplayName(Project project, String species) { - String displayName = null; - - // load reftax in memory - Iterator<String[]> reftax = project.getRefTaxSpecies().iterator(true); - while (reftax.hasNext()) { - String[] tuple = reftax.next(); - - // "C_Perm","NumSys","NivSys","C_VALIDE","L_VALIDE","AA_VALIDE","C_TxP\u00E8re","Taxa" - String speciesCode = tuple[3]; - if (speciesCode.equals(species)) { - // nom + auteur (sans ajout de parenthese : important) - displayName = tuple[4] + " " + tuple[5]; - break; - } - } - - return displayName; - } - - /** * Fusion d'especes. * * Used un selection ui. @@ -2753,14 +2707,14 @@ for (Category category : Category.values()) { if (category.isDataCategory()) { // originals names without suffix - String storageFileName = getDataStorageFileName(project, category, null); + String storageFileName = commonService.getDataStorageFileName(project, category, null); File dataFile = new File(projectDirectory, storageFileName); if (log.isDebugEnabled()) { log.debug("Saving selection file : " + dataFile); } DataStorage content = getProjectContent(project, selection, category, false); - importService.storeDataWhithoutQuote(content, dataFile); + commonService.storeDataWhithoutQuote(content, dataFile); } } @@ -2834,37 +2788,6 @@ } /** - * Lit tout le fichier associé à la categorie demandé, mais ne retourne - * que les données correspondant au numéro de lignes demandée. - * - * Le contenu retourné ne contient pas le numéro de ligne. - * - * @param project project - * @param category category - * @param lines lines to get content - * @return content for lines - * @throws CoserBusinessException - */ - public Map<String, String[]> getOriginalContent(Project project, Category category, Collection<String> lines) throws CoserBusinessException { - Map<String, String[]> contents = null; - - // ne lit pas un fichier entier pour ne rien chercher - if (CollectionUtils.isEmpty(lines)) { - return new HashMap<String, String[]>(); - } - - File projectsDirectory = config.getProjectsDirectory(); - File projectDirectory = new File(projectsDirectory, project.getName()); - File originalDirectory = new File(projectDirectory, CoserConstants.STORAGE_ORIGINAL_DIRECTORY); - String storageFileName = getDataStorageFileName(project, category, null); - File dataFile = new File(originalDirectory, storageFileName); - - contents = importService.getOriginalFileContent(dataFile, lines); - - return contents; - } - - /** * Look for project survey name in rsufi result. * Read estcomind file to known that. * Used in webservice to know map file names. @@ -2880,7 +2803,7 @@ // le fichier estcomind est moins gros que l'autre String estComIndName = rSufiResult.getEstComIndName(); File estComIndFile = new File(resultDirectory, estComIndName); - DataStorage dataStorage = importService.loadCSVFile(estComIndFile, CoserConstants.CSV_RESULT_SEPARATOR_CHAR); + DataStorage dataStorage = commonService.loadCSVFile(estComIndFile, CoserConstants.CSV_RESULT_SEPARATOR_CHAR); // Campagne Indicateur Liste Strate Annee Estimation EcartType CV Iterator<String[]> itEstComIndData = dataStorage.iterator(true); while (StringUtils.isEmpty(result) && itEstComIndData.hasNext()) { Modified: trunk/coser-business/src/main/java/fr/ifremer/coser/services/PublicationService.java =================================================================== --- trunk/coser-business/src/main/java/fr/ifremer/coser/services/PublicationService.java 2012-07-17 07:09:32 UTC (rev 1015) +++ trunk/coser-business/src/main/java/fr/ifremer/coser/services/PublicationService.java 2012-07-17 09:06:44 UTC (rev 1016) @@ -102,14 +102,11 @@ protected CoserBusinessConfig config; - protected ProjectService projectService; + protected CommonService commonService; - protected ImportService importService; - public PublicationService(CoserBusinessConfig config) { this.config = config; - projectService = new ProjectService(config); - importService = new ImportService(config); + commonService = new CommonService(config); } /** @@ -554,10 +551,10 @@ out.println("<ul>"); out.println("<li>" + _("coser.business.publication.creationdate") + " : " + dateFormat.format(project.getCreationDate())); out.println("<li>" + _("coser.business.publication.author") + " : " + project.getAuthor() + "</li>"); - out.println("<li>" + _("coser.business.publication.catchfilename") + " : " + projectService.getDataStorageFileName(project, Category.CATCH, null) + "</li>"); - out.println("<li>" + _("coser.business.publication.lengthfilename") + " : " + projectService.getDataStorageFileName(project, Category.LENGTH, null) + "</li>"); - out.println("<li>" + _("coser.business.publication.haulfilename") + " : " + projectService.getDataStorageFileName(project, Category.HAUL, null) + "</li>"); - out.println("<li>" + _("coser.business.publication.stratafilename") + " : " + projectService.getDataStorageFileName(project, Category.STRATA, null) + "</li>"); + out.println("<li>" + _("coser.business.publication.catchfilename") + " : " + commonService.getDataStorageFileName(project, Category.CATCH, null) + "</li>"); + out.println("<li>" + _("coser.business.publication.lengthfilename") + " : " + commonService.getDataStorageFileName(project, Category.LENGTH, null) + "</li>"); + out.println("<li>" + _("coser.business.publication.haulfilename") + " : " + commonService.getDataStorageFileName(project, Category.HAUL, null) + "</li>"); + out.println("<li>" + _("coser.business.publication.stratafilename") + " : " + commonService.getDataStorageFileName(project, Category.STRATA, null) + "</li>"); if (StringUtils.isNotEmpty(project.getComment())) { out.println("<li>" + _("coser.business.publication.comment") + " : " + project.getComment() + "</li>"); } @@ -608,10 +605,10 @@ } // second get content for lines - Map<String, String[]> catchContent = projectService.getOriginalContent(project, Category.CATCH, catchLines); - Map<String, String[]> lengthContent = projectService.getOriginalContent(project, Category.LENGTH, lengthLines); - Map<String, String[]> haulContent = projectService.getOriginalContent(project, Category.HAUL, haulLines); - Map<String, String[]> strataContent = projectService.getOriginalContent(project, Category.STRATA, strataLines); + Map<String, String[]> catchContent = commonService.getOriginalContent(project, Category.CATCH, catchLines); + Map<String, String[]> lengthContent = commonService.getOriginalContent(project, Category.LENGTH, lengthLines); + Map<String, String[]> haulContent = commonService.getOriginalContent(project, Category.HAUL, haulLines); + Map<String, String[]> strataContent = commonService.getOriginalContent(project, Category.STRATA, strataLines); // third, generate html report out.println("<h2>" + _("coser.business.publication.datamodification") + "</h2>"); @@ -677,7 +674,7 @@ File estComIndFile = new File(resultDirectory, rsufiResult.getEstComIndName()); // Campagne Indicateur Liste Strate Annee Estimation EcartType CV - DataStorage dataStorage = importService.loadCSVFile(estComIndFile, CoserConstants.CSV_RESULT_SEPARATOR_CHAR); + DataStorage dataStorage = commonService.loadCSVFile(estComIndFile, CoserConstants.CSV_RESULT_SEPARATOR_CHAR); // indicator list to take care // pour avoir une valeur non nulle si list est null @@ -734,7 +731,7 @@ // ajout de la traduction de la liste d'indicateur // les liste sont a1, T1, T2 ... String listLetter = String.valueOf(localList.charAt(0)); - DataStorage dataStorageType = importService.loadCSVFile(codeTypeEspecesFile, CoserConstants.CSV_SEPARATOR_CHAR); + DataStorage dataStorageType = commonService.loadCSVFile(codeTypeEspecesFile, CoserConstants.CSV_SEPARATOR_CHAR); Iterator<String[]> typeIterator = dataStorageType.iterator(true); while (typeIterator.hasNext()) { // "Types";"Commentaire";"NumSys min";"NumSys max";"Code" @@ -854,7 +851,7 @@ File estPopIndFile = new File(resultDirectory, rsufiResult.getEstPopIndName()); // Campagne Indicateur Liste Species Strate Annee Estimation EcartType CV - DataStorage dataStorage = importService.loadCSVFile(estPopIndFile, CoserConstants.CSV_RESULT_SEPARATOR_CHAR); + DataStorage dataStorage = commonService.loadCSVFile(estPopIndFile, CoserConstants.CSV_RESULT_SEPARATOR_CHAR); int multiplicator = 1; int minYear = Integer.MAX_VALUE; @@ -896,7 +893,7 @@ // get graph title String title = zoneDisplayName; title += " - " + indicatorName; - title += " - " + projectService.getSpeciesDisplayName(project, species); + title += " - " + commonService.getSpeciesDisplayName(project, species); // generate dataset with sorted data DefaultStatisticalCategoryDataset statisticalDataset = new DefaultStatisticalCategoryDataset(); @@ -988,7 +985,7 @@ File estComIndFile = new File(resultDirectory, rsufiResult.getEstComIndName()); // Campagne Indicateur Liste Strate Annee Estimation EcartType CV - DataStorage dataStorage = importService.loadCSVFile(estComIndFile, CoserConstants.CSV_RESULT_SEPARATOR_CHAR); + DataStorage dataStorage = commonService.loadCSVFile(estComIndFile, CoserConstants.CSV_RESULT_SEPARATOR_CHAR); DataStorage subDataStorage = new MemoryDataStorage(); Iterator<String[]> estComIndIterator = dataStorage.iterator(); // manage header @@ -1016,7 +1013,7 @@ } } - importService.storeDataWhithoutQuote(subDataStorage, result); + commonService.storeDataWhithoutQuote(subDataStorage, result); } catch (IOException ex) { throw new CoserBusinessException("Can't save csv file", ex); } @@ -1048,7 +1045,7 @@ File estPopIndFile = new File(resultDirectory, rsufiResult.getEstPopIndName()); // Campagne Indicateur Liste Species Strate Annee Estimation EcartType CV - DataStorage dataStorage = importService.loadCSVFile(estPopIndFile, CoserConstants.CSV_RESULT_SEPARATOR_CHAR); + DataStorage dataStorage = commonService.loadCSVFile(estPopIndFile, CoserConstants.CSV_RESULT_SEPARATOR_CHAR); DataStorage subDataStorage = new MemoryDataStorage(); Iterator<String[]> estPopIndIterator = dataStorage.iterator(); // manage header @@ -1082,7 +1079,7 @@ } } - importService.storeDataWhithoutQuote(subDataStorage, result); + commonService.storeDataWhithoutQuote(subDataStorage, result); } catch (IOException ex) { throw new CoserBusinessException("Can't save csv file", ex); } Modified: trunk/coser-business/src/main/java/fr/ifremer/coser/services/WebService.java =================================================================== --- trunk/coser-business/src/main/java/fr/ifremer/coser/services/WebService.java 2012-07-17 07:09:32 UTC (rev 1015) +++ trunk/coser-business/src/main/java/fr/ifremer/coser/services/WebService.java 2012-07-17 09:06:44 UTC (rev 1016) @@ -5,7 +5,7 @@ * $Id$ * $HeadURL$ * %% - * Copyright (C) 2010 - 2011 Ifremer, Codelutin, Chatellier Eric + * Copyright (C) 2010 - 2012 Ifremer, Codelutin, Chatellier Eric * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as @@ -101,15 +101,15 @@ /** * Service specifique à l'interface web de visualisation et à la partie UI - * qui sert a envouer les resultats vers l'interface web. + * qui sert a envoyer les resultats vers l'interface web. * * Ce service, contrairement aux autres a un état, les indicateurs et zones * chargées persistent après chargement, car elle ne peuvent pas changer * tant que l'application est en cours d'utilisation. * * Il faut garder à l'esprit que les projets n'ont pas forcement - * de resultat, donc le chargement du projet est possible, mais - * pas les données de controle et les données de selection (dont plutot + * de données publiées, donc le chargement du projet est possible, mais + * pas les données de controle et les données de selection (donc plutot * travailler sur les fichiers estcomind/estpopind que sur les 4 tables). * * @author chatellier @@ -124,7 +124,7 @@ protected CoserBusinessConfig config; - protected ImportService importService; + protected CommonService commonService; protected ProjectService projectService; @@ -142,7 +142,7 @@ public WebService(CoserBusinessConfig config) { this.config = config; - importService = new ImportService(config); + commonService = new CommonService(config); projectService = new ProjectService(config); publicationService = new PublicationService(config); @@ -172,7 +172,7 @@ if (indicatorsMap == null) { indicatorsMap = new MultiKeyMap(); File indicatorsFile = config.getWebIndicatorsFile(); - DataStorage indicatorsStorage = importService.loadCSVFile(indicatorsFile); + DataStorage indicatorsStorage = commonService.loadCSVFile(indicatorsFile); Iterator<String[]> iteratorInd = indicatorsStorage.iterator(true); while (iteratorInd.hasNext()) { // "id";"label_fr";"label_en";"unit" @@ -201,7 +201,7 @@ // l'operation n'est pas obligatoire pour tous les clients // lourd, le fichier peut donc ne pas exister if (zoneFile.isFile()) { - zonesMap = importService.loadCSVFile(zoneFile); + zonesMap = commonService.loadCSVFile(zoneFile); } else { // fait volontairement un return new, n'affecte pas l'etat du @@ -639,7 +639,7 @@ // (les noms de fichiers sont personnalisables) for (Category category : Category.values()) { if (category.isDataCategory()) { - String sourceFileName = projectService.getDataStorageFileName(project, category, null); + String sourceFileName = commonService.getDataStorageFileName(project, category, null); Matcher matcher = CoserUtils.FILENAME_SUFFIX_PATTERN.matcher(sourceFileName); if (matcher.matches()) { result &= !(fileName.startsWith(matcher.group(1)) && fileName.endsWith(matcher.group(2))); @@ -1406,7 +1406,7 @@ File estPopIndFile = new File(resultDirectory, rsufiResult.getEstPopIndName()); // Campagne Indicateur Liste Espece Strate Annee Estimation EcartType CV - DataStorage dataStorage = importService.loadCSVFile(estPopIndFile, CoserConstants.CSV_RESULT_SEPARATOR_CHAR); + DataStorage dataStorage = commonService.loadCSVFile(estPopIndFile, CoserConstants.CSV_RESULT_SEPARATOR_CHAR); Iterator<String[]> estPopIndIterator = dataStorage.iterator(true); while (estPopIndIterator.hasNext()) { @@ -1506,7 +1506,7 @@ File estPopIndFile = new File(resultDirectory, rsufiResult.getEstPopIndName()); // Campagne Indicateur Liste Espece Strate Annee Estimation EcartType CV - DataStorage dataStorage = importService.loadCSVFile(estPopIndFile, CoserConstants.CSV_RESULT_SEPARATOR_CHAR); + DataStorage dataStorage = commonService.loadCSVFile(estPopIndFile, CoserConstants.CSV_RESULT_SEPARATOR_CHAR); Iterator<String[]> estPopIndIterator = dataStorage.iterator(true); while (estPopIndIterator.hasNext()) { @@ -1547,7 +1547,7 @@ File estComIndFile = new File(resultDirectory, rsufiResult.getEstComIndName()); // Campagne Indicateur Liste Strate Annee Estimation EcartType CV - DataStorage dataStorage = importService.loadCSVFile(estComIndFile, CoserConstants.CSV_RESULT_SEPARATOR_CHAR); + DataStorage dataStorage = commonService.loadCSVFile(estComIndFile, CoserConstants.CSV_RESULT_SEPARATOR_CHAR); Iterator<String[]> estPopIndIterator = dataStorage.iterator(true); while (estPopIndIterator.hasNext()) { @@ -1645,8 +1645,8 @@ File estComIndFile = new File(resultDirectory, rsufiResult.getEstComIndName()); // Campagne Indicateur Liste Strate Annee Estimation EcartType CV - DataStorage dataStorage = importService.loadCSVFile(estComIndFile, CoserConstants.CSV_RESULT_SEPARATOR_CHAR); - DataStorage dataStorageType = importService.loadCSVFile(codeTypeEspecesFile, CoserConstants.CSV_SEPARATOR_CHAR); + DataStorage dataStorage = commonService.loadCSVFile(estComIndFile, CoserConstants.CSV_RESULT_SEPARATOR_CHAR); + DataStorage dataStorageType = commonService.loadCSVFile(codeTypeEspecesFile, CoserConstants.CSV_SEPARATOR_CHAR); Iterator<String[]> estPopIndIterator = dataStorage.iterator(true); while (estPopIndIterator.hasNext()) { @@ -2269,7 +2269,7 @@ Map<String, SortedSet<String>> speciesMap = new HashMap<String, SortedSet<String>>(); // Campagne Indicateur Liste Strate Annee Estimation EcartType CV - DataStorage dataStorage = importService.loadCSVFile(estComIndFile, CoserConstants.CSV_RESULT_SEPARATOR_CHAR); + DataStorage dataStorage = commonService.loadCSVFile(estComIndFile, CoserConstants.CSV_RESULT_SEPARATOR_CHAR); Iterator<String[]> estComIndIterator = dataStorage.iterator(true); while (estComIndIterator.hasNext()) { String[] tuple = estComIndIterator.next(); Copied: trunk/coser-business/src/test/java/fr/ifremer/coser/services/CommonServiceTest.java (from rev 1014, trunk/coser-business/src/test/java/fr/ifremer/coser/services/ImportServiceTest.java) =================================================================== --- trunk/coser-business/src/test/java/fr/ifremer/coser/services/CommonServiceTest.java (rev 0) +++ trunk/coser-business/src/test/java/fr/ifremer/coser/services/CommonServiceTest.java 2012-07-17 09:06:44 UTC (rev 1016) @@ -0,0 +1,82 @@ +/* + * #%L + * + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2010 - 2012 Ifremer, Codelutin, Chatellier Eric + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ + +package fr.ifremer.coser.services; + +import java.io.File; +import java.net.URL; + +import org.junit.Before; +import org.junit.Test; + +import fr.ifremer.coser.CoserBusinessException; +import fr.ifremer.coser.CoserConstants.Category; +import fr.ifremer.coser.bean.Project; + +/** + * Project service tests. + * + * @author chatellier + * @version $Revision$ + * + * Last update : $Date$ + * By : $Author$ + */ +public class CommonServiceTest extends CoserTestAbstract { + + protected CommonService service; + + @Before + public void initService() { + service = new CommonService(config); + } + + @Test(expected=CoserBusinessException.class) + public void testWrongSeparator() throws CoserBusinessException { + Project p = new Project(); + + URL url = CommonServiceTest.class.getResource("/csv/badformat/capturesbadseparator.csv"); + File file = new File(url.getFile()); + service.loadCSVFile(p, Category.CATCH, file, null, true); + } + + @Test(expected=CoserBusinessException.class) + public void testBadHeaderName() throws CoserBusinessException { + Project p = new Project(); + + URL url = CommonServiceTest.class.getResource("/csv/badformat/stratesheadername.csv"); + File file = new File(url.getFile()); + service.loadCSVFile(p, Category.STRATA, file, null, true); + } + + @Test(expected=CoserBusinessException.class) + public void testBadHeaderOrder() throws CoserBusinessException { + Project p = new Project(); + + URL url = CommonServiceTest.class.getResource("/csv/badformat/traitsheaderorder.csv"); + File file = new File(url.getFile()); + service.loadCSVFile(p, Category.HAUL, file, null, true); + } +} Deleted: trunk/coser-business/src/test/java/fr/ifremer/coser/services/ImportServiceTest.java =================================================================== --- trunk/coser-business/src/test/java/fr/ifremer/coser/services/ImportServiceTest.java 2012-07-17 07:09:32 UTC (rev 1015) +++ trunk/coser-business/src/test/java/fr/ifremer/coser/services/ImportServiceTest.java 2012-07-17 09:06:44 UTC (rev 1016) @@ -1,82 +0,0 @@ -/* - * #%L - * - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2010 Ifremer, Codelutin, Chatellier Eric - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package fr.ifremer.coser.services; - -import java.io.File; -import java.net.URL; - -import org.junit.Before; -import org.junit.Test; - -import fr.ifremer.coser.CoserBusinessException; -import fr.ifremer.coser.CoserConstants.Category; -import fr.ifremer.coser.bean.Project; - -/** - * Project service tests. - * - * @author chatellier - * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ - */ -public class ImportServiceTest extends CoserTestAbstract { - - protected ImportService service; - - @Before - public void initService() { - service = new ImportService(config); - } - - @Test(expected=CoserBusinessException.class) - public void testWrongSeparator() throws CoserBusinessException { - Project p = new Project(); - - URL url = ImportServiceTest.class.getResource("/csv/badformat/capturesbadseparator.csv"); - File file = new File(url.getFile()); - service.loadCSVFile(p, Category.CATCH, file, null, true); - } - - @Test(expected=CoserBusinessException.class) - public void testBadHeaderName() throws CoserBusinessException { - Project p = new Project(); - - URL url = ImportServiceTest.class.getResource("/csv/badformat/stratesheadername.csv"); - File file = new File(url.getFile()); - service.loadCSVFile(p, Category.STRATA, file, null, true); - } - - @Test(expected=CoserBusinessException.class) - public void testBadHeaderOrder() throws CoserBusinessException { - Project p = new Project(); - - URL url = ImportServiceTest.class.getResource("/csv/badformat/traitsheaderorder.csv"); - File file = new File(url.getFile()); - service.loadCSVFile(p, Category.HAUL, file, null, true); - } -} Modified: trunk/coser-ui/src/main/java/fr/ifremer/coser/Coser.java =================================================================== --- trunk/coser-ui/src/main/java/fr/ifremer/coser/Coser.java 2012-07-17 07:09:32 UTC (rev 1015) +++ trunk/coser-ui/src/main/java/fr/ifremer/coser/Coser.java 2012-07-17 09:06:44 UTC (rev 1016) @@ -42,7 +42,7 @@ import fr.ifremer.coser.services.CommandService; import fr.ifremer.coser.services.ControlService; -import fr.ifremer.coser.services.ImportService; +import fr.ifremer.coser.services.CommonService; import fr.ifremer.coser.services.ProjectService; import fr.ifremer.coser.services.PublicationService; import fr.ifremer.coser.services.WebService; @@ -146,7 +146,6 @@ context.setContextValue(coserConfig); context.setContextValue(session); context.setContextValue(new ProjectService(coserConfig)); - context.setContextValue(new ImportService(coserConfig)); context.setContextValue(new CommandService(coserConfig)); context.setContextValue(new ControlService(coserConfig)); context.setContextValue(new PublicationService(coserConfig)); Modified: trunk/coser-ui/src/main/java/fr/ifremer/coser/ui/control/ControlHandler.java =================================================================== --- trunk/coser-ui/src/main/java/fr/ifremer/coser/ui/control/ControlHandler.java 2012-07-17 07:09:32 UTC (rev 1015) +++ trunk/coser-ui/src/main/java/fr/ifremer/coser/ui/control/ControlHandler.java 2012-07-17 09:06:44 UTC (rev 1016) @@ -1069,10 +1069,16 @@ */ public void validControl(ControlView view) { Project project = view.getContextValue(Project.class); - project.getControl().setValidated(true); - saveProjectControl(view); - JOptionPane.showMessageDialog(view, _("coser.ui.control.controlValidated"), - _("coser.ui.control.controlTitle"), JOptionPane.INFORMATION_MESSAGE); + ProjectService service = view.getContextValue(ProjectService.class); + + try { + service.validControl(project); + saveProjectControl(view); + JOptionPane.showMessageDialog(view, _("coser.ui.control.controlValidated"), + _("coser.ui.control.controlTitle"), JOptionPane.INFORMATION_MESSAGE); + } catch (CoserBusinessException ex) { + throw new CoserException("Can't generate html report", ex); + } } /**