[Suiviobsmer-commits] r581 - in trunk: . wao-business wao-business/src/main/java/fr/ifremer/wao wao-business/src/main/java/fr/ifremer/wao/bean wao-business/src/main/java/fr/ifremer/wao/io wao-business/src/main/java/fr/ifremer/wao/io/csv wao-business/src/main/java/fr/ifremer/wao/io/kml wao-business/src/main/java/fr/ifremer/wao/service wao-business/src/main/resources/i18n wao-business/src/main/xmi wao-business/src/test/java/fr/ifremer/wao wao-business/src/test/java/fr/ifremer/wao/io wao-business/src/test/java
Author: fdesbois Date: 2010-06-30 10:54:53 +0000 (Wed, 30 Jun 2010) New Revision: 581 Log: Evo #2352 : Cartography for contacts : - Reorganize io package - Add ServiceCartography + BoatDistrictKmlReader (implementation using Jak api) Added: trunk/wao-business/src/main/java/fr/ifremer/wao/io/ImportResultsImpl.java trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv/ trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv/ExportHelper.java trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv/ImportHelper.java trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv/SamplingExport.java trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv/WaoCsvHeader.java trunk/wao-business/src/main/java/fr/ifremer/wao/io/kml/ trunk/wao-business/src/main/java/fr/ifremer/wao/io/kml/BoatDistrictKmlReader.java trunk/wao-business/src/main/java/fr/ifremer/wao/io/kml/BoatDistrictKmlReaderJak.java trunk/wao-business/src/main/java/fr/ifremer/wao/io/kml/BoatDistrictSchemaData.java trunk/wao-business/src/main/java/fr/ifremer/wao/service/ServiceCartographyImpl.java trunk/wao-business/src/test/java/fr/ifremer/wao/service/ServiceCartographyImplTest.java trunk/wao-business/src/test/resources/import/boat_districts.kml Removed: trunk/wao-business/src/main/java/fr/ifremer/wao/bean/ImportResultsImpl.java trunk/wao-business/src/main/java/fr/ifremer/wao/io/ExportHelper.java trunk/wao-business/src/main/java/fr/ifremer/wao/io/ImportHelper.java trunk/wao-business/src/main/java/fr/ifremer/wao/io/SamplingExport.java trunk/wao-business/src/main/java/fr/ifremer/wao/io/WaoCsvHeader.java Modified: trunk/pom.xml trunk/wao-business/pom.xml trunk/wao-business/src/main/java/fr/ifremer/wao/WaoContextImpl.java trunk/wao-business/src/main/java/fr/ifremer/wao/io/ImportRefusedException.java trunk/wao-business/src/main/java/fr/ifremer/wao/service/ActivityCalendarImport.java trunk/wao-business/src/main/java/fr/ifremer/wao/service/ServiceBoatImpl.java trunk/wao-business/src/main/java/fr/ifremer/wao/service/ServiceContactImpl.java trunk/wao-business/src/main/java/fr/ifremer/wao/service/ServiceReferentialImpl.java trunk/wao-business/src/main/java/fr/ifremer/wao/service/ServiceSamplingImpl.java trunk/wao-business/src/main/resources/i18n/wao-business-en_GB.properties trunk/wao-business/src/main/resources/i18n/wao-business-fr_FR.properties trunk/wao-business/src/main/xmi/wao.zargo trunk/wao-business/src/test/java/fr/ifremer/wao/TestManager.java trunk/wao-business/src/test/java/fr/ifremer/wao/io/ImportHelperTest.java trunk/wao-business/src/test/java/fr/ifremer/wao/service/ServiceContactInternalTest.java trunk/wao-business/src/test/java/fr/ifremer/wao/service/ServiceSamplingImplTest.java trunk/wao-business/src/test/resources/log4j.properties trunk/wao-ui/src/main/java/fr/ifremer/wao/ui/components/CsvImport.java trunk/wao-ui/src/main/java/fr/ifremer/wao/ui/data/ImportEngine.java trunk/wao-ui/src/main/java/fr/ifremer/wao/ui/pages/Administration.java trunk/wao-ui/src/main/java/fr/ifremer/wao/ui/pages/Contacts.java trunk/wao-ui/src/main/java/fr/ifremer/wao/ui/pages/SamplingPlan.java Modified: trunk/pom.xml =================================================================== --- trunk/pom.xml 2010-06-29 14:20:31 UTC (rev 580) +++ trunk/pom.xml 2010-06-30 10:54:53 UTC (rev 581) @@ -113,18 +113,6 @@ <scope>test</scope> </dependency>--> <dependency> - <groupId>com.formos.tapestry</groupId> - <artifactId>tapestry-testify</artifactId> - <version>1.0.2</version> - <scope>test</scope> - </dependency> - <dependency> - <groupId>org.mockito</groupId> - <artifactId>mockito-core</artifactId> - <version>1.8.4</version> - <scope>test</scope> - </dependency> - <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.14</version> @@ -141,12 +129,25 @@ <version>1.5.10</version> <scope>runtime</scope> </dependency> + <!-- Graphics --> <dependency> <groupId>jfree</groupId> <artifactId>jfreechart</artifactId> <version>1.0.12</version> - </dependency> + </dependency> + <!-- KML for Cartography --> <dependency> + <groupId>de.micromata.jak</groupId> + <artifactId>JavaAPIforKml</artifactId> + <version>2.2.0-SNAPSHOT</version> + </dependency> + <dependency> + <groupId>xpp3</groupId> + <artifactId>xpp3</artifactId> + <version>1.1.4c</version> + </dependency> + <!-- Csv import/export --> + <dependency> <groupId>net.sourceforge.javacsv</groupId> <artifactId>javacsv</artifactId> <version>2.0</version> @@ -174,6 +175,18 @@ <version>4.8.1</version> <scope>test</scope> </dependency> + <dependency> + <groupId>com.formos.tapestry</groupId> + <artifactId>tapestry-testify</artifactId> + <version>1.0.2</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-core</artifactId> + <version>1.8.4</version> + <scope>test</scope> + </dependency> </dependencies> </dependencyManagement> Modified: trunk/wao-business/pom.xml =================================================================== --- trunk/wao-business/pom.xml 2010-06-29 14:20:31 UTC (rev 580) +++ trunk/wao-business/pom.xml 2010-06-30 10:54:53 UTC (rev 581) @@ -53,8 +53,17 @@ <groupId>net.sourceforge.javacsv</groupId> <artifactId>javacsv</artifactId> </dependency> - <!-- ToPIA --> + <!-- KML lib --> <dependency> + <groupId>de.micromata.jak</groupId> + <artifactId>JavaAPIforKml</artifactId> + </dependency> + <dependency> + <groupId>xpp3</groupId> + <artifactId>xpp3</artifactId> + </dependency> + <!-- ToPIA --> + <dependency> <groupId>org.nuiton.topia</groupId> <artifactId>topia-persistence</artifactId> </dependency> Modified: trunk/wao-business/src/main/java/fr/ifremer/wao/WaoContextImpl.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/WaoContextImpl.java 2010-06-29 14:20:31 UTC (rev 580) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/WaoContextImpl.java 2010-06-30 10:54:53 UTC (rev 581) @@ -26,7 +26,7 @@ package fr.ifremer.wao; import fr.ifremer.wao.entity.ActivityCalendar; -import fr.ifremer.wao.io.ImportHelper; +import fr.ifremer.wao.io.csv.ImportHelper; import fr.ifremer.wao.service.ServiceUser; import org.apache.commons.lang.RandomStringUtils; import org.apache.commons.lang.StringUtils; Deleted: trunk/wao-business/src/main/java/fr/ifremer/wao/bean/ImportResultsImpl.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/bean/ImportResultsImpl.java 2010-06-29 14:20:31 UTC (rev 580) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/bean/ImportResultsImpl.java 2010-06-30 10:54:53 UTC (rev 581) @@ -1,64 +0,0 @@ -/* - * #%L - * Wao :: Business - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2009 - 2010 Ifremer - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU 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 Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -package fr.ifremer.wao.bean; - -import java.util.ArrayList; -import java.util.List; - -/** - * ImportResultsImpl - * - * Created: 11 janv. 2010 - * - * @author fdesbois <fdesbois at codelutin.com> - */ -public class ImportResultsImpl extends ImportResults { - - @Override - public void addError(int rowNum, String msg) { - String str = "Ligne " + rowNum + " : " + msg; - getErrors().add(str); - } - - @Override - public List<String> getErrors() { - if (errors == null) { - errors = new ArrayList<String>(); - } - return errors; - } - - @Override - public void incNbRefused() { - nbRowsRefused++; - } - - @Override - public void incNbImported() { - nbRowsImported++; - } - -} Deleted: trunk/wao-business/src/main/java/fr/ifremer/wao/io/ExportHelper.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/io/ExportHelper.java 2010-06-29 14:20:31 UTC (rev 580) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/io/ExportHelper.java 2010-06-30 10:54:53 UTC (rev 581) @@ -1,168 +0,0 @@ -/* - * #%L - * Wao :: Business - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2009 - 2010 Ifremer - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU 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 Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -package fr.ifremer.wao.io; - -import com.csvreader.CsvWriter; -import fr.ifremer.wao.io.WaoCsvHeader.IOHeader; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; - -/** - * Helper for CSV Export. This class must be inherited to be used in services - * implementations. Two methods needed : - * <pre> - * - {@link #record(IOHeader, String)} : record a value in the file - * - {@link #getHeaderValue(int)} : get the string header value corresponding - * to the index value. - * </pre> - * You have to used {@link WaoCsvHeader} to manage this two methods, - * to retrieve good indexes and good values for printing data headers. - * Steps : - * <pre> - * - Instanciate {@link #ExportHelper(CsvWriter, int) } - * (with abstract method implementations if needed). - * - Call {@link #writeHeaders() } method to prepare columns and write - * first row in the resulting file. - * - In the loop data, first use {@link #newRecord() } to prepare the current - * record. - * - Then used for each column, the {@link #record(IOHeader, String) } method. - * - Finally call the {@link #writeRecord() } to write the record in file. - * </pre> - * - * Created: 11 févr. 2010 - * - * @param <H> - * @author fdesbois <fdesbois at codelutin.com> - */ -public abstract class ExportHelper<H extends IOHeader> { - - private static final Logger logger = LoggerFactory.getLogger(ExportHelper.class); - - /** Writer used to record data **/ - protected CsvWriter writer; - - /** Current record to write **/ - protected String[] record; - - /** Number of columns/headers in resulting export **/ - protected int nbHeaders; - - /** - * Constructor of ExportHelper. Need an existing CsvWriter ready to - * write data in it. - * - * @param writer the CsvWriter used for record data - * @param nbHeaders number of columns in the resulting file - * @throws IOException - */ - public ExportHelper(CsvWriter writer, int nbHeaders) throws IOException { - this.writer = writer; - this.nbHeaders = nbHeaders; - } - - /** - * Record a value for a header corresponding to the H generic type from - * {@link IOHeader} class. - * - * @param header IOHeader used to record the value (column in the file) - * @param value the value to record - */ - public abstract void record(H header, String value); - - /** - * Return the header String value based on index. All matching integers for - * headers are defined in {@link IOHeader} class. - * - * @param index of the header - * @return the String value of the header - * @throws IOException - */ - protected abstract String getHeaderValue(int index) throws IOException; - - /** - * Write the first header line of the file. This method uses - * {@link #getHeaderValue(int) } to retrieve the corresponding name of the - * header depends on its index. - * - * @throws IOException - */ - public void writeHeaders() throws IOException { - for (int i = 0; i < nbHeaders; i++) { - // Always use "" for headers -// String header = null; -// -// if (i == 0) { -// header = new StringBuilder("\""). -// append(getHeaderValue(i)). -// append("\""). -// toString(); -// } else { -// header = getHeaderValue(i); -// } -// -// if (logger.isDebugEnabled()) { -// logger.debug("Header " + i + " : " + getHeaderValue(i)); -// logger.debug("Header " + i + " with StringBuilder : " + header); -// } - - String header = getHeaderValue(i); - - writer.write(header); - } - writer.endRecord(); - } - - /** - * Record a value in the current record. - * - * @param index of the column - * @param value of the data to record - */ - public void record(int index, String value) { - if (value != null) { - record[index] = value; - } - } - - /** - * Prepare a new record (new file row). - */ - public void newRecord() { - record = new String[nbHeaders]; - } - - /** - * Write the current record in the resulting file. - * - * @throws IOException - */ - public void writeRecord() throws IOException { - writer.writeRecord(record); - writer.flush(); - } -} Deleted: trunk/wao-business/src/main/java/fr/ifremer/wao/io/ImportHelper.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/io/ImportHelper.java 2010-06-29 14:20:31 UTC (rev 580) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/io/ImportHelper.java 2010-06-30 10:54:53 UTC (rev 581) @@ -1,320 +0,0 @@ -/* - * #%L - * Wao :: Business - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2009 - 2010 Ifremer - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU 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 Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -package fr.ifremer.wao.io; - -import fr.ifremer.wao.*; -import com.csvreader.CsvReader; -import fr.ifremer.wao.io.WaoCsvHeader.ACTIVITY_CALENDAR; -import fr.ifremer.wao.io.WaoCsvHeader.CONTACT; -import fr.ifremer.wao.io.WaoCsvHeader.DatedHeader; -import fr.ifremer.wao.io.WaoCsvHeader.IOHeader; -import fr.ifremer.wao.io.WaoCsvHeader.SAMPLING; -import java.io.IOException; -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.List; -import java.util.Locale; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.time.DurationFormatUtils; -import org.nuiton.util.PeriodDates; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * ImportHelper - * - * Created: 4 janv. 2010 - * - * @author fdesbois <fdesbois at codelutin.com> - */ -public class ImportHelper { - - private static final Logger logger = - LoggerFactory.getLogger(ImportHelper.class); - - protected CsvReader reader; - - protected static WaoContext context; - - // 2000 -> 2099 - public static final int CURRENT_MILLENIUM = 2000; - - public static final String DEFAULT_PATTERN = "dd/MM/yyyy"; - public static final String MONTH_PATTERN = "MM/yyyy"; - - public ImportHelper(CsvReader reader) { - this.reader = reader; - } - - public static void setContext(WaoContext context) { - ImportHelper.context = context; - } - - public static Boolean parseContactValidation(CsvReader reader, IOHeader header) throws IOException { - String validation = read(reader, header); - Boolean result = null; - if ("A".equals(validation)) { - result = Boolean.TRUE; - } else if ("R".equals(validation)) { - result = Boolean.FALSE; - } - return result; - } - - public static boolean parseContactMammals(CsvReader reader, IOHeader header) throws IOException { - String mammals = read(reader, header); - return "X".equals(mammals); - } - - public static Date parseContactCreateDate(String code, Date createDate) throws ParseException { - Calendar time = new GregorianCalendar(Locale.FRENCH); - if (StringUtils.isNotEmpty(code)) { - time = new GregorianCalendar(Locale.FRENCH); - time.setTime(CONTACT.TIME_FORMAT.parse(code)); - } else { - // Use current date with no time as a reference if no code is set - time.setTime(context.getCurrentDate()); - time.set(Calendar.HOUR_OF_DAY, 0); - time.set(Calendar.MINUTE, 0); - time.set(Calendar.SECOND, 0); - time.set(Calendar.MILLISECOND, 0); - } - - Calendar result = new GregorianCalendar(Locale.FRENCH); - if (createDate != null) { - result.setTime(createDate); - result.set(Calendar.HOUR_OF_DAY, time.get(Calendar.HOUR_OF_DAY)); - result.set(Calendar.MINUTE, time.get(Calendar.MINUTE)); - result.set(Calendar.SECOND, time.get(Calendar.SECOND)); - result.set(Calendar.MILLISECOND, time.get(Calendar.MILLISECOND)); - } else { - result.setTime(context.getCurrentDate()); - } - return result.getTime(); - } - - public static String readSampleRowCode(CsvReader reader) throws IOException { - String code = read(reader, SAMPLING.PLAN_CODE); - return context.prepareSampleRowCode(code); - } - - /** - * Read a string value in CsvReader from {@code header} column. - * In ActivityCalendarImport the result value can be null if the read value is "NA". - * - * @param reader CsvReader used to read the value - * @param header Column header in the CsvReader - * @return the String value read or null if set to "NA" in ActivityCalendar import. - * @throws IOException - */ - public static String read(CsvReader reader, IOHeader header) throws IOException { - String result = reader.get(header.name()).trim(); - if (header instanceof ACTIVITY_CALENDAR && "NA".equals(result)) { - return null; - } - return result; - } - - /** - * Read an int value in CsvReader from {@code header} column. - * - * @param reader CsvReader used to read the value - * @param header Column header in the CsvReader - * @return the int value or -1 if the value read is null - * @throws IOException - * @see ImportHelper#read(CsvReader, IOHeader) - */ - public static int readInt(CsvReader reader, IOHeader header) throws IOException { - String str = read(reader, header); - if (StringUtils.isEmpty(str)) { - return -1; - } - return Integer.parseInt(str); - } - - /** - * Read an Integer value in CsvReader from {@code header} column. - * - * @param reader CsvReader used to read the value - * @param header Column header in the CsvReader - * @return the Integer value or null if the value read is null - * @throws IOException - * @see ImportHelper#readInt(CsvReader, IOHeader) - */ - public static Integer readInteger(CsvReader reader, IOHeader header) throws IOException { - int result = readInt(reader, header); - return result != -1 ? result : null; - } - - /** - * Read two values in CsvReader corresponding to a period from {@code headerBegin} and {@code headEnd} column. - * - * @param reader CsvReader used to read the value - * @param headerBegin Column header in the CsvReader for periodBegin - * @param headerEnd Column header in the CsvReader for periodEnd - * @return the PeriodDates created from periodBegin and periodEnd read from Csv file - * @throws IOException - * @throws ParseException - * @throws IllegalArgumentException - * @see #readDate(CsvReader, DatedHeader) - */ - public static PeriodDates readPeriod(CsvReader reader, DatedHeader headerBegin, DatedHeader headerEnd) - throws IOException, ParseException { - Date end = readDate(reader, headerEnd); - Date begin = readDate(reader, headerBegin); - if (begin != null && end != null) { - PeriodDates period = new PeriodDates(begin, end); - period.initDayOfMonthExtremities(); - return period; - } - return null; - } - - /** - * Read a Date value in CsvReader from {@code header} column. - * - * @param reader CsvReader used to read the value - * @param header Column header in the CsvReader - * @return the Date value or null if the value read is null - * @throws IOException - * @throws ParseException - * @see ImportHelper#read(CsvReader, IOHeader) - * @see ImportHelper#parseDate(String, String) - */ - public static Date readDate(CsvReader reader, DatedHeader header) - throws IOException, ParseException { - - String str = read(reader, header); - if (logger.isTraceEnabled()) { - logger.trace("Read date " + header.name() + " : " + str); - } - return parseDate(str, header.datePattern()); - } - - /** - * Parse a date from a Csv file. Depends on pattern wanted. The default - * pattern from OpenOffice or Excel is considered for parsing (JJ/MM/AA). - * - * @param value of the reading date - * @param pattern for parsing - * @return the parsed date - * @throws ParseException - */ - public static Date parseDate(String value, String pattern) - throws ParseException { - - if (StringUtils.isEmpty(value)) { - return null; - } - - DateFormat dateFormat = null; - Date result = null; - Calendar calendar = Calendar.getInstance(); - - // Case of MONTH_PATTERN : MM/yyyy - if (pattern.equals(MONTH_PATTERN)) { - dateFormat = new SimpleDateFormat(DEFAULT_PATTERN); - try { - // Try to parse with default_pattern (ok for default OpenOffice - // or Excel date format) - result = dateFormat.parse(value); - calendar.setTime(result); - // In this case, we must suppress the day from the date - // Put it to 1 - calendar.set(Calendar.DAY_OF_MONTH, 1); - } catch (ParseException eee) { - // If the date can't be parse, it must be ok with header pattern - logger.debug("Date parse error : " + eee.getMessage()); - dateFormat = new SimpleDateFormat(pattern); - result = dateFormat.parse(value); - calendar.setTime(result); - } - } else { - dateFormat = new SimpleDateFormat(pattern); - result = dateFormat.parse(value); - calendar.setTime(result); - } - - // Check if the year is correct - int year = calendar.get(Calendar.YEAR); - if (logger.isTraceEnabled()) { - logger.trace("Read date year : " + year); - } - // If year < to the current millenium, the year is incorrect, must - // add the millenium to the year - // It's because of century problem : /10 must be /2010 - if (year < CURRENT_MILLENIUM) { - calendar.add(Calendar.YEAR, CURRENT_MILLENIUM); - } - return calendar.getTime(); - } - - public static long logTimeAndMemory(Logger log, long tic1, String msg) { - if (log.isInfoEnabled()) { - log.info("RUNNING... Import : " + msg); - Runtime runtime = Runtime.getRuntime(); - long mem = (runtime.totalMemory() - runtime.freeMemory()) / 1048576; - //long memMega = mem / 1024 / 1024; - log.info("Memory : " + mem + " Mo"); - long tic2 = System.currentTimeMillis(); - log.info("Time : " + DurationFormatUtils.formatDurationHMS(tic2 - tic1)); - } - return System.currentTimeMillis(); - } - - /** - * This method is used to check if {@code reader} contains at least the - * {@code keyHeader} in headers. Otherwise an exception will be thrown. - * - * @param reader CsvReader to check (headers need to be read before) - * @param keyHeader Header to check - * @throws WaoBusinessException if keyHeader is not found - */ - public static void checkKeyHeader(CsvReader reader, IOHeader keyHeader) - throws WaoBusinessException { - - try { - List<String> headers = Arrays.asList(reader.getHeaders()); - - if (!headers.contains(keyHeader.name())) { - throw new WaoBusinessException( - WaoBusinessException.Type.IMPORT_ERROR, null, - "Fichier non reconnu, aucune colonne ne correspond à '" + - keyHeader.name() + "'."); - } - - } catch (IOException eee) { - throw new WaoException("Une erreur est survenue à la lecture de" + - " l'en-tête du fichier CSV. Veuillez vérifier votre fichier.", eee); - } - } - -} Modified: trunk/wao-business/src/main/java/fr/ifremer/wao/io/ImportRefusedException.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/io/ImportRefusedException.java 2010-06-29 14:20:31 UTC (rev 580) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/io/ImportRefusedException.java 2010-06-30 10:54:53 UTC (rev 581) @@ -25,7 +25,7 @@ /** * ImportRefusedException is used to advise import service that an error occurs * during loading data. Generally this exception is catched and messages will - * be encapsulated in {@link fr.ifremer.wao.bean.ImportResults}. + * be encapsulated in {@link ImportResults}. * * Created: 15 avr. 2010 * Copied: trunk/wao-business/src/main/java/fr/ifremer/wao/io/ImportResultsImpl.java (from rev 573, trunk/wao-business/src/main/java/fr/ifremer/wao/bean/ImportResultsImpl.java) =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/io/ImportResultsImpl.java (rev 0) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/io/ImportResultsImpl.java 2010-06-30 10:54:53 UTC (rev 581) @@ -0,0 +1,64 @@ +/* + * #%L + * Wao :: Business + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2009 - 2010 Ifremer + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU 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 Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +package fr.ifremer.wao.io; + +import java.util.ArrayList; +import java.util.List; + +/** + * ImportResultsImpl + * + * Created: 11 janv. 2010 + * + * @author fdesbois <fdesbois at codelutin.com> + */ +public class ImportResultsImpl extends ImportResults { + + @Override + public void addError(int rowNum, String msg) { + String str = "Ligne " + rowNum + " : " + msg; + getErrors().add(str); + } + + @Override + public List<String> getErrors() { + if (errors == null) { + errors = new ArrayList<String>(); + } + return errors; + } + + @Override + public void incNbRefused() { + nbRowsRefused++; + } + + @Override + public void incNbImported() { + nbRowsImported++; + } + +} Property changes on: trunk/wao-business/src/main/java/fr/ifremer/wao/io/ImportResultsImpl.java ___________________________________________________________________ Added: svn:keywords + Author Date Id Revision HeadURL Deleted: trunk/wao-business/src/main/java/fr/ifremer/wao/io/SamplingExport.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/io/SamplingExport.java 2010-06-29 14:20:31 UTC (rev 580) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/io/SamplingExport.java 2010-06-30 10:54:53 UTC (rev 581) @@ -1,125 +0,0 @@ -/* - * #%L - * Wao :: Business - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2009 - 2010 Ifremer - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU 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 Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -package fr.ifremer.wao.io; - -import com.csvreader.CsvWriter; -import fr.ifremer.wao.bean.ConnectedUser; -import fr.ifremer.wao.entity.SampleMonth; -import fr.ifremer.wao.entity.SampleRow; -import fr.ifremer.wao.entity.WaoUser; -import fr.ifremer.wao.io.WaoCsvHeader.SAMPLING; -import fr.ifremer.wao.io.WaoCsvHeader.SamplingHeader; -import java.io.IOException; -import java.text.ParseException; -import java.util.Date; -import java.util.List; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * SamplingExport - * - * Created: 11 févr. 2010 - * - * @author fdesbois <fdesbois at codelutin.com> - */ -public class SamplingExport extends ExportHelper<SamplingHeader> { - - private static final Logger log = LoggerFactory.getLogger(SamplingExport.class); - - protected ConnectedUser user; - - protected List<String> monthHeaders; - - /** Used for {@link #getHeaderValue(int)} : changed for each call to the method **/ - protected int currMonthIndex; - - /** - * Constructor with {@code user} and {@code monthHeaders} needed to prepare - * headers and record months values. - * - * @param writer CsvWriter used to write data in the resulting file. - * @param user WaoUser who called the export - * @param monthHeaders String values of months to put in header row - * @throws IOException - */ - public SamplingExport(CsvWriter writer, ConnectedUser user, List<String> monthHeaders) throws IOException { - super(writer, SAMPLING.getTotalHeaders() + monthHeaders.size()); - this.monthHeaders = monthHeaders; - this.user = user; - } - - @Override - protected String getHeaderValue(int index) throws IOException { - int nbHeadersForMonths = monthHeaders.size(); - String result = ""; - if (index >= SAMPLING.getStartIndexForMonths() && currMonthIndex < nbHeadersForMonths) { - result = monthHeaders.get(currMonthIndex); - currMonthIndex++; - } else { - SamplingHeader header = WaoCsvHeader.getHeaderForSamplingCsv(index, nbHeadersForMonths); - // for an admin, same text as in Import (enum name) - // for a user, the text is complete - result = user.isAdmin() ? header.name() : header.toString(); - } - return result; - } - - @Override - public void record(SamplingHeader header, String value) { - int index = header.forSamplingCsv(); - if (index >= SAMPLING.getStartIndexForMonths()) { - index += monthHeaders.size(); - } - record(index, value); - } - - public void recordMonths(SampleRow row) throws ParseException { - for (int i = 0; i < monthHeaders.size(); i++) { - // Get date from monthHeaders list - Date month = SAMPLING.getDateFormat().parse(monthHeaders.get(i)); - // Retrieve sampleMonth corresponding - SampleMonth sampleMonth = row.getSampleMonth(month); - // Add it to the file if it exists - if (sampleMonth != null) { - // Prepare index for record - int index = SAMPLING.getStartIndexForMonths() + i; - String expected = String.valueOf(sampleMonth.getExpectedTidesValue()); - String real = String.valueOf(sampleMonth.getRealTidesValue()); - // The admin as only expected value (to be the same as - // in import) - // Evo #2227 : Guest users have only access to expected values - if (user.isAdmin() || user.isGuest()) { - record(index, expected); - // Other users have both expected and real values - } else { - record(index, expected + " (" + real + ")"); - } - } - } - } - -} Deleted: trunk/wao-business/src/main/java/fr/ifremer/wao/io/WaoCsvHeader.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/io/WaoCsvHeader.java 2010-06-29 14:20:31 UTC (rev 580) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/io/WaoCsvHeader.java 2010-06-30 10:54:53 UTC (rev 581) @@ -1,473 +0,0 @@ -/* - * #%L - * Wao :: Business - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2009 - 2010 Ifremer - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU 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 Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -package fr.ifremer.wao.io; - -import java.text.DateFormat; -import java.text.NumberFormat; -import java.text.SimpleDateFormat; -import java.util.Locale; -import org.apache.commons.lang.BooleanUtils; - -/** - * CsvHeader - * - * Created: 11 févr. 2010 - * - * @author fdesbois <fdesbois at codelutin.com> - */ -public class WaoCsvHeader { - - public interface IOHeader { - - /** - * Name of the header. This method is automatically implemented for an - * enum. - * - * @return the name of the header - */ - String name(); - } - - public interface DatedHeader extends IOHeader { - - /** - * Pattern for Date parsing. This pattern can be null, if no format date is necessary. - * - * @return a String corresponding to the date pattern - */ - String datePattern(); - } - - public interface ContactHeader extends IOHeader { - - int forContactCsv(); - } - - public interface SamplingHeader extends IOHeader { - - int forSamplingCsv(); - } - - /** - * CSV headers for Boat - */ - public enum BOAT implements ContactHeader { - /** Boat immatriculation **/ - NAVS_COD(1, "Immatriculation", 20), - /** Boat name **/ - CARN_NOM(2, "Nom", 21), - /** Boat length **/ - CARN_LONGUEUR_HT(3, "Longueur (m)"), - /** Boat build year **/ - CARN_ANNEE(4, "Année de construction"), - /** Boat district code **/ - QUARTIER_IMMA(5, "Code quartier", 22), - /** ShipOwner code **/ - PER_COD, - /** ShipOwner last name **/ - PER_NOM, - /** ShipOwner first name **/ - PER_PRENOM, - /** Boat active **/ - NAVS_ACTIVE(0, "Actif/Inactif"), - /** BoatInfos contactFirstName **/ - CONT_PRENOM(6, "Prénom du contact"), - /** BoatInfos contactLastName **/ - CONT_NOM(7, "Nom du contact"), - /** BoatInfos contactEmail **/ - CONT_EMAIL(8, "Email du contact"), - /** BoatInfos contactPhoneNumber **/ - CONT_TEL(9, "Tél du contact"), - /** BoatInfos dup **/ - NAVS_DUP(10, "Capacité d'accueil du navire en personnels spécialisés"), - /** BoatInfos comment **/ - NAVS_COMMENT(11, "Commentaire"); - - private int contactHeader; - - private int boatHeader; - - private String title; - - BOAT(int indexBoat, String title, int indexContact) { - contactHeader = indexContact; - boatHeader = indexBoat; - this.title = title; - } - - BOAT(int indexBoat, String title) { - boatHeader = indexBoat; - this.title = title; - contactHeader = -1; - } - - BOAT() { - contactHeader = -1; - boatHeader = -1; - title = name(); - } - - @Override - public int forContactCsv() { - return contactHeader; - } - - public int forBoatCsv() { - return boatHeader; - } - - @Override - public String toString() { - return title; - } - - public static int getTotalHeaders() { - // NAVS_COMMENT is the last column - return NAVS_COMMENT.forBoatCsv() + 1; - } - - public static String getBoatInactiveCode() { - return "I"; - } - } - - /** - * CSV headers for SamplingPlan - */ - public enum SAMPLING implements SamplingHeader, ContactHeader, DatedHeader { - /** SampleRow code **/ - PLAN_CODE(0, "Code ligne du plan", 6), - /** Company name **/ - SOCIETE_NOM(1, "Société prestataire", 5), - /** Program code **/ - PROGRAMME_CODE(12, "Programme de rattachement", 7), - /** Program period begin **/ - PROGRAMME_DEBUT(13, "Date de début", 8), - /** Program period end **/ - PROGRAMME_FIN(14, "Date de fin", 9), - /** FishingZone other infos **/ - PECHE_AUTRE(5, "Zone de pêche autres informations", 13), - /** Profession code DCF5 **/ - METIER_CODE_DCF5(6, "Métier (Code DCF niveau 5)", 14), - /** Profession mesh size **/ - METIER_MAILLAGE(7, "Métier maillage (mm)", 15), - /** Profession size **/ - METIER_TAILLE(8, "Métier taille (m)", 16), - /** Profession other infos **/ - METIER_AUTRE(9, "Métier autre information", 17), - /** Profession libelle **/ - METIER_LIBELLE(10, "Métier libellé", 18), - /** Profession species **/ - METIER_ESPECES(11, "Métier espèces cibles", 19), - /** SampleRow nb observants **/ - PLAN_NB_OBSERV(16, "Nombre d'observateurs"), - /** SampleRow average tide time **/ - PLAN_DUREE_MOY(15, "Durée moyenne d'une marée (jours)"), - /** SampleRow comment **/ - PLAN_COMMENT(17, "Commentaire"); - - private int contactHeader; - - private int samplingHeader; - - private String title; - - SAMPLING(int indexSampling, String title, int indexContact) { - this(indexSampling, title); - contactHeader = indexContact; - } - - SAMPLING(int indexSampling, String title) { - samplingHeader = indexSampling; - this.title = title; - contactHeader = -1; - } - - @Override - public int forContactCsv() { - return contactHeader; - } - - @Override - public int forSamplingCsv() { - return samplingHeader; - } - - @Override - public String toString() { - return title; - } - - @Override - public String datePattern() { - return defaultDatePattern(); - } - - public static String defaultDatePattern() { - return "MM/yyyy"; - } - - public static DateFormat getDateFormat() { - return new SimpleDateFormat(defaultDatePattern(), Locale.FRENCH); - } - - public static NumberFormat getNumberFormat() { - return NumberFormat.getNumberInstance(Locale.FRENCH); - } - - public static int getStartIndexForMonths() { - return getLastHeaderBeforeMonths().forSamplingCsv() + 1; - } - - public static int getTotalHeaders() { - // PLAN_COMMENT is the last column - return PLAN_COMMENT.forSamplingCsv() + 1; - } - - public static SAMPLING getLastHeaderBeforeMonths() { - // PROGRAMME_FIN is the last column before months - return PROGRAMME_FIN; - } - } - - /** - * CSV headers for FishingZone - */ - public enum FISHING_ZONE implements SamplingHeader, ContactHeader { - /** FishingZone facade **/ - PECHE_FACADE(2, "Zone de pêche façade", 10), - /** FishingZone sector **/ - PECHE_ZONE(3, "Zone de pêche", 11), - /** FishingZone district code **/ - PECHE_DIVISION(4, "Zone de pêche divisions", 12); - - private int contactHeader; - - private int samplingHeader; - - String title; - - FISHING_ZONE(int indexSampling, String title, int indexContact) { - contactHeader = indexContact; - samplingHeader = indexSampling; - this.title = title; - } - - @Override - public int forContactCsv() { - return contactHeader; - } - - @Override - public int forSamplingCsv() { - return samplingHeader; - } - - @Override - public String toString() { - return title; - } - - public static String getDistrictCodeSeparator() { - return " / "; - } - } - - /** - * CSV headers for Contact - */ - public enum CONTACT implements ContactHeader, DatedHeader { - /** Contact code (create date time for existing contact) **/ - CONT_CODE(0), - /** Contact create date **/ - CONT_CREATION(1), - /** User id **/ - OBSERV_ID(2), - /** User prenom **/ - OBSERV_PRENOM(3), - /** User nom **/ - OBSERV_NOM(4), - /** Company id **/ - //SOCIETE_ID, - /** Contact state **/ - CONT_ETAT(23), - /** Contact tide begin **/ - CONT_DEBUT_MAREE(24), - /** Contact tide end **/ - CONT_FIN_MAREE(25), - /** Contact nb observants **/ - CONT_NB_OBSERV(26), - /** Contact mammals capture **/ - CONT_MAM_CAPT(27), - /** Contact mammals observation **/ - CONT_MAM_OBS(28), - /** Contact comment **/ - CONT_COMMENT(29), - /** Contact data input **/ - CONT_ALLEGRO(30), - /** Contact company validation **/ - CONT_SOCIETE_VALID(31), - /** Contact program validation **/ - CONT_PROGRAM_VALID(32); - - private int contactHeader; - - public static final DateFormat DATE_FORMAT = - new SimpleDateFormat(defaultDatePattern(), Locale.FRENCH); - - public static final DateFormat TIME_FORMAT = - new SimpleDateFormat("HHmmssS", Locale.FRENCH); - - CONTACT(int index) { - this.contactHeader = index; - } - - @Override - public int forContactCsv() { - return contactHeader; - } - - @Override - public String datePattern() { - return defaultDatePattern(); - } - - private static String defaultDatePattern() { - return "dd/MM/yyyy"; - } - - public static int getTotalHeaders() { - // CONT_PROGRAM_VALID is the last column - return CONT_PROGRAM_VALID.forContactCsv() + 1; - } - - public static String formatValidation(Boolean validation) { - String valid = ""; - if (validation == null) { - valid = "N"; - } else if (BooleanUtils.isTrue(validation)) { - valid = "A"; - } else { - valid = "R"; - } - return valid; - } - - public static String formatMammals(boolean mammals) { - return mammals ? "X" : ""; - } - } - - public enum ACTIVITY_CALENDAR implements IOHeader { - /** ActivityCalendar year **/ - SYNA_AN, - /** ActivityCalendar fiability **/ - INDQ_COD, - /** ActivityMonth month **/ - SYNA_MOI, - /** ActivityMonth harbourCode **/ - SYNA_POR_COD, - /** ActivityMonth nbSeaDays **/ - SYNA_NOMJDM, - /** ActivityMonth nbFishingDays **/ - SYNA_NOMJDP, - /** ActivityMonth nbBoardingPersons **/ - SYNA_NOMHE, - /** ActivityMonth harbourId **/ - SYNA_TPOR_COD, - /** ActivityMonth harbourLibelle **/ - SYNA_POR_LIB, - /** ActivityProfession professionOrder **/ - META_ORDRE, - /** ActivityProfession code **/ - MET_COD, - /** ActivityProfession id **/ - MET_ID, - /** ActivityProfession libelle **/ - MET_LIB, - /** ActivityZone code **/ - SECT_COD, - /** ActivityZone gradiantCode **/ - GRA_COD, - /** ActivityZone gradiantLibelle **/ - GRA_LIB, - /** ActivityZone zoneId **/ - TSECT_COD, - /** ActivityZone zoneLibelle **/ - SECT_LIB; - } - - public static String getHeaderForContactCsv(int index) { - for (BOAT boatEnum : BOAT.values()) { - if (boatEnum.forContactCsv() == index) { - return boatEnum.name(); - } - } - for (SAMPLING samplingEnum : SAMPLING.values()) { - if (samplingEnum.forContactCsv() == index) { - return samplingEnum.name(); - } - } - for (FISHING_ZONE zoneEnum : FISHING_ZONE.values()) { - if (zoneEnum.forContactCsv() == index) { - return zoneEnum.name(); - } - } - for (CONTACT contactEnum : CONTACT.values()) { - if (contactEnum.forContactCsv() == index) { - return contactEnum.name(); - } - } - return ""; - } - - public static String getHeaderForBoatCsv(int index) { - for (BOAT boatEnum : BOAT.values()) { - if (boatEnum.forBoatCsv() == index) { - return boatEnum.toString(); - } - } - return ""; - } - - public static SamplingHeader getHeaderForSamplingCsv(int index, int nbMonthHeaders) { - if (index > SAMPLING.getStartIndexForMonths()) { - index -= nbMonthHeaders; - } - - for (SAMPLING samplingEnum : SAMPLING.values()) { - if (samplingEnum.forSamplingCsv() == index) { - return samplingEnum; - } - } - for (FISHING_ZONE zoneEnum : FISHING_ZONE.values()) { - if (zoneEnum.forSamplingCsv() == index) { - return zoneEnum; - } - } - return null; - } -} Added: trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv/ExportHelper.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv/ExportHelper.java (rev 0) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv/ExportHelper.java 2010-06-30 10:54:53 UTC (rev 581) @@ -0,0 +1,168 @@ +/* + * #%L + * Wao :: Business + * + * $Id: ExportHelper.java 492 2010-06-07 18:36:10Z fdesbois $ + * $HeadURL: svn+ssh://fdesbois at labs.libre-entreprise.org/svnroot/suiviobsmer/trunk/wao-business/src/main/java/fr/ifremer/wao/io/ExportHelper.java $ + * %% + * Copyright (C) 2009 - 2010 Ifremer + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU 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 Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +package fr.ifremer.wao.io.csv; + +import com.csvreader.CsvWriter; +import fr.ifremer.wao.io.csv.WaoCsvHeader.IOHeader; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; + +/** + * Helper for CSV Export. This class must be inherited to be used in services + * implementations. Two methods needed : + * <pre> + * - {@link #record(IOHeader, String)} : record a value in the file + * - {@link #getHeaderValue(int)} : get the string header value corresponding + * to the index value. + * </pre> + * You have to used {@link WaoCsvHeader} to manage this two methods, + * to retrieve good indexes and good values for printing data headers. + * Steps : + * <pre> + * - Instanciate {@link #ExportHelper(CsvWriter, int) } + * (with abstract method implementations if needed). + * - Call {@link #writeHeaders() } method to prepare columns and write + * first row in the resulting file. + * - In the loop data, first use {@link #newRecord() } to prepare the current + * record. + * - Then used for each column, the {@link #record(IOHeader, String) } method. + * - Finally call the {@link #writeRecord() } to write the record in file. + * </pre> + * + * Created: 11 févr. 2010 + * + * @param <H> + * @author fdesbois <fdesbois at codelutin.com> + */ +public abstract class ExportHelper<H extends IOHeader> { + + private static final Logger logger = LoggerFactory.getLogger(ExportHelper.class); + + /** Writer used to record data **/ + protected CsvWriter writer; + + /** Current record to write **/ + protected String[] record; + + /** Number of columns/headers in resulting export **/ + protected int nbHeaders; + + /** + * Constructor of ExportHelper. Need an existing CsvWriter ready to + * write data in it. + * + * @param writer the CsvWriter used for record data + * @param nbHeaders number of columns in the resulting file + * @throws IOException + */ + public ExportHelper(CsvWriter writer, int nbHeaders) throws IOException { + this.writer = writer; + this.nbHeaders = nbHeaders; + } + + /** + * Record a value for a header corresponding to the H generic type from + * {@link IOHeader} class. + * + * @param header IOHeader used to record the value (column in the file) + * @param value the value to record + */ + public abstract void record(H header, String value); + + /** + * Return the header String value based on index. All matching integers for + * headers are defined in {@link IOHeader} class. + * + * @param index of the header + * @return the String value of the header + * @throws IOException + */ + protected abstract String getHeaderValue(int index) throws IOException; + + /** + * Write the first header line of the file. This method uses + * {@link #getHeaderValue(int) } to retrieve the corresponding name of the + * header depends on its index. + * + * @throws IOException + */ + public void writeHeaders() throws IOException { + for (int i = 0; i < nbHeaders; i++) { + // Always use "" for headers +// String header = null; +// +// if (i == 0) { +// header = new StringBuilder("\""). +// append(getHeaderValue(i)). +// append("\""). +// toString(); +// } else { +// header = getHeaderValue(i); +// } +// +// if (logger.isDebugEnabled()) { +// logger.debug("Header " + i + " : " + getHeaderValue(i)); +// logger.debug("Header " + i + " with StringBuilder : " + header); +// } + + String header = getHeaderValue(i); + + writer.write(header); + } + writer.endRecord(); + } + + /** + * Record a value in the current record. + * + * @param index of the column + * @param value of the data to record + */ + public void record(int index, String value) { + if (value != null) { + record[index] = value; + } + } + + /** + * Prepare a new record (new file row). + */ + public void newRecord() { + record = new String[nbHeaders]; + } + + /** + * Write the current record in the resulting file. + * + * @throws IOException + */ + public void writeRecord() throws IOException { + writer.writeRecord(record); + writer.flush(); + } +} Added: trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv/ImportHelper.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv/ImportHelper.java (rev 0) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv/ImportHelper.java 2010-06-30 10:54:53 UTC (rev 581) @@ -0,0 +1,320 @@ +/* + * #%L + * Wao :: Business + * + * $Id: ImportHelper.java 570 2010-06-28 14:29:55Z fdesbois $ + * $HeadURL: svn+ssh://fdesbois at labs.libre-entreprise.org/svnroot/suiviobsmer/trunk/wao-business/src/main/java/fr/ifremer/wao/io/ImportHelper.java $ + * %% + * Copyright (C) 2009 - 2010 Ifremer + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU 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 Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +package fr.ifremer.wao.io.csv; + +import fr.ifremer.wao.*; +import com.csvreader.CsvReader; +import fr.ifremer.wao.io.csv.WaoCsvHeader.ACTIVITY_CALENDAR; +import fr.ifremer.wao.io.csv.WaoCsvHeader.CONTACT; +import fr.ifremer.wao.io.csv.WaoCsvHeader.DatedHeader; +import fr.ifremer.wao.io.csv.WaoCsvHeader.IOHeader; +import fr.ifremer.wao.io.csv.WaoCsvHeader.SAMPLING; +import java.io.IOException; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; +import java.util.Locale; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.time.DurationFormatUtils; +import org.nuiton.util.PeriodDates; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * ImportHelper + * + * Created: 4 janv. 2010 + * + * @author fdesbois <fdesbois at codelutin.com> + */ +public class ImportHelper { + + private static final Logger logger = + LoggerFactory.getLogger(ImportHelper.class); + + protected CsvReader reader; + + protected static WaoContext context; + + // 2000 -> 2099 + public static final int CURRENT_MILLENIUM = 2000; + + public static final String DEFAULT_PATTERN = "dd/MM/yyyy"; + public static final String MONTH_PATTERN = "MM/yyyy"; + + public ImportHelper(CsvReader reader) { + this.reader = reader; + } + + public static void setContext(WaoContext context) { + ImportHelper.context = context; + } + + public static Boolean parseContactValidation(CsvReader reader, IOHeader header) throws IOException { + String validation = read(reader, header); + Boolean result = null; + if ("A".equals(validation)) { + result = Boolean.TRUE; + } else if ("R".equals(validation)) { + result = Boolean.FALSE; + } + return result; + } + + public static boolean parseContactMammals(CsvReader reader, IOHeader header) throws IOException { + String mammals = read(reader, header); + return "X".equals(mammals); + } + + public static Date parseContactCreateDate(String code, Date createDate) throws ParseException { + Calendar time = new GregorianCalendar(Locale.FRENCH); + if (StringUtils.isNotEmpty(code)) { + time = new GregorianCalendar(Locale.FRENCH); + time.setTime(CONTACT.TIME_FORMAT.parse(code)); + } else { + // Use current date with no time as a reference if no code is set + time.setTime(context.getCurrentDate()); + time.set(Calendar.HOUR_OF_DAY, 0); + time.set(Calendar.MINUTE, 0); + time.set(Calendar.SECOND, 0); + time.set(Calendar.MILLISECOND, 0); + } + + Calendar result = new GregorianCalendar(Locale.FRENCH); + if (createDate != null) { + result.setTime(createDate); + result.set(Calendar.HOUR_OF_DAY, time.get(Calendar.HOUR_OF_DAY)); + result.set(Calendar.MINUTE, time.get(Calendar.MINUTE)); + result.set(Calendar.SECOND, time.get(Calendar.SECOND)); + result.set(Calendar.MILLISECOND, time.get(Calendar.MILLISECOND)); + } else { + result.setTime(context.getCurrentDate()); + } + return result.getTime(); + } + + public static String readSampleRowCode(CsvReader reader) throws IOException { + String code = read(reader, SAMPLING.PLAN_CODE); + return context.prepareSampleRowCode(code); + } + + /** + * Read a string value in CsvReader from {@code header} column. + * In ActivityCalendarImport the result value can be null if the read value is "NA". + * + * @param reader CsvReader used to read the value + * @param header Column header in the CsvReader + * @return the String value read or null if set to "NA" in ActivityCalendar import. + * @throws IOException + */ + public static String read(CsvReader reader, IOHeader header) throws IOException { + String result = reader.get(header.name()).trim(); + if (header instanceof ACTIVITY_CALENDAR && "NA".equals(result)) { + return null; + } + return result; + } + + /** + * Read an int value in CsvReader from {@code header} column. + * + * @param reader CsvReader used to read the value + * @param header Column header in the CsvReader + * @return the int value or -1 if the value read is null + * @throws IOException + * @see ImportHelper#read(CsvReader, IOHeader) + */ + public static int readInt(CsvReader reader, IOHeader header) throws IOException { + String str = read(reader, header); + if (StringUtils.isEmpty(str)) { + return -1; + } + return Integer.parseInt(str); + } + + /** + * Read an Integer value in CsvReader from {@code header} column. + * + * @param reader CsvReader used to read the value + * @param header Column header in the CsvReader + * @return the Integer value or null if the value read is null + * @throws IOException + * @see ImportHelper#readInt(CsvReader, IOHeader) + */ + public static Integer readInteger(CsvReader reader, IOHeader header) throws IOException { + int result = readInt(reader, header); + return result != -1 ? result : null; + } + + /** + * Read two values in CsvReader corresponding to a period from {@code headerBegin} and {@code headEnd} column. + * + * @param reader CsvReader used to read the value + * @param headerBegin Column header in the CsvReader for periodBegin + * @param headerEnd Column header in the CsvReader for periodEnd + * @return the PeriodDates created from periodBegin and periodEnd read from Csv file + * @throws IOException + * @throws ParseException + * @throws IllegalArgumentException + * @see #readDate(CsvReader, DatedHeader) + */ + public static PeriodDates readPeriod(CsvReader reader, DatedHeader headerBegin, DatedHeader headerEnd) + throws IOException, ParseException { + Date end = readDate(reader, headerEnd); + Date begin = readDate(reader, headerBegin); + if (begin != null && end != null) { + PeriodDates period = new PeriodDates(begin, end); + period.initDayOfMonthExtremities(); + return period; + } + return null; + } + + /** + * Read a Date value in CsvReader from {@code header} column. + * + * @param reader CsvReader used to read the value + * @param header Column header in the CsvReader + * @return the Date value or null if the value read is null + * @throws IOException + * @throws ParseException + * @see ImportHelper#read(CsvReader, IOHeader) + * @see ImportHelper#parseDate(String, String) + */ + public static Date readDate(CsvReader reader, DatedHeader header) + throws IOException, ParseException { + + String str = read(reader, header); + if (logger.isTraceEnabled()) { + logger.trace("Read date " + header.name() + " : " + str); + } + return parseDate(str, header.datePattern()); + } + + /** + * Parse a date from a Csv file. Depends on pattern wanted. The default + * pattern from OpenOffice or Excel is considered for parsing (JJ/MM/AA). + * + * @param value of the reading date + * @param pattern for parsing + * @return the parsed date + * @throws ParseException + */ + public static Date parseDate(String value, String pattern) + throws ParseException { + + if (StringUtils.isEmpty(value)) { + return null; + } + + DateFormat dateFormat = null; + Date result = null; + Calendar calendar = Calendar.getInstance(); + + // Case of MONTH_PATTERN : MM/yyyy + if (pattern.equals(MONTH_PATTERN)) { + dateFormat = new SimpleDateFormat(DEFAULT_PATTERN); + try { + // Try to parse with default_pattern (ok for default OpenOffice + // or Excel date format) + result = dateFormat.parse(value); + calendar.setTime(result); + // In this case, we must suppress the day from the date + // Put it to 1 + calendar.set(Calendar.DAY_OF_MONTH, 1); + } catch (ParseException eee) { + // If the date can't be parse, it must be ok with header pattern + logger.debug("Date parse error : " + eee.getMessage()); + dateFormat = new SimpleDateFormat(pattern); + result = dateFormat.parse(value); + calendar.setTime(result); + } + } else { + dateFormat = new SimpleDateFormat(pattern); + result = dateFormat.parse(value); + calendar.setTime(result); + } + + // Check if the year is correct + int year = calendar.get(Calendar.YEAR); + if (logger.isTraceEnabled()) { + logger.trace("Read date year : " + year); + } + // If year < to the current millenium, the year is incorrect, must + // add the millenium to the year + // It's because of century problem : /10 must be /2010 + if (year < CURRENT_MILLENIUM) { + calendar.add(Calendar.YEAR, CURRENT_MILLENIUM); + } + return calendar.getTime(); + } + + public static long logTimeAndMemory(Logger log, long tic1, String msg) { + if (log.isInfoEnabled()) { + log.info("RUNNING... Import : " + msg); + Runtime runtime = Runtime.getRuntime(); + long mem = (runtime.totalMemory() - runtime.freeMemory()) / 1048576; + //long memMega = mem / 1024 / 1024; + log.info("Memory : " + mem + " Mo"); + long tic2 = System.currentTimeMillis(); + log.info("Time : " + DurationFormatUtils.formatDurationHMS(tic2 - tic1)); + } + return System.currentTimeMillis(); + } + + /** + * This method is used to check if {@code reader} contains at least the + * {@code keyHeader} in headers. Otherwise an exception will be thrown. + * + * @param reader CsvReader to check (headers need to be read before) + * @param keyHeader Header to check + * @throws WaoBusinessException if keyHeader is not found + */ + public static void checkKeyHeader(CsvReader reader, IOHeader keyHeader) + throws WaoBusinessException { + + try { + List<String> headers = Arrays.asList(reader.getHeaders()); + + if (!headers.contains(keyHeader.name())) { + throw new WaoBusinessException( + WaoBusinessException.Type.IMPORT_ERROR, null, + "Fichier non reconnu, aucune colonne ne correspond à '" + + keyHeader.name() + "'."); + } + + } catch (IOException eee) { + throw new WaoException("Une erreur est survenue à la lecture de" + + " l'en-tête du fichier CSV. Veuillez vérifier votre fichier.", eee); + } + } + +} Added: trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv/SamplingExport.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv/SamplingExport.java (rev 0) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv/SamplingExport.java 2010-06-30 10:54:53 UTC (rev 581) @@ -0,0 +1,124 @@ +/* + * #%L + * Wao :: Business + * + * $Id: SamplingExport.java 507 2010-06-11 14:51:13Z fdesbois $ + * $HeadURL: svn+ssh://fdesbois at labs.libre-entreprise.org/svnroot/suiviobsmer/trunk/wao-business/src/main/java/fr/ifremer/wao/io/SamplingExport.java $ + * %% + * Copyright (C) 2009 - 2010 Ifremer + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU 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 Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +package fr.ifremer.wao.io.csv; + +import com.csvreader.CsvWriter; +import fr.ifremer.wao.bean.ConnectedUser; +import fr.ifremer.wao.entity.SampleMonth; +import fr.ifremer.wao.entity.SampleRow; +import fr.ifremer.wao.io.csv.WaoCsvHeader.SAMPLING; +import fr.ifremer.wao.io.csv.WaoCsvHeader.SamplingHeader; +import java.io.IOException; +import java.text.ParseException; +import java.util.Date; +import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * SamplingExport + * + * Created: 11 févr. 2010 + * + * @author fdesbois <fdesbois at codelutin.com> + */ +public class SamplingExport extends ExportHelper<SamplingHeader> { + + private static final Logger log = LoggerFactory.getLogger(SamplingExport.class); + + protected ConnectedUser user; + + protected List<String> monthHeaders; + + /** Used for {@link #getHeaderValue(int)} : changed for each call to the method **/ + protected int currMonthIndex; + + /** + * Constructor with {@code user} and {@code monthHeaders} needed to prepare + * headers and record months values. + * + * @param writer CsvWriter used to write data in the resulting file. + * @param user WaoUser who called the export + * @param monthHeaders String values of months to put in header row + * @throws IOException + */ + public SamplingExport(CsvWriter writer, ConnectedUser user, List<String> monthHeaders) throws IOException { + super(writer, SAMPLING.getTotalHeaders() + monthHeaders.size()); + this.monthHeaders = monthHeaders; + this.user = user; + } + + @Override + protected String getHeaderValue(int index) throws IOException { + int nbHeadersForMonths = monthHeaders.size(); + String result = ""; + if (index >= SAMPLING.getStartIndexForMonths() && currMonthIndex < nbHeadersForMonths) { + result = monthHeaders.get(currMonthIndex); + currMonthIndex++; + } else { + SamplingHeader header = WaoCsvHeader.getHeaderForSamplingCsv(index, nbHeadersForMonths); + // for an admin, same text as in Import (enum name) + // for a user, the text is complete + result = user.isAdmin() ? header.name() : header.toString(); + } + return result; + } + + @Override + public void record(SamplingHeader header, String value) { + int index = header.forSamplingCsv(); + if (index >= SAMPLING.getStartIndexForMonths()) { + index += monthHeaders.size(); + } + record(index, value); + } + + public void recordMonths(SampleRow row) throws ParseException { + for (int i = 0; i < monthHeaders.size(); i++) { + // Get date from monthHeaders list + Date month = SAMPLING.getDateFormat().parse(monthHeaders.get(i)); + // Retrieve sampleMonth corresponding + SampleMonth sampleMonth = row.getSampleMonth(month); + // Add it to the file if it exists + if (sampleMonth != null) { + // Prepare index for record + int index = SAMPLING.getStartIndexForMonths() + i; + String expected = String.valueOf(sampleMonth.getExpectedTidesValue()); + String real = String.valueOf(sampleMonth.getRealTidesValue()); + // The admin as only expected value (to be the same as + // in import) + // Evo #2227 : Guest users have only access to expected values + if (user.isAdmin() || user.isGuest()) { + record(index, expected); + // Other users have both expected and real values + } else { + record(index, expected + " (" + real + ")"); + } + } + } + } + +} Added: trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv/WaoCsvHeader.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv/WaoCsvHeader.java (rev 0) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv/WaoCsvHeader.java 2010-06-30 10:54:53 UTC (rev 581) @@ -0,0 +1,473 @@ +/* + * #%L + * Wao :: Business + * + * $Id: WaoCsvHeader.java 462 2010-04-19 23:41:59Z tchemit $ + * $HeadURL: svn+ssh://fdesbois at labs.libre-entreprise.org/svnroot/suiviobsmer/trunk/wao-business/src/main/java/fr/ifremer/wao/io/WaoCsvHeader.java $ + * %% + * Copyright (C) 2009 - 2010 Ifremer + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU 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 Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +package fr.ifremer.wao.io.csv; + +import java.text.DateFormat; +import java.text.NumberFormat; +import java.text.SimpleDateFormat; +import java.util.Locale; +import org.apache.commons.lang.BooleanUtils; + +/** + * CsvHeader + * + * Created: 11 févr. 2010 + * + * @author fdesbois <fdesbois at codelutin.com> + */ +public class WaoCsvHeader { + + public interface IOHeader { + + /** + * Name of the header. This method is automatically implemented for an + * enum. + * + * @return the name of the header + */ + String name(); + } + + public interface DatedHeader extends IOHeader { + + /** + * Pattern for Date parsing. This pattern can be null, if no format date is necessary. + * + * @return a String corresponding to the date pattern + */ + String datePattern(); + } + + public interface ContactHeader extends IOHeader { + + int forContactCsv(); + } + + public interface SamplingHeader extends IOHeader { + + int forSamplingCsv(); + } + + /** + * CSV headers for Boat + */ + public enum BOAT implements ContactHeader { + /** Boat immatriculation **/ + NAVS_COD(1, "Immatriculation", 20), + /** Boat name **/ + CARN_NOM(2, "Nom", 21), + /** Boat length **/ + CARN_LONGUEUR_HT(3, "Longueur (m)"), + /** Boat build year **/ + CARN_ANNEE(4, "Année de construction"), + /** Boat district code **/ + QUARTIER_IMMA(5, "Code quartier", 22), + /** ShipOwner code **/ + PER_COD, + /** ShipOwner last name **/ + PER_NOM, + /** ShipOwner first name **/ + PER_PRENOM, + /** Boat active **/ + NAVS_ACTIVE(0, "Actif/Inactif"), + /** BoatInfos contactFirstName **/ + CONT_PRENOM(6, "Prénom du contact"), + /** BoatInfos contactLastName **/ + CONT_NOM(7, "Nom du contact"), + /** BoatInfos contactEmail **/ + CONT_EMAIL(8, "Email du contact"), + /** BoatInfos contactPhoneNumber **/ + CONT_TEL(9, "Tél du contact"), + /** BoatInfos dup **/ + NAVS_DUP(10, "Capacité d'accueil du navire en personnels spécialisés"), + /** BoatInfos comment **/ + NAVS_COMMENT(11, "Commentaire"); + + private int contactHeader; + + private int boatHeader; + + private String title; + + BOAT(int indexBoat, String title, int indexContact) { + contactHeader = indexContact; + boatHeader = indexBoat; + this.title = title; + } + + BOAT(int indexBoat, String title) { + boatHeader = indexBoat; + this.title = title; + contactHeader = -1; + } + + BOAT() { + contactHeader = -1; + boatHeader = -1; + title = name(); + } + + @Override + public int forContactCsv() { + return contactHeader; + } + + public int forBoatCsv() { + return boatHeader; + } + + @Override + public String toString() { + return title; + } + + public static int getTotalHeaders() { + // NAVS_COMMENT is the last column + return NAVS_COMMENT.forBoatCsv() + 1; + } + + public static String getBoatInactiveCode() { + return "I"; + } + } + + /** + * CSV headers for SamplingPlan + */ + public enum SAMPLING implements SamplingHeader, ContactHeader, DatedHeader { + /** SampleRow code **/ + PLAN_CODE(0, "Code ligne du plan", 6), + /** Company name **/ + SOCIETE_NOM(1, "Société prestataire", 5), + /** Program code **/ + PROGRAMME_CODE(12, "Programme de rattachement", 7), + /** Program period begin **/ + PROGRAMME_DEBUT(13, "Date de début", 8), + /** Program period end **/ + PROGRAMME_FIN(14, "Date de fin", 9), + /** FishingZone other infos **/ + PECHE_AUTRE(5, "Zone de pêche autres informations", 13), + /** Profession code DCF5 **/ + METIER_CODE_DCF5(6, "Métier (Code DCF niveau 5)", 14), + /** Profession mesh size **/ + METIER_MAILLAGE(7, "Métier maillage (mm)", 15), + /** Profession size **/ + METIER_TAILLE(8, "Métier taille (m)", 16), + /** Profession other infos **/ + METIER_AUTRE(9, "Métier autre information", 17), + /** Profession libelle **/ + METIER_LIBELLE(10, "Métier libellé", 18), + /** Profession species **/ + METIER_ESPECES(11, "Métier espèces cibles", 19), + /** SampleRow nb observants **/ + PLAN_NB_OBSERV(16, "Nombre d'observateurs"), + /** SampleRow average tide time **/ + PLAN_DUREE_MOY(15, "Durée moyenne d'une marée (jours)"), + /** SampleRow comment **/ + PLAN_COMMENT(17, "Commentaire"); + + private int contactHeader; + + private int samplingHeader; + + private String title; + + SAMPLING(int indexSampling, String title, int indexContact) { + this(indexSampling, title); + contactHeader = indexContact; + } + + SAMPLING(int indexSampling, String title) { + samplingHeader = indexSampling; + this.title = title; + contactHeader = -1; + } + + @Override + public int forContactCsv() { + return contactHeader; + } + + @Override + public int forSamplingCsv() { + return samplingHeader; + } + + @Override + public String toString() { + return title; + } + + @Override + public String datePattern() { + return defaultDatePattern(); + } + + public static String defaultDatePattern() { + return "MM/yyyy"; + } + + public static DateFormat getDateFormat() { + return new SimpleDateFormat(defaultDatePattern(), Locale.FRENCH); + } + + public static NumberFormat getNumberFormat() { + return NumberFormat.getNumberInstance(Locale.FRENCH); + } + + public static int getStartIndexForMonths() { + return getLastHeaderBeforeMonths().forSamplingCsv() + 1; + } + + public static int getTotalHeaders() { + // PLAN_COMMENT is the last column + return PLAN_COMMENT.forSamplingCsv() + 1; + } + + public static SAMPLING getLastHeaderBeforeMonths() { + // PROGRAMME_FIN is the last column before months + return PROGRAMME_FIN; + } + } + + /** + * CSV headers for FishingZone + */ + public enum FISHING_ZONE implements SamplingHeader, ContactHeader { + /** FishingZone facade **/ + PECHE_FACADE(2, "Zone de pêche façade", 10), + /** FishingZone sector **/ + PECHE_ZONE(3, "Zone de pêche", 11), + /** FishingZone district code **/ + PECHE_DIVISION(4, "Zone de pêche divisions", 12); + + private int contactHeader; + + private int samplingHeader; + + String title; + + FISHING_ZONE(int indexSampling, String title, int indexContact) { + contactHeader = indexContact; + samplingHeader = indexSampling; + this.title = title; + } + + @Override + public int forContactCsv() { + return contactHeader; + } + + @Override + public int forSamplingCsv() { + return samplingHeader; + } + + @Override + public String toString() { + return title; + } + + public static String getDistrictCodeSeparator() { + return " / "; + } + } + + /** + * CSV headers for Contact + */ + public enum CONTACT implements ContactHeader, DatedHeader { + /** Contact code (create date time for existing contact) **/ + CONT_CODE(0), + /** Contact create date **/ + CONT_CREATION(1), + /** User id **/ + OBSERV_ID(2), + /** User prenom **/ + OBSERV_PRENOM(3), + /** User nom **/ + OBSERV_NOM(4), + /** Company id **/ + //SOCIETE_ID, + /** Contact state **/ + CONT_ETAT(23), + /** Contact tide begin **/ + CONT_DEBUT_MAREE(24), + /** Contact tide end **/ + CONT_FIN_MAREE(25), + /** Contact nb observants **/ + CONT_NB_OBSERV(26), + /** Contact mammals capture **/ + CONT_MAM_CAPT(27), + /** Contact mammals observation **/ + CONT_MAM_OBS(28), + /** Contact comment **/ + CONT_COMMENT(29), + /** Contact data input **/ + CONT_ALLEGRO(30), + /** Contact company validation **/ + CONT_SOCIETE_VALID(31), + /** Contact program validation **/ + CONT_PROGRAM_VALID(32); + + private int contactHeader; + + public static final DateFormat DATE_FORMAT = + new SimpleDateFormat(defaultDatePattern(), Locale.FRENCH); + + public static final DateFormat TIME_FORMAT = + new SimpleDateFormat("HHmmssS", Locale.FRENCH); + + CONTACT(int index) { + this.contactHeader = index; + } + + @Override + public int forContactCsv() { + return contactHeader; + } + + @Override + public String datePattern() { + return defaultDatePattern(); + } + + private static String defaultDatePattern() { + return "dd/MM/yyyy"; + } + + public static int getTotalHeaders() { + // CONT_PROGRAM_VALID is the last column + return CONT_PROGRAM_VALID.forContactCsv() + 1; + } + + public static String formatValidation(Boolean validation) { + String valid = ""; + if (validation == null) { + valid = "N"; + } else if (BooleanUtils.isTrue(validation)) { + valid = "A"; + } else { + valid = "R"; + } + return valid; + } + + public static String formatMammals(boolean mammals) { + return mammals ? "X" : ""; + } + } + + public enum ACTIVITY_CALENDAR implements IOHeader { + /** ActivityCalendar year **/ + SYNA_AN, + /** ActivityCalendar fiability **/ + INDQ_COD, + /** ActivityMonth month **/ + SYNA_MOI, + /** ActivityMonth harbourCode **/ + SYNA_POR_COD, + /** ActivityMonth nbSeaDays **/ + SYNA_NOMJDM, + /** ActivityMonth nbFishingDays **/ + SYNA_NOMJDP, + /** ActivityMonth nbBoardingPersons **/ + SYNA_NOMHE, + /** ActivityMonth harbourId **/ + SYNA_TPOR_COD, + /** ActivityMonth harbourLibelle **/ + SYNA_POR_LIB, + /** ActivityProfession professionOrder **/ + META_ORDRE, + /** ActivityProfession code **/ + MET_COD, + /** ActivityProfession id **/ + MET_ID, + /** ActivityProfession libelle **/ + MET_LIB, + /** ActivityZone code **/ + SECT_COD, + /** ActivityZone gradiantCode **/ + GRA_COD, + /** ActivityZone gradiantLibelle **/ + GRA_LIB, + /** ActivityZone zoneId **/ + TSECT_COD, + /** ActivityZone zoneLibelle **/ + SECT_LIB; + } + + public static String getHeaderForContactCsv(int index) { + for (BOAT boatEnum : BOAT.values()) { + if (boatEnum.forContactCsv() == index) { + return boatEnum.name(); + } + } + for (SAMPLING samplingEnum : SAMPLING.values()) { + if (samplingEnum.forContactCsv() == index) { + return samplingEnum.name(); + } + } + for (FISHING_ZONE zoneEnum : FISHING_ZONE.values()) { + if (zoneEnum.forContactCsv() == index) { + return zoneEnum.name(); + } + } + for (CONTACT contactEnum : CONTACT.values()) { + if (contactEnum.forContactCsv() == index) { + return contactEnum.name(); + } + } + return ""; + } + + public static String getHeaderForBoatCsv(int index) { + for (BOAT boatEnum : BOAT.values()) { + if (boatEnum.forBoatCsv() == index) { + return boatEnum.toString(); + } + } + return ""; + } + + public static SamplingHeader getHeaderForSamplingCsv(int index, int nbMonthHeaders) { + if (index > SAMPLING.getStartIndexForMonths()) { + index -= nbMonthHeaders; + } + + for (SAMPLING samplingEnum : SAMPLING.values()) { + if (samplingEnum.forSamplingCsv() == index) { + return samplingEnum; + } + } + for (FISHING_ZONE zoneEnum : FISHING_ZONE.values()) { + if (zoneEnum.forSamplingCsv() == index) { + return zoneEnum; + } + } + return null; + } +} Added: trunk/wao-business/src/main/java/fr/ifremer/wao/io/kml/BoatDistrictKmlReader.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/io/kml/BoatDistrictKmlReader.java (rev 0) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/io/kml/BoatDistrictKmlReader.java 2010-06-30 10:54:53 UTC (rev 581) @@ -0,0 +1,23 @@ +package fr.ifremer.wao.io.kml; + +import fr.ifremer.wao.io.BoatDistrictData; + +import java.io.IOException; +import java.io.InputStream; + +/** + * Created: 30 juin 2010 + * + * @author fdesbois <fdesbois at codelutin.com> + * @version $Id$ + */ +public interface BoatDistrictKmlReader { + + void init(InputStream stream) throws IOException; + + boolean hasNext(); + + BoatDistrictData readNext(); + + void close(); +} Added: trunk/wao-business/src/main/java/fr/ifremer/wao/io/kml/BoatDistrictKmlReaderJak.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/io/kml/BoatDistrictKmlReaderJak.java (rev 0) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/io/kml/BoatDistrictKmlReaderJak.java 2010-06-30 10:54:53 UTC (rev 581) @@ -0,0 +1,106 @@ +package fr.ifremer.wao.io.kml; + +import de.micromata.opengis.kml.v_2_2_0.Coordinate; +import de.micromata.opengis.kml.v_2_2_0.Document; +import de.micromata.opengis.kml.v_2_2_0.Folder; +import de.micromata.opengis.kml.v_2_2_0.Kml; +import de.micromata.opengis.kml.v_2_2_0.Placemark; +import de.micromata.opengis.kml.v_2_2_0.Point; +import de.micromata.opengis.kml.v_2_2_0.SchemaData; +import de.micromata.opengis.kml.v_2_2_0.SimpleData; +import fr.ifremer.wao.entity.BoatDistrict; +import fr.ifremer.wao.io.BoatDistrictData; +import fr.ifremer.wao.io.BoatDistrictDataImpl; +import org.apache.commons.lang.StringUtils; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +/** + * Created: 30 juin 2010 + * + * @author fdesbois <fdesbois at codelutin.com> + * @version $Id$ + */ +public class BoatDistrictKmlReaderJak implements BoatDistrictKmlReader { + + List<Placemark> districts; + + Iterator<Placemark> iterator; + + @Override + public void init(InputStream stream) throws IOException { + Kml kml = Kml.unmarshal(stream); + + Document document = (Document) kml.getFeature(); + Folder folder = (Folder) document.getFeature().get(0); + + districts = new ArrayList<Placemark>(); + + int size = folder.getFeature().size(); + for (int i = 0; i < size; i++) { + Placemark placemark = (Placemark) folder.getFeature().get(i); + districts.add(placemark); + } + + iterator = districts.iterator(); + } + + @Override + public boolean hasNext() { + return iterator.hasNext(); + } + + @Override + public BoatDistrictData readNext() { + + Placemark placemark = iterator.next(); + + BoatDistrictData district = new BoatDistrictDataImpl(); + + SchemaData schemaData = placemark.getExtendedData().getSchemaData().get(0); + + for (SimpleData data : schemaData.getSimpleData()) { + + BoatDistrictSchemaData type = + BoatDistrictSchemaData.valueOfLabel(data.getName()); + + String value = data.getValue(); + switch (type) { + case NAME: + district.setName(value); break; + case DESCRIPTION: + district.setDescription(value); break; + case OBJECTID: + district.setObjectid(value); break; + case LIEU_COD: + district.setLieuCod(value); break; + case LIEU_LIB: + district.setLieuLib(value); break; + case TLIEU_COD: + district.setTlieuCod(value); break; + case L_OCEAN: + district.setLOcean(value); break; + case L_PAYS: + district.setLPays(value); + } + } + + // Retrieve coordinate + Point point = (Point) placemark.getGeometry(); + Coordinate coordinate = point.getCoordinates().get(0); + + district.setLongitude(coordinate.getLongitude()); + district.setLatitude(coordinate.getLatitude()); + + return district; + } + + @Override + public void close() { + } + +} Added: trunk/wao-business/src/main/java/fr/ifremer/wao/io/kml/BoatDistrictSchemaData.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/io/kml/BoatDistrictSchemaData.java (rev 0) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/io/kml/BoatDistrictSchemaData.java 2010-06-30 10:54:53 UTC (rev 581) @@ -0,0 +1,43 @@ +package fr.ifremer.wao.io.kml; + +/** + * Created: 29 juin 2010 + * + * @author fdesbois <fdesbois at codelutin.com> + * @version $Id$ + * @since 1.5 + */ +public enum BoatDistrictSchemaData { + + NAME("Name"), + DESCRIPTION("Description"), + OBJECTID(null), + LIEU_LIB(null), + LIEU_COD(null), + TLIEU_COD(null), + L_OCEAN(null), + L_PAYS(null); + + String label; + + BoatDistrictSchemaData(String label) { + this.label = label; + } + + public String getLabel() { + if (label != null) { + return label; + } + return name(); + } + + public static BoatDistrictSchemaData valueOfLabel(String label) { + for (BoatDistrictSchemaData curr : values()) { + if (curr.getLabel().equals(label)) { + return curr; + } + } + return null; + } + +} Modified: trunk/wao-business/src/main/java/fr/ifremer/wao/service/ActivityCalendarImport.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/service/ActivityCalendarImport.java 2010-06-29 14:20:31 UTC (rev 580) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/service/ActivityCalendarImport.java 2010-06-30 10:54:53 UTC (rev 581) @@ -37,9 +37,9 @@ import fr.ifremer.wao.entity.ActivityZoneDAO; import fr.ifremer.wao.entity.Boat; import fr.ifremer.wao.entity.BoatDAO; -import fr.ifremer.wao.io.ImportHelper; -import fr.ifremer.wao.io.WaoCsvHeader.ACTIVITY_CALENDAR; -import fr.ifremer.wao.io.WaoCsvHeader.BOAT; +import fr.ifremer.wao.io.csv.ImportHelper; +import fr.ifremer.wao.io.csv.WaoCsvHeader.ACTIVITY_CALENDAR; +import fr.ifremer.wao.io.csv.WaoCsvHeader.BOAT; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; Modified: trunk/wao-business/src/main/java/fr/ifremer/wao/service/ServiceBoatImpl.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/service/ServiceBoatImpl.java 2010-06-29 14:20:31 UTC (rev 580) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/service/ServiceBoatImpl.java 2010-06-30 10:54:53 UTC (rev 581) @@ -30,6 +30,7 @@ import fr.ifremer.wao.*; import fr.ifremer.wao.WaoBusinessException.Type; import fr.ifremer.wao.bean.ConnectedUser; +import fr.ifremer.wao.io.csv.ImportHelper; import org.nuiton.topia.TopiaException; import org.nuiton.topia.framework.TopiaQuery; import org.nuiton.topia.framework.TopiaQuery.Op; @@ -37,10 +38,9 @@ import fr.ifremer.wao.bean.CompanyBoatInfos; import fr.ifremer.wao.bean.CompanyBoatInfosImpl; import fr.ifremer.wao.entity.*; -import fr.ifremer.wao.io.ImportHelper; -import fr.ifremer.wao.io.ExportHelper; -import fr.ifremer.wao.io.WaoCsvHeader; -import fr.ifremer.wao.io.WaoCsvHeader.BOAT; +import fr.ifremer.wao.io.csv.ExportHelper; +import fr.ifremer.wao.io.csv.WaoCsvHeader; +import fr.ifremer.wao.io.csv.WaoCsvHeader.BOAT; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; Added: trunk/wao-business/src/main/java/fr/ifremer/wao/service/ServiceCartographyImpl.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/service/ServiceCartographyImpl.java (rev 0) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/service/ServiceCartographyImpl.java 2010-06-30 10:54:53 UTC (rev 581) @@ -0,0 +1,177 @@ +package fr.ifremer.wao.service; + +import de.micromata.opengis.kml.v_2_2_0.Coordinate; +import de.micromata.opengis.kml.v_2_2_0.Document; +import de.micromata.opengis.kml.v_2_2_0.Folder; +import de.micromata.opengis.kml.v_2_2_0.Kml; +import de.micromata.opengis.kml.v_2_2_0.Placemark; +import de.micromata.opengis.kml.v_2_2_0.Point; +import de.micromata.opengis.kml.v_2_2_0.SchemaData; +import de.micromata.opengis.kml.v_2_2_0.SimpleData; +import fr.ifremer.wao.WaoContext; +import fr.ifremer.wao.WaoDAOHelper; +import fr.ifremer.wao.WaoException; +import fr.ifremer.wao.io.BoatDistrictData; +import fr.ifremer.wao.io.kml.BoatDistrictKmlReader; +import fr.ifremer.wao.io.kml.BoatDistrictKmlReaderJak; +import fr.ifremer.wao.io.kml.BoatDistrictSchemaData; +import fr.ifremer.wao.io.ImportResults; +import fr.ifremer.wao.io.ImportResultsImpl; +import fr.ifremer.wao.entity.BoatDistrict; +import fr.ifremer.wao.entity.BoatDistrictDAO; +import org.nuiton.topia.TopiaContext; +import org.nuiton.topia.TopiaException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.InputStream; + +/** + * Created: 29 juin 2010 + * + * @author fdesbois <fdesbois at codelutin.com> + * @version $Id$ + * @since 1.5 + */ +public class ServiceCartographyImpl extends ServiceCartographyAbstract { + + private static final Logger logger = + LoggerFactory.getLogger(ServiceCartographyImpl.class); + + private WaoContext context; + + public void setContext(WaoContext context) { + this.context = context; + } + + @Override + protected TopiaContext beginTransaction() throws TopiaException { + return context.beginTransaction(); + } + + @Override + protected void treateError(TopiaContext transaction, Exception eee, + String message, Object... args) throws WaoException { + context.treateError(transaction, eee, message, args); + } + + @Override + protected void closeTransaction(TopiaContext transaction) { + context.closeTransaction(transaction); + } + + @Override + protected ImportResults executeImportBoatDistrictKml(TopiaContext transaction, InputStream input) + throws TopiaException, IOException { + + ImportResults results = new ImportResultsImpl(); + + BoatDistrictDAO dao = WaoDAOHelper.getBoatDistrictDAO(transaction); + + BoatDistrictKmlReader reader = new BoatDistrictKmlReaderJak(); + reader.init(input); + + int i = 0; + while (reader.hasNext()) { + + BoatDistrictData data = reader.readNext(); + + String districtName = data.getDescription(); + String districtCode = data.getObjectid(); + + if (logger.isDebugEnabled()) { + logger.debug("District : code = " + districtCode + + " _ name = " + districtName); + } + + if (districtCode != null) { + + BoatDistrict district = dao.findByCode(districtCode); + + if (district != null) { + + // Update data + district.setLatitude(data.getLatitude()); + district.setLongitude(data.getLongitude()); + district.setName(districtName); + + dao.update(district); + + results.incNbImported(); + } else { + // Reject + results.incNbRefused(); + results.addError(i, "Code quartier inconnu : " + districtCode); + } + } + + i++; + } + + reader.close(); + transaction.commitTransaction(); + +// Kml kml = Kml.unmarshal(input); +// +// Document document = (Document) kml.getFeature(); +// Folder folder = (Folder) document.getFeature().get(0); +// +// int size = folder.getFeature().size(); +// for (int i = 0; i < size; i++) { +// Placemark placemark = (Placemark) folder.getFeature().get(i); +// +// SchemaData schemaData = placemark.getExtendedData().getSchemaData().get(0); +// +// String districtName = null, districtCode = null; +// +// for (SimpleData data : schemaData.getSimpleData()) { +// +// BoatDistrictSchemaData type = +// BoatDistrictSchemaData.valueOfLabel(data.getName()); +// +// switch (type) { +// case DESCRIPTION: +// districtName = data.getValue(); +// break; +// case OBJECTID: +// districtCode = data.getValue(); +// } +// } +// +// if (logger.isDebugEnabled()) { +// logger.debug("District : code = " + districtCode + +// " _ name = " + districtName); +// } +// +// if (districtCode != null) { +// +// BoatDistrict district = dao.findByCode(districtCode); +// +// if (district != null) { +// +// // Retrieve coordinate +// Point point = (Point) placemark.getGeometry(); +// Coordinate coordinate = point.getCoordinates().get(0); +// +// // Update data +// district.setLatitude(coordinate.getLatitude()); +// district.setLongitude(coordinate.getLongitude()); +// district.setName(districtName); +// +// dao.update(district); +// +// results.incNbImported(); +// } else { +// // Reject +// results.incNbRefused(); +// results.addError(i, "Code quartier inconnu : " + districtCode); +// } +// } +// } +// +// transaction.commitTransaction(); + + return results; + } +} Modified: trunk/wao-business/src/main/java/fr/ifremer/wao/service/ServiceContactImpl.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/service/ServiceContactImpl.java 2010-06-29 14:20:31 UTC (rev 580) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/service/ServiceContactImpl.java 2010-06-30 10:54:53 UTC (rev 581) @@ -47,6 +47,23 @@ import fr.ifremer.wao.WaoQueryHelper; import fr.ifremer.wao.bean.ConnectedUser; import fr.ifremer.wao.bean.UserRole; +import fr.ifremer.wao.entity.Boat; +import fr.ifremer.wao.entity.Company; +import fr.ifremer.wao.entity.Contact; +import fr.ifremer.wao.entity.ContactDAO; +import fr.ifremer.wao.entity.ContactImpl; +import fr.ifremer.wao.entity.ElligibleBoat; +import fr.ifremer.wao.entity.ElligibleBoatDAO; +import fr.ifremer.wao.entity.FishingZone; +import fr.ifremer.wao.entity.Profession; +import fr.ifremer.wao.entity.SampleMonth; +import fr.ifremer.wao.entity.SampleRow; +import fr.ifremer.wao.entity.WaoUser; +import fr.ifremer.wao.io.ContactInput; +import fr.ifremer.wao.io.ImportRefusedException; +import fr.ifremer.wao.io.csv.ExportHelper; +import fr.ifremer.wao.io.csv.ImportHelper; +import fr.ifremer.wao.io.csv.WaoCsvHeader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.nuiton.topia.TopiaContext; @@ -57,11 +74,9 @@ import fr.ifremer.wao.bean.ContactStatus.NullSampleMonthException; import fr.ifremer.wao.bean.ContactFilter; import fr.ifremer.wao.bean.ContactState; -import fr.ifremer.wao.bean.ImportResults; -import fr.ifremer.wao.bean.ImportResultsImpl; -import fr.ifremer.wao.entity.*; -import fr.ifremer.wao.io.*; -import fr.ifremer.wao.io.WaoCsvHeader.*; +import fr.ifremer.wao.io.ImportResults; +import fr.ifremer.wao.io.ImportResultsImpl; +import fr.ifremer.wao.io.csv.WaoCsvHeader.*; import org.apache.commons.lang.BooleanUtils; /** @@ -192,7 +207,7 @@ @Override public void executeSaveContact(TopiaContext transaction, - Contact contact, boolean delete) + Contact contact, boolean delete) throws TopiaException, NullSampleMonthException { checkObserver(contact); @@ -353,7 +368,7 @@ FileOutputStream output = new FileOutputStream(file); writer = new CsvWriter(output, ',', context.getCsvCharset()); - ExportHelper<ContactHeader> export = + ExportHelper<ContactHeader> export = new ExportHelper<ContactHeader>(writer, CONTACT.getTotalHeaders()) { @@ -629,7 +644,7 @@ * @throws ParseException from ImportHelper * @see ImportHelper */ - protected void loadContactCsv(CsvReader reader, ContactInput contact, + protected void loadContactCsv(CsvReader reader, ContactInput contact, boolean updateValidation) throws IOException, TopiaException, ImportRefusedException, Modified: trunk/wao-business/src/main/java/fr/ifremer/wao/service/ServiceReferentialImpl.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/service/ServiceReferentialImpl.java 2010-06-29 14:20:31 UTC (rev 580) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/service/ServiceReferentialImpl.java 2010-06-30 10:54:53 UTC (rev 581) @@ -37,9 +37,8 @@ import fr.ifremer.wao.entity.FishingZoneDAO; import fr.ifremer.wao.entity.Profession; import fr.ifremer.wao.entity.ProfessionDAO; -import fr.ifremer.wao.io.ImportHelper; -import fr.ifremer.wao.io.WaoCsvHeader; -import fr.ifremer.wao.io.WaoCsvHeader.FISHING_ZONE; +import fr.ifremer.wao.io.csv.ImportHelper; +import fr.ifremer.wao.io.csv.WaoCsvHeader.FISHING_ZONE; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; Modified: trunk/wao-business/src/main/java/fr/ifremer/wao/service/ServiceSamplingImpl.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/service/ServiceSamplingImpl.java 2010-06-29 14:20:31 UTC (rev 580) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/service/ServiceSamplingImpl.java 2010-06-30 10:54:53 UTC (rev 581) @@ -39,8 +39,8 @@ import fr.ifremer.wao.bean.ConnectedUser; import fr.ifremer.wao.bean.FacadeRow; import fr.ifremer.wao.bean.FacadeRowImpl; -import fr.ifremer.wao.bean.ImportResults; -import fr.ifremer.wao.bean.ImportResultsImpl; +import fr.ifremer.wao.io.ImportResults; +import fr.ifremer.wao.io.ImportResultsImpl; import fr.ifremer.wao.bean.SamplingFilter; import fr.ifremer.wao.bean.UserRole; import fr.ifremer.wao.entity.Boat; @@ -63,10 +63,10 @@ import fr.ifremer.wao.entity.SampleRowLogDAO; import fr.ifremer.wao.entity.SampleRowLogImpl; import fr.ifremer.wao.entity.WaoUser; -import fr.ifremer.wao.io.ImportHelper; -import fr.ifremer.wao.io.SamplingExport; -import fr.ifremer.wao.io.WaoCsvHeader.FISHING_ZONE; -import fr.ifremer.wao.io.WaoCsvHeader.SAMPLING; +import fr.ifremer.wao.io.csv.ImportHelper; +import fr.ifremer.wao.io.csv.SamplingExport; +import fr.ifremer.wao.io.csv.WaoCsvHeader.FISHING_ZONE; +import fr.ifremer.wao.io.csv.WaoCsvHeader.SAMPLING; import org.apache.commons.lang.StringUtils; import org.apache.commons.mail.EmailException; import org.nuiton.topia.TopiaContext; Modified: trunk/wao-business/src/main/resources/i18n/wao-business-en_GB.properties =================================================================== --- trunk/wao-business/src/main/resources/i18n/wao-business-en_GB.properties 2010-06-29 14:20:31 UTC (rev 580) +++ trunk/wao-business/src/main/resources/i18n/wao-business-en_GB.properties 2010-06-30 10:54:53 UTC (rev 581) @@ -25,6 +25,7 @@ wao.error.serviceBoat.getShipOwnerNamesContains= wao.error.serviceBoat.importActivityCalendarCsv= wao.error.serviceBoat.importBoatCsv= +wao.error.serviceCartography.importBoatDistrictKml= wao.error.serviceContact.exportContactCsv= wao.error.serviceContact.getContacts= wao.error.serviceContact.getNbContacts= Modified: trunk/wao-business/src/main/resources/i18n/wao-business-fr_FR.properties =================================================================== --- trunk/wao-business/src/main/resources/i18n/wao-business-fr_FR.properties 2010-06-29 14:20:31 UTC (rev 580) +++ trunk/wao-business/src/main/resources/i18n/wao-business-fr_FR.properties 2010-06-30 10:54:53 UTC (rev 581) @@ -24,6 +24,7 @@ wao.error.serviceBoat.getShipOwnerNamesContains= wao.error.serviceBoat.importActivityCalendarCsv=Probl\u00E8me d'import du fichier CSV des calendriers d'activit\u00E9 wao.error.serviceBoat.importBoatCsv=Probl\u00E8me d'import du fichier CSV. V\u00E9rifiez l'en-t\u00EAte du fichier \: [ NAVS_COD,CARN_NOM,CARN_LONGUEUR_HT,CARN_ANNEE,QUARTIER_IMMA,PER_COD,PER_NOM,PER_PRENOM,NAVS_ACTIVE ]. Voir documentation pour plus de d\u00E9tails. +wao.error.serviceCartography.importBoatDistrictKml= wao.error.serviceContact.exportContactCsv=Impossible d'exporter les contacts wao.error.serviceContact.getContacts=Impossible de filtrer la liste des contacts wao.error.serviceContact.getNbContacts=Impossible de compter le nombre de contacts filtr\u00E9s Modified: trunk/wao-business/src/main/xmi/wao.zargo =================================================================== (Binary files differ) Modified: trunk/wao-business/src/test/java/fr/ifremer/wao/TestManager.java =================================================================== --- trunk/wao-business/src/test/java/fr/ifremer/wao/TestManager.java 2010-06-29 14:20:31 UTC (rev 580) +++ trunk/wao-business/src/test/java/fr/ifremer/wao/TestManager.java 2010-06-30 10:54:53 UTC (rev 581) @@ -27,6 +27,7 @@ import fr.ifremer.wao.service.ServiceBoat; import fr.ifremer.wao.service.ServiceBoatImpl; +import fr.ifremer.wao.service.ServiceCartographyImpl; import fr.ifremer.wao.service.ServiceContact; import fr.ifremer.wao.service.ServiceContactImpl; import fr.ifremer.wao.service.ServiceNews; @@ -160,38 +161,10 @@ return instance; } -// public void prepareData() throws WaoExceptionO { -// ServiceBoat serviceBoat = new ServiceBoatImpl(); -// ServiceReferential serviceReferential = new ServiceReferentialImpl(); -// ServiceUser serviceUser = new ServiceUserImpl(); -// ServiceSampling serviceSampling = new ServiceSamplingImpl(); -// ServiceContact serviceContact = new ServiceContactImpl(); -// -// Company company = new CompanyImpl(); -// company.setName("TARTANPION"); -// company.setActive(true); -// serviceUser.createUpdateCompany(company); -// -// WaoUser observer = new WaoUserImpl(); -// observer.setCompany(company); -// observer.setFirstName("Jean"); -// observer.setLastName("Michmuche"); -// observer.setLogin("jmichmuche"); -// observer.setActive(true); -// serviceUser.createUpdateUser(observer, true); -// -// InputStream input = getClass().getResourceAsStream("/import/navires.csv"); -// serviceBoat.importBoatCsv(input); -// -// input = getClass().getResourceAsStream("/import/zonesPeche.csv"); -// serviceReferential.importFishingZoneCsv(input); -// -// input = getClass().getResourceAsStream("/import/echantillonnage.csv"); -// serviceSampling.importSamplingPlanCsv(input); -// -// input = getClass().getResourceAsStream("/import/contacts.csv"); -// // user import : no activation -// serviceContact.importContactCsv(observer, input); -// } + public ServiceCartographyImpl getServiceCartography() { + ServiceCartographyImpl instance = new ServiceCartographyImpl(); + instance.setContext(getContext()); + return instance; + } } Modified: trunk/wao-business/src/test/java/fr/ifremer/wao/io/ImportHelperTest.java =================================================================== --- trunk/wao-business/src/test/java/fr/ifremer/wao/io/ImportHelperTest.java 2010-06-29 14:20:31 UTC (rev 580) +++ trunk/wao-business/src/test/java/fr/ifremer/wao/io/ImportHelperTest.java 2010-06-30 10:54:53 UTC (rev 581) @@ -27,13 +27,13 @@ import fr.ifremer.wao.*; import com.csvreader.CsvReader; -import fr.ifremer.wao.io.WaoCsvHeader.CONTACT; -import fr.ifremer.wao.io.WaoCsvHeader.DatedHeader; -import fr.ifremer.wao.io.WaoCsvHeader.SAMPLING; +import fr.ifremer.wao.io.csv.ImportHelper; +import fr.ifremer.wao.io.csv.WaoCsvHeader.CONTACT; +import fr.ifremer.wao.io.csv.WaoCsvHeader.DatedHeader; +import fr.ifremer.wao.io.csv.WaoCsvHeader.SAMPLING; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; -import java.text.DateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; Added: trunk/wao-business/src/test/java/fr/ifremer/wao/service/ServiceCartographyImplTest.java =================================================================== --- trunk/wao-business/src/test/java/fr/ifremer/wao/service/ServiceCartographyImplTest.java (rev 0) +++ trunk/wao-business/src/test/java/fr/ifremer/wao/service/ServiceCartographyImplTest.java 2010-06-30 10:54:53 UTC (rev 581) @@ -0,0 +1,91 @@ +package fr.ifremer.wao.service; + +import fr.ifremer.wao.AbstractServiceTest; +import fr.ifremer.wao.WaoBusinessException; +import fr.ifremer.wao.WaoDAOHelper; +import fr.ifremer.wao.entity.BoatDistrict; +import fr.ifremer.wao.entity.BoatDistrictDAO; +import fr.ifremer.wao.io.ImportResults; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.nuiton.topia.TopiaContext; +import org.nuiton.topia.TopiaException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.InputStream; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * Created: 30 juin 2010 + * + * @author fdesbois <fdesbois at codelutin.com> + * @version $Id$ + */ +public class ServiceCartographyImplTest extends AbstractServiceTest { + + private static final Logger logger = + LoggerFactory.getLogger(ServiceCartographyImplTest.class); + + private ServiceCartography service; + + @Before + public void initialize() { + logger.info("initialize ServiceCartographyImplTest"); + service = manager.getServiceCartography(); + } + + @Test + public void testImportBoatDistrictKml() + throws WaoBusinessException, TopiaException { + + /** PREPARE DATA **/ + InputStream input = getClass().getResourceAsStream("/import/navires.csv"); + manager.getServiceBoat().importBoatCsv(input); + + /** EXEC METHOD **/ + input = getClass().getResourceAsStream("/import/boat_districts.kml"); + ImportResults results = service.importBoatDistrictKml(input); + Assert.assertEquals(3, results.getNbRowsImported()); + Assert.assertEquals(0, results.getNbRowsRefused()); + + /** CHECK RESULT DATA **/ + TopiaContext transaction = manager.getContext().beginTransaction(); + BoatDistrictDAO dao = WaoDAOHelper.getBoatDistrictDAO(transaction); + try { + + List<BoatDistrict> districts = dao.findAll(); + Assert.assertEquals(3, districts.size()); + + Set<String> codes = new HashSet<String>(); + for (BoatDistrict district : districts) { + codes.add(district.getCode()); + + Assert.assertNotNull(district.getLatitude()); + Assert.assertNotNull(district.getLongitude()); + Assert.assertNotNull(district.getName()); + } + + Assert.assertTrue(codes.contains("UN")); + Assert.assertTrue(codes.contains("UX")); + Assert.assertTrue(codes.contains("CI")); + + } finally { + transaction.closeContext(); + } + } + + //@Test + public void testImportBoatDistrictBadKml() throws WaoBusinessException { + /** PREPARE DATA **/ + InputStream input = getClass().getResourceAsStream("/import/navires.csv"); + manager.getServiceBoat().importBoatCsv(input); + + /** EXEC METHOD **/ + input = getClass().getResourceAsStream("/import/activity.csv"); + ImportResults results = service.importBoatDistrictKml(input); + } +} Modified: trunk/wao-business/src/test/java/fr/ifremer/wao/service/ServiceContactInternalTest.java =================================================================== --- trunk/wao-business/src/test/java/fr/ifremer/wao/service/ServiceContactInternalTest.java 2010-06-29 14:20:31 UTC (rev 580) +++ trunk/wao-business/src/test/java/fr/ifremer/wao/service/ServiceContactInternalTest.java 2010-06-30 10:54:53 UTC (rev 581) @@ -28,7 +28,7 @@ import fr.ifremer.wao.WaoDAOHelper; import fr.ifremer.wao.bean.ConnectedUser; import fr.ifremer.wao.bean.ContactState; -import fr.ifremer.wao.bean.ImportResults; +import fr.ifremer.wao.bean.ContactStatus.NullSampleMonthException; import fr.ifremer.wao.bean.UserRole; import fr.ifremer.wao.entity.Boat; import fr.ifremer.wao.entity.BoatDAO; @@ -44,15 +44,10 @@ import fr.ifremer.wao.entity.WaoUserDAO; import fr.ifremer.wao.io.ContactInput; import fr.ifremer.wao.io.ImportRefusedException; -import fr.ifremer.wao.io.WaoCsvHeader.BOAT; -import fr.ifremer.wao.io.WaoCsvHeader.CONTACT; -import fr.ifremer.wao.io.WaoCsvHeader.SAMPLING; -import fr.ifremer.wao.bean.ContactStatus.NullSampleMonthException; -import java.io.IOException; -import java.io.InputStream; -import java.text.ParseException; -import java.util.Date; -import java.util.List; +import fr.ifremer.wao.io.ImportResults; +import fr.ifremer.wao.io.csv.WaoCsvHeader.BOAT; +import fr.ifremer.wao.io.csv.WaoCsvHeader.CONTACT; +import fr.ifremer.wao.io.csv.WaoCsvHeader.SAMPLING; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; @@ -65,9 +60,20 @@ import org.nuiton.util.DateUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static org.mockito.Mockito.*; -import static org.junit.Assert.*; +import java.io.IOException; +import java.io.InputStream; +import java.text.ParseException; +import java.util.Date; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + /** * ServiceContactImplTest * Modified: trunk/wao-business/src/test/java/fr/ifremer/wao/service/ServiceSamplingImplTest.java =================================================================== --- trunk/wao-business/src/test/java/fr/ifremer/wao/service/ServiceSamplingImplTest.java 2010-06-29 14:20:31 UTC (rev 580) +++ trunk/wao-business/src/test/java/fr/ifremer/wao/service/ServiceSamplingImplTest.java 2010-06-30 10:54:53 UTC (rev 581) @@ -29,10 +29,9 @@ import fr.ifremer.wao.WaoBusinessException; import fr.ifremer.wao.WaoDAOHelper; import fr.ifremer.wao.WaoException; -import fr.ifremer.wao.bean.ImportResults; +import fr.ifremer.wao.bean.FacadeRow; import fr.ifremer.wao.bean.SamplingFilter; import fr.ifremer.wao.bean.SamplingFilterImpl; -import fr.ifremer.wao.bean.FacadeRow; import fr.ifremer.wao.entity.Boat; import fr.ifremer.wao.entity.Company; import fr.ifremer.wao.entity.CompanyDAO; @@ -48,13 +47,7 @@ import fr.ifremer.wao.entity.SampleRow; import fr.ifremer.wao.entity.SampleRowDAO; import fr.ifremer.wao.entity.SampleRowLogImpl; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collection; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.List; +import fr.ifremer.wao.io.ImportResults; import org.junit.Assert; import org.junit.Test; import org.nuiton.topia.TopiaContext; @@ -63,8 +56,20 @@ import org.nuiton.util.PeriodDates; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static org.junit.Assert.*; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collection; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertNull; + /** * ServiceSamplingImplTest * Added: trunk/wao-business/src/test/resources/import/boat_districts.kml =================================================================== --- trunk/wao-business/src/test/resources/import/boat_districts.kml (rev 0) +++ trunk/wao-business/src/test/resources/import/boat_districts.kml 2010-06-30 10:54:53 UTC (rev 581) @@ -0,0 +1,78 @@ +<?xml version="1.0" encoding="utf-8" ?> +<kml xmlns="http://www.opengis.net/kml/2.2"> + <Document> + <Folder> + <name>IFR_SIH_QUARTIER_MAR_PT</name> + <Schema name="IFR_SIH_QUARTIER_MAR_PT" id="IFR_SIH_QUARTIER_MAR_PT"> + <SimpleField name="Name" type="string"></SimpleField> + <SimpleField name="Description" type="string"></SimpleField> + <SimpleField name="OBJECTID" type="int"></SimpleField> + <SimpleField name="LIEU_LIB" type="string"></SimpleField> + <SimpleField name="LIEU_COD" type="string"></SimpleField> + <SimpleField name="TLIEU_COD" type="int"></SimpleField> + <SimpleField name="L_OCEAN" type="string"></SimpleField> + <SimpleField name="L_PAYS" type="string"></SimpleField> + </Schema> + <Placemark> + <name>34</name> + <description>Sete</description> + <ExtendedData> + <SchemaData schemaUrl="#IFR_SIH_QUARTIER_MAR_PT"> + <SimpleData name="Name">2</SimpleData> + <SimpleData name="Description">Unio</SimpleData> + <SimpleData name="OBJECTID">UN</SimpleData> + <SimpleData name="LIEU_LIB">13</SimpleData> + <SimpleData name="LIEU_COD">ME</SimpleData> + <SimpleData name="TLIEU_COD">FRA</SimpleData> + <SimpleData name="L_OCEAN">0</SimpleData> + <SimpleData name="L_PAYS">POINT</SimpleData> + </SchemaData> + </ExtendedData> + <Point> + <coordinates>3.697544304924308,43.400978635376085 + </coordinates> + </Point> + </Placemark> + <Placemark> + <name>30</name> + <description>Martigues</description> + <ExtendedData> + <SchemaData schemaUrl="#IFR_SIH_QUARTIER_MAR_PT"> + <SimpleData name="Name">30</SimpleData> + <SimpleData name="Description">Uxirgue</SimpleData> + <SimpleData name="OBJECTID">UX</SimpleData> + <SimpleData name="LIEU_LIB">13</SimpleData> + <SimpleData name="LIEU_COD">ME</SimpleData> + <SimpleData name="TLIEU_COD">FRA</SimpleData> + <SimpleData name="L_OCEAN">1</SimpleData> + <SimpleData name="L_PAYS">POINT</SimpleData> + </SchemaData> + </ExtendedData> + <Point> + <coordinates>5.05084975227851,43.405830559005189 + </coordinates> + </Point> + </Placemark> + <Placemark> + <name>29</name> + <description>Marseille</description> + <ExtendedData> + <SchemaData schemaUrl="#IFR_SIH_QUARTIER_MAR_PT"> + <SimpleData name="Name">29</SimpleData> + <SimpleData name="Description">Civik</SimpleData> + <SimpleData name="OBJECTID">CI</SimpleData> + <SimpleData name="LIEU_LIB">13</SimpleData> + <SimpleData name="LIEU_COD">ME</SimpleData> + <SimpleData name="TLIEU_COD">FRA</SimpleData> + <SimpleData name="L_OCEAN">2</SimpleData> + <SimpleData name="L_PAYS">POINT</SimpleData> + </SchemaData> + </ExtendedData> + <Point> + <coordinates>5.351948092148461,43.323330380088101 + </coordinates> + </Point> + </Placemark> + </Folder> + </Document> +</kml> Modified: trunk/wao-business/src/test/resources/log4j.properties =================================================================== --- trunk/wao-business/src/test/resources/log4j.properties 2010-06-29 14:20:31 UTC (rev 580) +++ trunk/wao-business/src/test/resources/log4j.properties 2010-06-30 10:54:53 UTC (rev 581) @@ -8,6 +8,6 @@ log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=%d [%p] %c{2} %m%n -log4j.logger.fr.ifremer.wao=INFO +log4j.logger.fr.ifremer.wao=DEBUG log4j.logger.org.nuiton.util=INFO log4j.logger.org.nuiton.util.beans.BinderProvider=ERROR Modified: trunk/wao-ui/src/main/java/fr/ifremer/wao/ui/components/CsvImport.java =================================================================== --- trunk/wao-ui/src/main/java/fr/ifremer/wao/ui/components/CsvImport.java 2010-06-29 14:20:31 UTC (rev 580) +++ trunk/wao-ui/src/main/java/fr/ifremer/wao/ui/components/CsvImport.java 2010-06-30 10:54:53 UTC (rev 581) @@ -23,7 +23,7 @@ import fr.ifremer.wao.WaoBusinessException; import fr.ifremer.wao.WaoException; -import fr.ifremer.wao.bean.ImportResults; +import fr.ifremer.wao.io.ImportResults; import fr.ifremer.wao.ui.data.ErrorReport; import fr.ifremer.wao.ui.data.ImportEngine; import fr.ifremer.wao.ui.services.WaoManager; Modified: trunk/wao-ui/src/main/java/fr/ifremer/wao/ui/data/ImportEngine.java =================================================================== --- trunk/wao-ui/src/main/java/fr/ifremer/wao/ui/data/ImportEngine.java 2010-06-29 14:20:31 UTC (rev 580) +++ trunk/wao-ui/src/main/java/fr/ifremer/wao/ui/data/ImportEngine.java 2010-06-30 10:54:53 UTC (rev 581) @@ -23,7 +23,7 @@ import fr.ifremer.wao.WaoBusinessException; import fr.ifremer.wao.WaoException; -import fr.ifremer.wao.bean.ImportResults; +import fr.ifremer.wao.io.ImportResults; import fr.ifremer.wao.ui.components.CsvImport; import fr.ifremer.wao.ui.components.Layout; Modified: trunk/wao-ui/src/main/java/fr/ifremer/wao/ui/pages/Administration.java =================================================================== --- trunk/wao-ui/src/main/java/fr/ifremer/wao/ui/pages/Administration.java 2010-06-29 14:20:31 UTC (rev 580) +++ trunk/wao-ui/src/main/java/fr/ifremer/wao/ui/pages/Administration.java 2010-06-30 10:54:53 UTC (rev 581) @@ -30,8 +30,8 @@ import fr.ifremer.wao.WaoException; import fr.ifremer.wao.WaoProperty; import fr.ifremer.wao.bean.ConnectedUser; -import fr.ifremer.wao.bean.ImportResults; -import fr.ifremer.wao.bean.ImportResultsImpl; +import fr.ifremer.wao.io.ImportResults; +import fr.ifremer.wao.io.ImportResultsImpl; import fr.ifremer.wao.bean.UserRole; import fr.ifremer.wao.entity.Company; import fr.ifremer.wao.entity.CompanyImpl; @@ -48,18 +48,15 @@ import fr.ifremer.wao.ui.services.WaoManager; import java.io.FileNotFoundException; -import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; -import java.util.zip.GZIPInputStream; import org.apache.commons.lang.StringUtils; import org.apache.tapestry5.EventContext; import org.apache.tapestry5.OptionModel; import org.apache.tapestry5.RenderSupport; import org.apache.tapestry5.SelectModel; -import org.apache.tapestry5.StreamResponse; import org.apache.tapestry5.annotations.Environmental; import org.apache.tapestry5.annotations.IncludeJavaScriptLibrary; import org.apache.tapestry5.annotations.IncludeStylesheet; @@ -78,8 +75,6 @@ import org.apache.tapestry5.ioc.services.PropertyAccess; import org.apache.tapestry5.ioc.services.TypeCoercer; import org.apache.tapestry5.services.BeanModelSource; -import org.apache.tapestry5.services.Response; -import org.apache.tapestry5.upload.services.UploadedFile; import org.slf4j.Logger; /** Modified: trunk/wao-ui/src/main/java/fr/ifremer/wao/ui/pages/Contacts.java =================================================================== --- trunk/wao-ui/src/main/java/fr/ifremer/wao/ui/pages/Contacts.java 2010-06-29 14:20:31 UTC (rev 580) +++ trunk/wao-ui/src/main/java/fr/ifremer/wao/ui/pages/Contacts.java 2010-06-30 10:54:53 UTC (rev 581) @@ -31,7 +31,7 @@ import fr.ifremer.wao.bean.ContactFilter; import fr.ifremer.wao.bean.ContactFilterImpl; import fr.ifremer.wao.bean.ContactState; -import fr.ifremer.wao.bean.ImportResults; +import fr.ifremer.wao.io.ImportResults; import fr.ifremer.wao.bean.SamplingFilter; import fr.ifremer.wao.bean.UserRole; import fr.ifremer.wao.entity.Boat; Modified: trunk/wao-ui/src/main/java/fr/ifremer/wao/ui/pages/SamplingPlan.java =================================================================== --- trunk/wao-ui/src/main/java/fr/ifremer/wao/ui/pages/SamplingPlan.java 2010-06-29 14:20:31 UTC (rev 580) +++ trunk/wao-ui/src/main/java/fr/ifremer/wao/ui/pages/SamplingPlan.java 2010-06-30 10:54:53 UTC (rev 581) @@ -29,7 +29,7 @@ import fr.ifremer.wao.WaoException; import fr.ifremer.wao.bean.ConnectedUser; import fr.ifremer.wao.bean.FacadeRow; -import fr.ifremer.wao.bean.ImportResults; +import fr.ifremer.wao.io.ImportResults; import fr.ifremer.wao.bean.SamplingFilter; import fr.ifremer.wao.bean.SamplingFilterImpl; import fr.ifremer.wao.entity.FishingZone;
participants (1)
-
fdesbois@users.labs.libre-entreprise.org