Author: fdesbois Date: 2010-02-11 20:04:33 +0000 (Thu, 11 Feb 2010) New Revision: 346 Added: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/io/ trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/io/ExportHelper.java trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/io/ImportHelper.java trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/io/SamplingExport.java trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/io/WaoCsvHeader.java Removed: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/ImportHelper.java Modified: trunk/changelog.txt trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ActivityCalendarImport.java trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceBoatImpl.java trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceContactImpl.java trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceReferentialImpl.java trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceSamplingImpl.java trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceSynthesisImpl.java trunk/suiviobsmer-business/src/main/xmi/suiviobsmer.zargo trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/ImportHelperTest.java trunk/suiviobsmer-ui/src/main/java/fr/ifremer/suiviobsmer/ui/pages/Boats.java trunk/suiviobsmer-ui/src/main/java/fr/ifremer/suiviobsmer/ui/pages/SamplingPlan.java trunk/suiviobsmer-ui/src/main/resources/fr/ifremer/suiviobsmer/ui/pages/Boats.properties trunk/suiviobsmer-ui/src/main/webapp/SamplingPlan.tml Log: - Evo #2022 : Export SamplingPlan - Improve import/export : new ExportHelper abstract class + new io package + headers enumerations put in WaoCsvHeader class. Of course ImportHelper has less methods now. - Note : correction of query for boats export Modified: trunk/changelog.txt =================================================================== --- trunk/changelog.txt 2010-02-10 22:04:27 UTC (rev 345) +++ trunk/changelog.txt 2010-02-11 20:04:33 UTC (rev 346) @@ -9,6 +9,8 @@ Evolutions ++++++++++ +- [fdesbois] Evo #2022 : Plan d'échantillonnage : Export CSV +- [fdesbois] Evo #1986 : Synthèse : indicateur sur les états des contacts - [fdesbois] Evo #1984 : Synthèse : indicateur de non respect du nombre d'observateurs embarqués - [fdesbois] Evo #2092 : Contacts : Ajouter filtres sur les validations du Deleted: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/ImportHelper.java =================================================================== --- trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/ImportHelper.java 2010-02-10 22:04:27 UTC (rev 345) +++ trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/ImportHelper.java 2010-02-11 20:04:33 UTC (rev 346) @@ -1,564 +0,0 @@ -/* - * *##% - * SuiviObsmer :: Business - * 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 Lesser 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>. - * ##%* - */ - -package fr.ifremer.suiviobsmer; - -import com.csvreader.CsvReader; -import java.io.IOException; -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.Locale; -import org.apache.commons.lang.BooleanUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.time.DurationFormatUtils; -import org.nuiton.util.PeriodDates; -import org.slf4j.Logger; - -/** - * ImportHelper - * - * Created: 4 janv. 2010 - * - * @author fdesbois - * @version $Revision$ - * - * Mise a jour: $Date$ - * par : $Author$ - */ -public class ImportHelper { - - public interface ImportHeader { - - int forContactCsv(); - - String name(); - - /** - * 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(); - } - - /** - * CSV headers for Boat - */ - public enum BOAT implements ImportHeader { - /** 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; - } - - BOAT() { - contactHeader = -1; - boatHeader = -1; - title = name(); - } - - @Override - public int forContactCsv() { - return contactHeader; - } - - public int forBoatCsv() { - return boatHeader; - } - - @Override - public String datePattern() { - return null; - } - - @Override - public String toString() { - return title; - } - } - - /** - * CSV headers for SamplingPlan - */ - public enum SAMPLING implements ImportHeader { - /** SampleRow code **/ - PLAN_CODE(6), - /** Company name **/ - SOCIETE_NOM(5), - /** Program code **/ - PROGRAMME_CODE(7), - /** Program period begin **/ - PROGRAMME_DEBUT(8), - /** Program period end **/ - PROGRAMME_FIN(9), - /** FishingZone other infos **/ - PECHE_AUTRE(13), - /** Profession code DCF5 **/ - METIER_CODE_DCF5(14), - /** Profession mesh size **/ - METIER_MAILLAGE(15), - /** Profession size **/ - METIER_TAILLE(16), - /** Profession other infos **/ - METIER_AUTRE(17), - /** Profession libelle **/ - METIER_LIBELLE(18), - /** Profession species **/ - METIER_ESPECES(19), - /** SampleRow nb observants **/ - PLAN_NB_OBSERV, - /** SampleRow average tide time **/ - PLAN_DUREE_MOY, - /** SampleRow comment **/ - PLAN_COMMENT; - - private int contactHeader; - - SAMPLING(int index) { - this.contactHeader = index; - } - - SAMPLING() { - this.contactHeader = -1; - } - - @Override - public int forContactCsv() { - return contactHeader; - } - - @Override - public String datePattern() { - return defaultDatePattern(); - } - - public static String defaultDatePattern() { - return "MM/yyyy"; - } - } - - /** - * CSV headers for FishingZone - */ - public enum FISHING_ZONE implements ImportHeader { - /** FishingZone facade **/ - PECHE_FACADE(10), - /** FishingZone sector **/ - PECHE_ZONE(11), - /** FishingZone district code **/ - PECHE_DIVISION(12); - - private int contactHeader; - - FISHING_ZONE(int index) { - this.contactHeader = index; - } - - @Override - public int forContactCsv() { - return contactHeader; - } - - @Override - public String datePattern() { - return null; - } - } - - /** - * CSV headers for Contact - */ - public enum CONTACT implements ImportHeader { - /** 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; - - CONTACT(int index) { - this.contactHeader = index; - } - - @Override - public int forContactCsv() { - return contactHeader; - } - - @Override - public String datePattern() { - return "dd/MM/yyyy"; - } - } - - public enum ACTIVITY_CALENDAR implements ImportHeader { - /** 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; - - @Override - public int forContactCsv() { - return -1; - } - - @Override - public String datePattern() { - return ""; - } - } - - public static final int CONTACT_NB_HEADERS = 33; - - public static final int BOAT_NB_HEADERS = 12; - - public static final String BOAT_INACTIVE_CODE = "I"; - - 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 String formatContactValidation(Boolean validation) { - String valid = ""; - if (validation == null) { - valid = "N"; - } else if (BooleanUtils.isTrue(validation)) { - valid = "A"; - } else { - valid = "R"; - } - return valid; - } - - public static Boolean parseContactValidation(CsvReader reader, ImportHeader 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 String formatContactMammals(boolean mammals) { - return mammals ? "X" : ""; - } - - public static boolean parseContactMammals(CsvReader reader, ImportHeader header) throws IOException { - String mammals = read(reader, header); - return "X".equals(mammals); - } - - protected static String CONTACT_TIME_PATTERN = "HHmmssS"; - - protected static String CONTACT_DATE_PATTERN = "dd/MM/yyyy"; - - public static String formatContactCode(Date createDate) { - DateFormat timeFormat = new SimpleDateFormat(CONTACT_TIME_PATTERN, Locale.FRENCH); - String result = timeFormat.format(createDate); - return result; - } - - public static Date parseContactCreateDate(String code, String createDate) throws ParseException { - Calendar time = new GregorianCalendar(Locale.FRENCH); - if (StringUtils.isNotEmpty(code)) { - DateFormat timeFormat = new SimpleDateFormat(CONTACT_TIME_PATTERN, Locale.FRENCH); - time = new GregorianCalendar(Locale.FRENCH); - time.setTime(timeFormat.parse(code)); - } else { - // Use current date with no time as a reference if no code is set - time.setTime(SuiviObsmerContext.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 (StringUtils.isNotEmpty(createDate)) { - DateFormat dateFormat = getContactDateFormat(); - result.setTime(dateFormat.parse(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(SuiviObsmerContext.getCurrentDate()); - } - return result.getTime(); - } - - public static String readSampleRowCode(CsvReader reader) throws IOException { - String code = read(reader, SAMPLING.PLAN_CODE); - return SuiviObsmerContext.prepareSampleRowCode(code); - } - - public static DateFormat getContactDateFormat() { - return new SimpleDateFormat(CONTACT_DATE_PATTERN, Locale.FRENCH); - } - - 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(); - } - - /** - * 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, ImportHeader 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, ImportHeader) - */ - public static int readInt(CsvReader reader, ImportHeader 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, ImportHeader) - */ - public static Integer readInteger(CsvReader reader, ImportHeader 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 ImportHelper#readDate(CsvReader, ImportHeader) - */ - public static PeriodDates readPeriod(CsvReader reader, ImportHeader headerBegin, ImportHeader 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, ImportHeader) - */ - public static Date readDate(CsvReader reader, ImportHeader header) - throws IOException, ParseException { - DateFormat dateFormat = new SimpleDateFormat(header.datePattern()); - String str = read(reader, header); - if (StringUtils.isEmpty(str)) { - return null; - } - // Parsing problem with Pattern dd/MM/yyyy which is valid for dd/MM/yy date - // The length is tested to avoid accepting wrong dates - if (str.length() != header.datePattern().length()) { - throw new ParseException("Date error : " + str, str.length()); - } - return dateFormat.parse(str); - } - -} Added: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/io/ExportHelper.java =================================================================== --- trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/io/ExportHelper.java (rev 0) +++ trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/io/ExportHelper.java 2010-02-11 20:04:33 UTC (rev 346) @@ -0,0 +1,125 @@ + +package fr.ifremer.suiviobsmer.io; + +import com.csvreader.CsvWriter; +import fr.ifremer.suiviobsmer.io.WaoCsvHeader.IOHeader; +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 + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ +public abstract class ExportHelper<H extends IOHeader> { + + /** 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 WaoCsvReader } 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 WaoCsvReader } 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++) { + 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(); + } +} Property changes on: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/io/ExportHelper.java ___________________________________________________________________ Added: svn:keywords + "Author Date Id Revision HeadURL" Copied: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/io/ImportHelper.java (from rev 338, trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/ImportHelper.java) =================================================================== --- trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/io/ImportHelper.java (rev 0) +++ trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/io/ImportHelper.java 2010-02-11 20:04:33 UTC (rev 346) @@ -0,0 +1,225 @@ +/* + * *##% + * SuiviObsmer :: Business + * 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 Lesser 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>. + * ##%* + */ + +package fr.ifremer.suiviobsmer.io; + +import fr.ifremer.suiviobsmer.*; +import com.csvreader.CsvReader; +import fr.ifremer.suiviobsmer.io.WaoCsvHeader.ACTIVITY_CALENDAR; +import fr.ifremer.suiviobsmer.io.WaoCsvHeader.CONTACT; +import fr.ifremer.suiviobsmer.io.WaoCsvHeader.DatedHeader; +import fr.ifremer.suiviobsmer.io.WaoCsvHeader.IOHeader; +import fr.ifremer.suiviobsmer.io.WaoCsvHeader.SAMPLING; +import fr.ifremer.suiviobsmer.io.WaoCsvHeader.SamplingHeader; +import java.io.IOException; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.Locale; +import org.apache.commons.lang.BooleanUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.time.DurationFormatUtils; +import org.nuiton.util.PeriodDates; +import org.slf4j.Logger; + +/** + * ImportHelper + * + * Created: 4 janv. 2010 + * + * @author fdesbois + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ +public class ImportHelper { + + protected CsvReader reader; + + public ImportHelper(CsvReader reader) { + this.reader = reader; + } + + 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, String createDate) throws ParseException { + Calendar time = new GregorianCalendar(Locale.FRENCH); + if (StringUtils.isNotEmpty(code)) { + DateFormat timeFormat = CONTACT.getTimeFormat(); + time = new GregorianCalendar(Locale.FRENCH); + time.setTime(timeFormat.parse(code)); + } else { + // Use current date with no time as a reference if no code is set + time.setTime(SuiviObsmerContext.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 (StringUtils.isNotEmpty(createDate)) { + DateFormat dateFormat = CONTACT.getDateFormat(); + result.setTime(dateFormat.parse(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(SuiviObsmerContext.getCurrentDate()); + } + return result.getTime(); + } + + public static String readSampleRowCode(CsvReader reader) throws IOException { + String code = read(reader, SAMPLING.PLAN_CODE); + return SuiviObsmerContext.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 ImportHelper#readDate(CsvReader, IOHeader) + */ + 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) + */ + public static Date readDate(CsvReader reader, DatedHeader header) + throws IOException, ParseException { + DateFormat dateFormat = new SimpleDateFormat(header.datePattern()); + String str = read(reader, header); + if (StringUtils.isEmpty(str)) { + return null; + } + // Parsing problem with Pattern dd/MM/yyyy which is valid for dd/MM/yy date + // The length is tested to avoid accepting wrong dates + if (str.length() != header.datePattern().length()) { + throw new ParseException("Date error : " + str, str.length()); + } + return dateFormat.parse(str); + } + + 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(); + } + +} Property changes on: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/io/ImportHelper.java ___________________________________________________________________ Added: svn:keywords + "Author Date Id Revision HeadURL" Added: svn:mergeinfo + Added: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/io/SamplingExport.java =================================================================== --- trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/io/SamplingExport.java (rev 0) +++ trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/io/SamplingExport.java 2010-02-11 20:04:33 UTC (rev 346) @@ -0,0 +1,103 @@ + +package fr.ifremer.suiviobsmer.io; + +import com.csvreader.CsvWriter; +import fr.ifremer.suiviobsmer.entity.SampleMonth; +import fr.ifremer.suiviobsmer.entity.SampleRow; +import fr.ifremer.suiviobsmer.entity.WaoUser; +import fr.ifremer.suiviobsmer.io.WaoCsvHeader.SAMPLING; +import fr.ifremer.suiviobsmer.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 + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ +public class SamplingExport extends ExportHelper<SamplingHeader> { + + private static final Logger log = LoggerFactory.getLogger(SamplingExport.class); + + protected WaoUser 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, WaoUser 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.getAdmin() ? 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) + if (user.getAdmin()) { + record(index, expected); //record[index] = expected; + // The user as both expected and real values + } else { + record(index, expected + " (" + real + ")"); + } + } + } + } + +} Property changes on: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/io/SamplingExport.java ___________________________________________________________________ Added: svn:keywords + "Author Date Id Revision HeadURL" Added: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/io/WaoCsvHeader.java =================================================================== --- trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/io/WaoCsvHeader.java (rev 0) +++ trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/io/WaoCsvHeader.java 2010-02-11 20:04:33 UTC (rev 346) @@ -0,0 +1,451 @@ + +package fr.ifremer.suiviobsmer.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 + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ +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() { + // PROGRAMME_FIN is the last column before months + return PROGRAMME_FIN.forSamplingCsv() + 1; + } + + public static int getTotalHeaders() { + // PLAN_COMMENT is the last column + return PLAN_COMMENT.forSamplingCsv() + 1; + } + } + + /** + * 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; + + 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 DateFormat getDateFormat() { + return new SimpleDateFormat(defaultDatePattern(), Locale.FRENCH); + } + + public static DateFormat getTimeFormat() { + return new SimpleDateFormat("HHmmssS", Locale.FRENCH); + } + + 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; + } +} Property changes on: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/io/WaoCsvHeader.java ___________________________________________________________________ Added: svn:keywords + "Author Date Id Revision HeadURL" Modified: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ActivityCalendarImport.java =================================================================== --- trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ActivityCalendarImport.java 2010-02-10 22:04:27 UTC (rev 345) +++ trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ActivityCalendarImport.java 2010-02-11 20:04:33 UTC (rev 346) @@ -23,8 +23,6 @@ import fr.ifremer.suiviobsmer.*; import com.csvreader.CsvReader; -import fr.ifremer.suiviobsmer.ImportHelper.ACTIVITY_CALENDAR; -import fr.ifremer.suiviobsmer.ImportHelper.BOAT; import fr.ifremer.suiviobsmer.entity.ActivityCalendar; import fr.ifremer.suiviobsmer.entity.ActivityCalendarDAO; import fr.ifremer.suiviobsmer.entity.ActivityMonth; @@ -35,6 +33,9 @@ import fr.ifremer.suiviobsmer.entity.ActivityZoneDAO; import fr.ifremer.suiviobsmer.entity.Boat; import fr.ifremer.suiviobsmer.entity.BoatDAO; +import fr.ifremer.suiviobsmer.io.ImportHelper; +import fr.ifremer.suiviobsmer.io.WaoCsvHeader.ACTIVITY_CALENDAR; +import fr.ifremer.suiviobsmer.io.WaoCsvHeader.BOAT; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; @@ -49,7 +50,6 @@ import java.util.HashMap; import java.util.Locale; import java.util.Map; -import java.util.logging.Level; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.time.DurationFormatUtils; import org.nuiton.topia.TopiaContext; Modified: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceBoatImpl.java =================================================================== --- trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceBoatImpl.java 2010-02-10 22:04:27 UTC (rev 345) +++ trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceBoatImpl.java 2010-02-11 20:04:33 UTC (rev 346) @@ -23,14 +23,11 @@ import com.csvreader.CsvReader; import com.csvreader.CsvWriter; -import fr.ifremer.suiviobsmer.ImportHelper; -import fr.ifremer.suiviobsmer.ImportHelper.BOAT; import fr.ifremer.suiviobsmer.SuiviObsmerBusinessException; import fr.ifremer.suiviobsmer.SuiviObsmerBusinessException.Type; import fr.ifremer.suiviobsmer.SuiviObsmerContext; import fr.ifremer.suiviobsmer.SuiviObsmerException; import fr.ifremer.suiviobsmer.SuiviObsmerModelDAOHelper; -import java.util.logging.Level; import org.nuiton.topia.TopiaException; import org.nuiton.topia.framework.TopiaQuery; import org.nuiton.topia.framework.TopiaQuery.Op; @@ -38,7 +35,10 @@ import fr.ifremer.suiviobsmer.bean.CompanyBoatInfos; import fr.ifremer.suiviobsmer.bean.CompanyBoatInfosImpl; import fr.ifremer.suiviobsmer.entity.*; -import fr.ifremer.suiviobsmer.services.ServiceBoat; +import fr.ifremer.suiviobsmer.io.ImportHelper; +import fr.ifremer.suiviobsmer.io.ExportHelper; +import fr.ifremer.suiviobsmer.io.WaoCsvHeader; +import fr.ifremer.suiviobsmer.io.WaoCsvHeader.BOAT; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; @@ -91,9 +91,9 @@ query = createQueryForBoatFilter(query, filter); - if (StringUtils.isNotEmpty(filter.getOrderBy())) { - query.addOrder("B." + filter.getOrderBy()); - } +// if (StringUtils.isNotEmpty(filter.getOrderBy())) { +// query.addOrder("B." + filter.getOrderBy()); +// } query.addLoad(Boat.ACTIVITY_CALENDAR); @@ -154,6 +154,10 @@ } } + if (StringUtils.isNotEmpty(filter.getOrderBy())) { + query.addOrder(main + "." + filter.getOrderBy()); + } + return query; } @@ -408,7 +412,7 @@ String shipOwnerFirstName = ImportHelper.read(reader, BOAT.PER_PRENOM); //String activeStr = reader.get(BOAT.NAVS_ACTIVE.name()).trim(); String activeStr = ImportHelper.read(reader, BOAT.NAVS_ACTIVE); - boolean active = !activeStr.equals(ImportHelper.BOAT_INACTIVE_CODE); + boolean active = !activeStr.equals(BOAT.getBoatInactiveCode()); if (log.isDebugEnabled()) { log.debug("Active : " + active + " (" + activeStr + ")"); @@ -484,7 +488,7 @@ @Override public InputStream exportBoatCsv(BoatFilter filter) throws SuiviObsmerException { - TopiaContext transaction = null; + TopiaContext transaction = null; InputStream result = null; CsvWriter writer = null; try { @@ -496,56 +500,62 @@ FileOutputStream output = new FileOutputStream(file); writer = new CsvWriter(output, ',', Charset.forName("UTF-8")); - // Headers - for (int i = 0; i < ImportHelper.BOAT_NB_HEADERS; i++) { - String header = ImportHelper.getHeaderForBoatCsv(i); - if (log.isDebugEnabled()) { - log.debug("header : " + header); + ExportHelper<BOAT> export = new ExportHelper<BOAT>(writer, BOAT.getTotalHeaders()) { + @Override + public String getHeaderValue(int index) throws IOException { + return WaoCsvHeader.getHeaderForBoatCsv(index); } - writer.write(header); - } - writer.endRecord(); + @Override + public void record(BOAT header, String value) { + record(header.forBoatCsv(), value); + } + }; + + export.writeHeaders(); + // Get boats from database filterd by filter in argument BoatDAO dao = SuiviObsmerModelDAOHelper.getBoatDAO(transaction); TopiaQuery query = dao.createQuery("B"); - query = filter.prepareQueryForBoat(query, "B"); + query = createQueryForBoatFilter(query, filter); // Reset limit : no pagination needed for results query.resetLimit(); + + if (log.isDebugEnabled()) { + log.debug("Exec query : " + query); + } List<Boat> boats = dao.findAllByQuery(query); for (Boat boat : boats) { - String[] record = new String[ImportHelper.BOAT_NB_HEADERS]; + export.newRecord(); - if (log.isDebugEnabled()) { - log.debug("add boat : " + boat.getName() + " (" + boat.getImmatriculation() + ")"); + if (log.isTraceEnabled()) { + log.trace("add boat : " + boat.getName() + " (" + boat.getImmatriculation() + ")"); } - record[BOAT.NAVS_COD.forBoatCsv()] = String.valueOf(boat.getImmatriculation()); - record[BOAT.CARN_NOM.forBoatCsv()] = boat.getName(); - record[BOAT.CARN_LONGUEUR_HT.forBoatCsv()] = String.valueOf(boat.getBoatLength()); - record[BOAT.CARN_ANNEE.forBoatCsv()] = String.valueOf(boat.getBuildYear()); - record[BOAT.QUARTIER_IMMA.forBoatCsv()] = boat.getDistrictCode(); - record[BOAT.NAVS_ACTIVE.forBoatCsv()] = !boat.getActive() ? - ImportHelper.BOAT_INACTIVE_CODE : ""; + export.record(BOAT.NAVS_COD, String.valueOf(boat.getImmatriculation())); + export.record(BOAT.CARN_NOM, boat.getName()); + export.record(BOAT.CARN_LONGUEUR_HT, String.valueOf(boat.getBoatLength())); + export.record(BOAT.CARN_ANNEE, String.valueOf(boat.getBuildYear())); + export.record(BOAT.QUARTIER_IMMA, boat.getDistrictCode()); + export.record(BOAT.NAVS_ACTIVE, (!boat.getActive() ? BOAT.getBoatInactiveCode() : "")); if (filter.getCompany() != null) { BoatInfos boatInfos = boat.getCompanyBoatInfos(filter.getCompany()); if (boatInfos != null) { - record[BOAT.CONT_PRENOM.forBoatCsv()] = boatInfos.getContactFirstName(); - record[BOAT.CONT_NOM.forBoatCsv()] = boatInfos.getContactLastName(); - record[BOAT.CONT_EMAIL.forBoatCsv()] = boatInfos.getContactEmail(); - record[BOAT.CONT_TEL.forBoatCsv()] = boatInfos.getContactPhoneNumber(); - record[BOAT.NAVS_DUP.forBoatCsv()] = String.valueOf(boatInfos.getDup()); - record[BOAT.NAVS_COMMENT.forBoatCsv()] = boatInfos.getComment(); + export.record(BOAT.CONT_PRENOM, boatInfos.getContactFirstName()); + export.record(BOAT.CONT_NOM, boatInfos.getContactLastName()); + export.record(BOAT.CONT_EMAIL, boatInfos.getContactEmail()); + export.record(BOAT.CONT_TEL, boatInfos.getContactPhoneNumber()); + export.record(BOAT.NAVS_DUP, String.valueOf(boatInfos.getDup())); + export.record(BOAT.NAVS_COMMENT, boatInfos.getComment()); } } - writer.writeRecord(record); - writer.flush(); + export.writeRecord(); } result = new FileInputStream(file); Modified: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceContactImpl.java =================================================================== --- trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceContactImpl.java 2010-02-10 22:04:27 UTC (rev 345) +++ trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceContactImpl.java 2010-02-11 20:04:33 UTC (rev 346) @@ -23,8 +23,8 @@ import com.csvreader.CsvReader; import com.csvreader.CsvWriter; -import fr.ifremer.suiviobsmer.ImportHelper; -import fr.ifremer.suiviobsmer.ImportHelper.*; +import fr.ifremer.suiviobsmer.io.ImportHelper; +import fr.ifremer.suiviobsmer.io.ImportHelper.*; import fr.ifremer.suiviobsmer.SuiviObsmerBusinessException; import fr.ifremer.suiviobsmer.SuiviObsmerBusinessException.Type; import fr.ifremer.suiviobsmer.SuiviObsmerException; @@ -52,7 +52,13 @@ import fr.ifremer.suiviobsmer.entity.SampleRowDAO; import fr.ifremer.suiviobsmer.entity.WaoUser; import fr.ifremer.suiviobsmer.entity.WaoUserDAO; -import fr.ifremer.suiviobsmer.services.ServiceContact; +import fr.ifremer.suiviobsmer.io.ExportHelper; +import fr.ifremer.suiviobsmer.io.WaoCsvHeader; +import fr.ifremer.suiviobsmer.io.WaoCsvHeader.BOAT; +import fr.ifremer.suiviobsmer.io.WaoCsvHeader.CONTACT; +import fr.ifremer.suiviobsmer.io.WaoCsvHeader.ContactHeader; +import fr.ifremer.suiviobsmer.io.WaoCsvHeader.FISHING_ZONE; +import fr.ifremer.suiviobsmer.io.WaoCsvHeader.SAMPLING; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; @@ -205,19 +211,30 @@ FileOutputStream output = new FileOutputStream(file); writer = new CsvWriter(output, ',', Charset.forName("UTF-8")); - // Headers - for (int i = 0; i < ImportHelper.CONTACT_NB_HEADERS; i++) { - String header = ImportHelper.getHeaderForContactCsv(i); - writer.write(header); - } - writer.endRecord(); + ExportHelper<ContactHeader> export = new ExportHelper<ContactHeader>(writer, CONTACT.getTotalHeaders()) { + @Override + public void record(ContactHeader header, String value) { + record(header.forContactCsv(), value); + } + + @Override + protected String getHeaderValue(int index) throws IOException { + if (log.isDebugEnabled()) { + log.debug("record header : " + index + " = " + WaoCsvHeader.getHeaderForContactCsv(index)); + } + return WaoCsvHeader.getHeaderForContactCsv(index); + } + }; + + export.writeHeaders(); - DateFormat dateFormat = ImportHelper.getContactDateFormat(); + DateFormat dateFormat = CONTACT.getDateFormat(); // Get contacts from database ContactDAO dao = SuiviObsmerModelDAOHelper.getContactDAO(transaction); TopiaQuery query = dao.createQuery("C"); + query.addOrderDesc("C." + TopiaEntity.TOPIA_CREATE_DATE); // No page limit in this case query = filter.prepareQueryForContact(query).resetLimit(); @@ -228,77 +245,73 @@ List<Contact> contacts = dao.findAllByQuery(query); + DateFormat timeFormat = CONTACT.getTimeFormat(); + for (Contact contact : contacts) { - String[] record = new String[ImportHelper.CONTACT_NB_HEADERS]; + export.newRecord(); // Contact part - record[CONTACT.CONT_CODE.forContactCsv()] = ImportHelper.formatContactCode(contact.getTopiaCreateDate()); - record[CONTACT.CONT_CREATION.forContactCsv()] = dateFormat.format(contact.getTopiaCreateDate()); - record[CONTACT.CONT_ETAT.forContactCsv()] = contact.getState(); + export.record(CONTACT.CONT_CODE, timeFormat.format(contact.getTopiaCreateDate())); + export.record(CONTACT.CONT_CREATION, dateFormat.format(contact.getTopiaCreateDate())); + export.record(CONTACT.CONT_ETAT, contact.getState()); if (contact.getTideBeginDate() != null) { - record[CONTACT.CONT_DEBUT_MAREE.forContactCsv()] = dateFormat.format(contact.getTideBeginDate()); + export.record(CONTACT.CONT_DEBUT_MAREE, dateFormat.format(contact.getTideBeginDate())); } if (contact.getTideEndDate() != null) { - record[CONTACT.CONT_FIN_MAREE.forContactCsv()] = dateFormat.format(contact.getTideEndDate()); + export.record(CONTACT.CONT_FIN_MAREE, dateFormat.format(contact.getTideEndDate())); } - record[CONTACT.CONT_NB_OBSERV.forContactCsv()] = String.valueOf(contact.getNbObservants()); - record[CONTACT.CONT_MAM_CAPT.forContactCsv()] = - ImportHelper.formatContactMammals(contact.getMammalsCapture()); - record[CONTACT.CONT_MAM_OBS.forContactCsv()] = - ImportHelper.formatContactMammals(contact.getMammalsObservation()); - record[CONTACT.CONT_COMMENT.forContactCsv()] = contact.getComment(); + export.record(CONTACT.CONT_NB_OBSERV, String.valueOf(contact.getNbObservants())); + export.record(CONTACT.CONT_MAM_CAPT, CONTACT.formatMammals(contact.getMammalsCapture())); + export.record(CONTACT.CONT_MAM_OBS, CONTACT.formatMammals(contact.getMammalsObservation())); + export.record(CONTACT.CONT_COMMENT, contact.getComment()); if (contact.getDataInputDate() != null) { - record[CONTACT.CONT_ALLEGRO.forContactCsv()] = dateFormat.format(contact.getDataInputDate()); + export.record(CONTACT.CONT_ALLEGRO, dateFormat.format(contact.getDataInputDate())); } - record[CONTACT.CONT_SOCIETE_VALID.forContactCsv()] = - ImportHelper.formatContactValidation(contact.getValidationCompany()); - record[CONTACT.CONT_PROGRAM_VALID.forContactCsv()] = - ImportHelper.formatContactValidation(contact.getValidationProgram()); + export.record(CONTACT.CONT_SOCIETE_VALID, CONTACT.formatValidation(contact.getValidationCompany())); + export.record(CONTACT.CONT_PROGRAM_VALID, CONTACT.formatValidation(contact.getValidationProgram())); // Observer part WaoUser observer = contact.getObserver(); Company company = observer.getCompany(); - record[CONTACT.OBSERV_ID.forContactCsv()] = observer.getLogin(); - record[CONTACT.OBSERV_PRENOM.forContactCsv()] = observer.getFirstName(); - record[CONTACT.OBSERV_NOM.forContactCsv()] = observer.getLastName(); - record[SAMPLING.SOCIETE_NOM.forContactCsv()] = company.getName(); + export.record(CONTACT.OBSERV_ID, observer.getLogin()); + export.record(CONTACT.OBSERV_PRENOM, observer.getFirstName()); + export.record(CONTACT.OBSERV_NOM, observer.getLastName()); + export.record(SAMPLING.SOCIETE_NOM, company.getName()); // SampleRow part SampleRow row = contact.getSampleRow(); - record[SAMPLING.PLAN_CODE.forContactCsv()] = row.getCode(); - record[SAMPLING.PROGRAMME_CODE.forContactCsv()] = row.getProgramName(); - record[SAMPLING.PROGRAMME_DEBUT.forContactCsv()] = dateFormat.format(row.getPeriodBegin()); - record[SAMPLING.PROGRAMME_FIN.forContactCsv()] = dateFormat.format(row.getPeriodEnd()); - record[SAMPLING.PECHE_AUTRE.forContactCsv()] = row.getFishingZonesInfos(); + export.record(SAMPLING.PLAN_CODE, row.getCode()); + export.record(SAMPLING.PROGRAMME_CODE, row.getProgramName()); + export.record(SAMPLING.PROGRAMME_DEBUT, dateFormat.format(row.getPeriodBegin())); + export.record(SAMPLING.PROGRAMME_FIN, dateFormat.format(row.getPeriodEnd())); + export.record(SAMPLING.PECHE_AUTRE, row.getFishingZonesInfos()); // FishingZone part - List<FishingZone> zones = row.getFishingZone(); - String fishingDistrict = ""; - for (FishingZone zone : zones) { - fishingDistrict += zone.getDistrictCode() + " - "; + String divisions = ""; + String separator = " - "; + for (FishingZone zone : row.getFishingZone()) { + divisions += separator + zone.getDistrictCode(); } - fishingDistrict = fishingDistrict.substring(fishingDistrict.length() - 3); - record[FISHING_ZONE.PECHE_FACADE.forContactCsv()] = zones.get(0).getFacadeName(); - record[FISHING_ZONE.PECHE_ZONE.forContactCsv()] = zones.get(0).getSectorName(); - record[FISHING_ZONE.PECHE_DIVISION.forContactCsv()] = fishingDistrict; + export.record(FISHING_ZONE.PECHE_DIVISION, divisions.substring(separator.length())); + export.record(FISHING_ZONE.PECHE_FACADE, row.getFacade()); + export.record(FISHING_ZONE.PECHE_ZONE, row.getSectors()); // Profession part Profession profession = row.getProfession(); - record[SAMPLING.METIER_CODE_DCF5.forContactCsv()] = profession.getCodeDCF5(); - record[SAMPLING.METIER_MAILLAGE.forContactCsv()] = profession.getMeshSize(); - record[SAMPLING.METIER_TAILLE.forContactCsv()] = profession.getSize(); - record[SAMPLING.METIER_AUTRE.forContactCsv()] = profession.getOther(); - record[SAMPLING.METIER_LIBELLE.forContactCsv()] = profession.getLibelle(); - record[SAMPLING.METIER_ESPECES.forContactCsv()] = profession.getSpecies(); + export.record(SAMPLING.METIER_CODE_DCF5, profession.getCodeDCF5()); + export.record(SAMPLING.METIER_MAILLAGE, profession.getMeshSize()); + export.record(SAMPLING.METIER_TAILLE, profession.getSize()); + export.record(SAMPLING.METIER_AUTRE, profession.getOther()); + export.record(SAMPLING.METIER_LIBELLE, profession.getLibelle()); + export.record(SAMPLING.METIER_ESPECES, profession.getSpecies()); // Boat part Boat boat = contact.getBoat(); - record[BOAT.NAVS_COD.forContactCsv()] = String.valueOf(boat.getImmatriculation()); - record[BOAT.CARN_NOM.forContactCsv()] = boat.getName(); - record[BOAT.QUARTIER_IMMA.forContactCsv()] = boat.getDistrictCode(); + export.record(BOAT.NAVS_COD, String.valueOf(boat.getImmatriculation())); + export.record(BOAT.CARN_NOM, boat.getName()); + export.record(BOAT.QUARTIER_IMMA, boat.getDistrictCode()); - writer.writeRecord(record); - writer.flush(); + export.writeRecord(); } result = new FileInputStream(file); Modified: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceReferentialImpl.java =================================================================== --- trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceReferentialImpl.java 2010-02-10 22:04:27 UTC (rev 345) +++ trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceReferentialImpl.java 2010-02-11 20:04:33 UTC (rev 346) @@ -22,7 +22,6 @@ package fr.ifremer.suiviobsmer.services; import com.csvreader.CsvReader; -import fr.ifremer.suiviobsmer.ImportHelper.FISHING_ZONE; import fr.ifremer.suiviobsmer.SuiviObsmerException; import fr.ifremer.suiviobsmer.SuiviObsmerModelDAOHelper; import fr.ifremer.suiviobsmer.SuiviObsmerContext; @@ -32,7 +31,8 @@ import fr.ifremer.suiviobsmer.entity.Profession; import fr.ifremer.suiviobsmer.entity.ProfessionDAO; import fr.ifremer.suiviobsmer.entity.SampleRow; -import fr.ifremer.suiviobsmer.services.ServiceReferential; +import fr.ifremer.suiviobsmer.io.ImportHelper; +import fr.ifremer.suiviobsmer.io.WaoCsvHeader.FISHING_ZONE; import java.io.InputStream; import java.nio.charset.Charset; import java.util.ArrayList; @@ -192,9 +192,9 @@ log.trace(" " + Arrays.asList(reader.getValues())); } - String facadeName = reader.get(FISHING_ZONE.PECHE_FACADE.name()).trim(); - String sectorName = reader.get(FISHING_ZONE.PECHE_ZONE.name()).trim(); - String districtCode = reader.get(FISHING_ZONE.PECHE_DIVISION.name()).trim(); + String facadeName = ImportHelper.read(reader, FISHING_ZONE.PECHE_FACADE); + String sectorName = ImportHelper.read(reader, FISHING_ZONE.PECHE_ZONE); + String districtCode = ImportHelper.read(reader, FISHING_ZONE.PECHE_DIVISION); FishingZone zone = dao.findByDistrictCode(districtCode); Modified: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceSamplingImpl.java =================================================================== --- trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceSamplingImpl.java 2010-02-10 22:04:27 UTC (rev 345) +++ trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceSamplingImpl.java 2010-02-11 20:04:33 UTC (rev 346) @@ -22,9 +22,8 @@ package fr.ifremer.suiviobsmer.services; import com.csvreader.CsvReader; -import fr.ifremer.suiviobsmer.ImportHelper; -import fr.ifremer.suiviobsmer.ImportHelper.FISHING_ZONE; -import fr.ifremer.suiviobsmer.ImportHelper.SAMPLING; +import com.csvreader.CsvWriter; +import fr.ifremer.suiviobsmer.io.ImportHelper; import fr.ifremer.suiviobsmer.SuiviObsmerBusinessException; import fr.ifremer.suiviobsmer.SuiviObsmerBusinessException.Type; import fr.ifremer.suiviobsmer.SuiviObsmerException; @@ -36,11 +35,20 @@ import fr.ifremer.suiviobsmer.bean.ImportResultsImpl; import fr.ifremer.suiviobsmer.bean.SamplingFilter; import fr.ifremer.suiviobsmer.entity.*; -import fr.ifremer.suiviobsmer.services.ServiceSampling; +import fr.ifremer.suiviobsmer.io.WaoCsvHeader.FISHING_ZONE; +import fr.ifremer.suiviobsmer.io.WaoCsvHeader.SAMPLING; +import fr.ifremer.suiviobsmer.io.WaoCsvHeader.SamplingHeader; +import fr.ifremer.suiviobsmer.io.ExportHelper; +import fr.ifremer.suiviobsmer.io.ExportHelper; +import fr.ifremer.suiviobsmer.io.SamplingExport; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.text.DateFormat; +import java.text.NumberFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; @@ -514,6 +522,140 @@ } @Override + public InputStream exportSamplingPlanCsv(WaoUser user, PeriodDates period) throws SuiviObsmerException { + TopiaContext transaction = null; + InputStream result = null; + CsvWriter writer = null; + try { + transaction = rootContext.beginTransaction(); + + File file = File.createTempFile("wao-samplingPlan-", ".csv"); + file.deleteOnExit(); + + FileOutputStream output = new FileOutputStream(file); + writer = new CsvWriter(output, ',', Charset.forName("UTF-8")); + + // Get min and max dates to have the biggest period +// Date min = (Date)query.executeToObject("MIN(S." + SampleRow.PERIOD_BEGIN + ")"); +// Date max = (Date)query.executeToObject("MAX(S." + SampleRow.PERIOD_END + ")"); + +// PeriodDates periodMax = new PeriodDates(min, max); + period.setPattern(SAMPLING.defaultDatePattern()); + List<String> monthHeaders = period.getFormatedMonths(); + + SamplingExport export = new SamplingExport(writer, user, monthHeaders); + + export.writeHeaders(); + + // Get sampleRows from database filtered by company if needed + // (only for user) and period + SampleRowDAO dao = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); + TopiaQuery query = dao.createQuery("S"); + + if (!user.getAdmin()) { + query.add("S." + SampleRow.COMPANY, user.getCompany()); + } + + // Prepare period dates + period.initDayOfMonthExtremities(); + query.add("S." + SampleRow.PERIOD_BEGIN, Op.LT, period.getThruDate()). + add("S." + SampleRow.PERIOD_END, Op.GT, period.getFromDate()); + + query.addOrder("S." + SampleRow.CODE); + + List<SampleRow> rows = dao.findAllByQuery(query); + + DateFormat dateFormat = SAMPLING.getDateFormat(); + NumberFormat numberFormat = SAMPLING.getNumberFormat(); + + for (SampleRow row : rows) { + export.newRecord(); + + if (log.isDebugEnabled()) { + log.debug("add sampleRow : " + row.getCode()); + } + + export.record(SAMPLING.PLAN_CODE, row.getCode()); + Company company = row.getCompany(); + if (company != null) { + export.record(SAMPLING.SOCIETE_NOM, company.getName()); + } + + // Profession can't be null + Profession profession = row.getProfession(); + export.record(SAMPLING.METIER_CODE_DCF5, profession.getCodeDCF5()); + export.record(SAMPLING.METIER_MAILLAGE, profession.getMeshSize()); + export.record(SAMPLING.METIER_TAILLE, profession.getSize()); + export.record(SAMPLING.METIER_AUTRE, profession.getOther()); + export.record(SAMPLING.METIER_LIBELLE, profession.getLibelle()); + export.record(SAMPLING.METIER_ESPECES, profession.getSpecies()); + + export.record(SAMPLING.PROGRAMME_CODE, row.getProgramName()); + export.record(SAMPLING.PROGRAMME_DEBUT, dateFormat.format(row.getPeriodBegin())); + export.record(SAMPLING.PROGRAMME_FIN, dateFormat.format(row.getPeriodEnd())); + + export.record(FISHING_ZONE.PECHE_FACADE, row.getFacade()); + export.record(FISHING_ZONE.PECHE_ZONE, row.getSectors()); + export.record(SAMPLING.PECHE_AUTRE, row.getFishingZonesInfos()); + + String divisions = ""; + String separator = FISHING_ZONE.getDistrictCodeSeparator(); + for (FishingZone zone : row.getFishingZone()) { + divisions += separator + zone.getDistrictCode(); + } + + // There is at least one district in row, so no problem with substring + export.record(FISHING_ZONE.PECHE_DIVISION, divisions.substring(separator.length())); + + export.record(SAMPLING.PLAN_NB_OBSERV, numberFormat.format(row.getNbObservants())); + export.record(SAMPLING.PLAN_DUREE_MOY, numberFormat.format(row.getAverageTideTime())); + export.record(SAMPLING.PLAN_COMMENT, String.valueOf(row.getComment())); + + export.recordMonths(row); + +// for (int i = 0; i < monthHeaders.size(); i++) { +// // Get date from monthHeaders list +// Date month = dateFormat.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) +// if (user.getAdmin()) { +// export.record(index, expected); //record[index] = expected; +// // The user as both expected and real values +// } else { +// export.record(index, expected + " (" + real + ")"); +// } +// } +// } + + export.writeRecord(); + } + + result = new FileInputStream(file); + + } catch (Exception eee) { + DateFormat dateFormat = SAMPLING.getDateFormat(); + SuiviObsmerContext.serviceException(transaction, + "Impossible d'exporter le plan d'échantillonnage sur la période du " + + dateFormat.format(period.getFromDate()) + " au " + + dateFormat.format(period.getThruDate()), eee); + } finally { + if (writer != null) { + writer.close(); + } + SuiviObsmerContext.closeTransaction(transaction); + } + return result; + } + + @Override public ImportResults importSamplingPlanCsv(InputStream input) throws SuiviObsmerException { TopiaContext transaction = null; ImportResults result = new ImportResultsImpl(); @@ -666,7 +808,7 @@ FishingZoneDAO dao = SuiviObsmerModelDAOHelper.getFishingZoneDAO(transaction); - List<String> districtList = new ArrayList<String>(Arrays.asList(districts.split(" / "))); + List<String> districtList = new ArrayList<String>(Arrays.asList(districts.split(FISHING_ZONE.getDistrictCodeSeparator()))); if (log.isDebugEnabled()) { log.debug("FishingZone districts : " + districts); @@ -725,7 +867,7 @@ // Note : nbTotalColumns must be > nbFixedColumns int lastMonthColumnId = firstMonthColumnId + nbTotalColumns - nbFixedColumns; - DateFormat dateFormat = new SimpleDateFormat(SAMPLING.defaultDatePattern()); + DateFormat dateFormat = SAMPLING.getDateFormat(); for (int i = firstMonthColumnId; i < lastMonthColumnId; i++) { Modified: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceSynthesisImpl.java =================================================================== --- trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceSynthesisImpl.java 2010-02-10 22:04:27 UTC (rev 345) +++ trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceSynthesisImpl.java 2010-02-11 20:04:33 UTC (rev 346) @@ -89,7 +89,9 @@ return results; } + // Expected SortedMap<Date, Integer> serie1 = new TreeMap<Date,Integer>(); + // Real SortedMap<Date, Integer> serie2 = new TreeMap<Date,Integer>(); results.add(serie1); results.add(serie2); Modified: trunk/suiviobsmer-business/src/main/xmi/suiviobsmer.zargo =================================================================== (Binary files differ) Modified: trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/ImportHelperTest.java =================================================================== --- trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/ImportHelperTest.java 2010-02-10 22:04:27 UTC (rev 345) +++ trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/ImportHelperTest.java 2010-02-11 20:04:33 UTC (rev 346) @@ -22,10 +22,13 @@ package fr.ifremer.suiviobsmer; import com.csvreader.CsvReader; -import fr.ifremer.suiviobsmer.ImportHelper.SAMPLING; +import fr.ifremer.suiviobsmer.io.ImportHelper; +import fr.ifremer.suiviobsmer.io.WaoCsvHeader.CONTACT; +import fr.ifremer.suiviobsmer.io.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; @@ -127,7 +130,8 @@ calendar.set(Calendar.SECOND, 50); calendar.set(Calendar.MILLISECOND, 260); String expResult = "100150260"; - String result = ImportHelper.formatContactCode(calendar.getTime()); + DateFormat timeFormat = CONTACT.getTimeFormat(); + String result = timeFormat.format(calendar.getTime()); assertEquals(expResult, result); } Modified: trunk/suiviobsmer-ui/src/main/java/fr/ifremer/suiviobsmer/ui/pages/Boats.java =================================================================== --- trunk/suiviobsmer-ui/src/main/java/fr/ifremer/suiviobsmer/ui/pages/Boats.java 2010-02-10 22:04:27 UTC (rev 345) +++ trunk/suiviobsmer-ui/src/main/java/fr/ifremer/suiviobsmer/ui/pages/Boats.java 2010-02-11 20:04:33 UTC (rev 346) @@ -514,6 +514,9 @@ public InputStream getStream() throws IOException { InputStream result = null; try { + if (log.isDebugEnabled()) { + log.debug("Filter sampleRow : " + getFilter().getSampleRow()); + } result = serviceBoat.exportBoatCsv(getFilter()); } catch (SuiviObsmerException eee) { throw new IOException(eee); Modified: trunk/suiviobsmer-ui/src/main/java/fr/ifremer/suiviobsmer/ui/pages/SamplingPlan.java =================================================================== --- trunk/suiviobsmer-ui/src/main/java/fr/ifremer/suiviobsmer/ui/pages/SamplingPlan.java 2010-02-10 22:04:27 UTC (rev 345) +++ trunk/suiviobsmer-ui/src/main/java/fr/ifremer/suiviobsmer/ui/pages/SamplingPlan.java 2010-02-11 20:04:33 UTC (rev 346) @@ -34,11 +34,15 @@ import fr.ifremer.suiviobsmer.services.ServiceSampling; import fr.ifremer.suiviobsmer.ui.base.SuiviObsmerPage; import fr.ifremer.suiviobsmer.ui.components.Layout; +import fr.ifremer.suiviobsmer.ui.data.ExportStreamResponse; +import java.io.IOException; +import java.io.InputStream; import java.text.DateFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; +import org.apache.tapestry5.StreamResponse; import org.apache.tapestry5.annotations.IncludeStylesheet; import org.apache.tapestry5.annotations.InjectComponent; import org.apache.tapestry5.annotations.Log; @@ -119,7 +123,25 @@ layout.getFeedBack().addError(eee.getMessage()); } } + + /**************************** EXPORT **************************************/ + StreamResponse onActionFromExportSamplingPlan() { + return new ExportStreamResponse("wao-echantillonnage") { + + @Override + public InputStream getStream() throws IOException { + InputStream result = null; + try { + result = serviceSampling.exportSamplingPlanCsv(user, getPeriod()); + } catch (SuiviObsmerException eee) { + throw new IOException(eee); + } + return result; + } + }; + } + /**************************** PERIOD SELECTION *****************************/ @Persist Modified: trunk/suiviobsmer-ui/src/main/resources/fr/ifremer/suiviobsmer/ui/pages/Boats.properties =================================================================== --- trunk/suiviobsmer-ui/src/main/resources/fr/ifremer/suiviobsmer/ui/pages/Boats.properties 2010-02-10 22:04:27 UTC (rev 345) +++ trunk/suiviobsmer-ui/src/main/resources/fr/ifremer/suiviobsmer/ui/pages/Boats.properties 2010-02-11 20:04:33 UTC (rev 346) @@ -28,4 +28,5 @@ contactEmail-label: E-mail shipOwner-label: Armateur fromDate-label: Sollicitations du navire depuis le -dup-label: Capacit\u00E9 d'accueil du navire en personnels sp\u00E9cialis\u00E9s \ No newline at end of file +dup-label: Capacit\u00E9 d'accueil du navire en personnels sp\u00E9cialis\u00E9s +comment-label: Commentaire \ No newline at end of file Modified: trunk/suiviobsmer-ui/src/main/webapp/SamplingPlan.tml =================================================================== --- trunk/suiviobsmer-ui/src/main/webapp/SamplingPlan.tml 2010-02-10 22:04:27 UTC (rev 345) +++ trunk/suiviobsmer-ui/src/main/webapp/SamplingPlan.tml 2010-02-11 20:04:33 UTC (rev 346) @@ -17,7 +17,13 @@ </t:if> <div class="clearfix mbottom10"> <div class="fleft"> - <h1>Plan d'échantillonnage</h1> + <h1> + Plan d'échantillonnage + <a t:type="actionlink" t:id="exportSamplingPlan"> + <img src="${asset:context:}/img/file-export-22px.png" alt="Export CSV" + title="Exporter le plan d'échantillonnage du ${dateFormat.format(period.fromDate)} au ${dateFormat.format(period.thruDate)}" /> + </a> + </h1> <form t:type="form" t:id="periodForm"> <t:label t:for="periodBegin" /> : <input t:type="datefield" class="width70" t:id="periodBegin" t:format="MM/yyyy" /> <t:label t:for="periodEnd" /> : <input t:type="datefield" class="width70" t:id="periodEnd" t:format="MM/yyyy" />