[Suiviobsmer-commits] r339 - in trunk: suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/entity suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/services suiviobsmer-ui/src/main/java/fr/ifremer/suiviobsmer/ui/services
Author: fdesbois Date: 2010-02-09 01:30:52 +0000 (Tue, 09 Feb 2010) New Revision: 339 Added: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ 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/java/fr/ifremer/suiviobsmer/services/ServiceUserImpl.java trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/services/ trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/services/ServiceSamplingImplTest.java trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/services/ServiceSynthesisImplTest.java Removed: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/impl/ 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/java/fr/ifremer/suiviobsmer/services/ServiceUserImpl.java trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/impl/ trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/services/ServiceSamplingImplTest.java trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/services/ServiceSynthesisImplTest.java Modified: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceNewsImpl.java trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/SuiviObsmerGlobalTest.java trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/SuiviObsmerRunnerTest.java trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/entity/BoatImplTest.java trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/entity/BoatInfosImplTest.java trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/entity/SampleRowImplTest.java trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/services/ActivityCalendarImportTest.java trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/services/ServiceBoatImplTest.java trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/services/ServiceReferentialImplTest.java trunk/suiviobsmer-ui/src/main/java/fr/ifremer/suiviobsmer/ui/services/AppModule.java Log: Refactor package impl to services Property changes on: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services ___________________________________________________________________ Added: svn:mergeinfo + Deleted: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ActivityCalendarImport.java =================================================================== --- trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/impl/ActivityCalendarImport.java 2010-02-04 21:33:50 UTC (rev 325) +++ trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ActivityCalendarImport.java 2010-02-09 01:30:52 UTC (rev 339) @@ -1,381 +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.impl; - -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; -import fr.ifremer.suiviobsmer.entity.ActivityMonthDAO; -import fr.ifremer.suiviobsmer.entity.ActivityProfession; -import fr.ifremer.suiviobsmer.entity.ActivityProfessionDAO; -import fr.ifremer.suiviobsmer.entity.ActivityZone; -import fr.ifremer.suiviobsmer.entity.ActivityZoneDAO; -import fr.ifremer.suiviobsmer.entity.Boat; -import fr.ifremer.suiviobsmer.entity.BoatDAO; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.Writer; -import java.nio.charset.Charset; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.time.DurationFormatUtils; -import org.nuiton.topia.TopiaContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * ActivityCalendarImport - * - * Created: 11 déc. 2009 - * - * @author fdesbois - * @version $Revision$ - * - * Mise a jour: $Date$ - * par : $Author$ - */ -public class ActivityCalendarImport implements Runnable { - - private InputStream input; - - private Writer writer; - - private static final Logger log = LoggerFactory.getLogger(ActivityCalendarImport.class); - - private static final boolean DISABLED = false; - - public class ActivityCalendarKey { - - private Boat _boat; - private String _boatId; - private int _year; - - public ActivityCalendarKey(Boat boat, int year) { - _boatId = boat.getTopiaId(); - _year = year; - _boat = boat; - } - - public String boatId() { - return _boatId; - } - - public Boat boat() { - return _boat; - } - - public int year() { - return _year; - } - - @Override - public boolean equals(Object key) { - if (!ActivityCalendarKey.class.isAssignableFrom(key.getClass())) { - throw new ClassCastException("Unable to cast object " + key.getClass() + " to " + this.getClass().getName()); - } - ActivityCalendarKey calendarKey = (ActivityCalendarKey)key; - return _year == calendarKey.year() && _boatId.equals(calendarKey.boatId()); - } - - @Override - public int hashCode() { - int hash = 7; - hash = 61 * hash + (this._boatId != null ? this._boatId.hashCode() : 0); - hash = 61 * hash + this._year; - return hash; - } - } - - public ActivityCalendarImport(InputStream input) throws IOException { - super(); - this.input = input; - String filename = SuiviObsmerContext.getProperty( - SuiviObsmerContext.PROP_FILENAME_LOG_ACTIVITY_IMPORT); - File file = new File(filename); - file.getParentFile().mkdirs(); - if (file.exists()) { - file.delete(); - file.createNewFile(); - } - writer = new BufferedWriter(new FileWriter(filename)); - } - - @Override - public void run() { - TopiaContext transaction = null; - SuiviObsmerContext.setActivityCalendarImport(true); - int currRow = 1; - try { - transaction = SuiviObsmerContext.getTopiaRootContext().beginTransaction(); - - CsvReader reader = new CsvReader(input, Charset.forName("UTF-8")); - - long startTime = System.currentTimeMillis(); - - reader.readHeaders(); - - int result = 0; - - long firstTic = startTime; - - long tic1, tic2; - - Map<ActivityCalendarKey, ActivityCalendar> availableCalendars = new HashMap<ActivityCalendarKey, ActivityCalendar>(); - - BoatDAO boatDAO = SuiviObsmerModelDAOHelper.getBoatDAO(transaction); - ActivityCalendarDAO calendarDAO = SuiviObsmerModelDAOHelper.getActivityCalendarDAO(transaction); - ActivityMonthDAO monthDAO = SuiviObsmerModelDAOHelper.getActivityMonthDAO(transaction); - ActivityProfessionDAO professionDAO = SuiviObsmerModelDAOHelper.getActivityProfessionDAO(transaction); - ActivityZoneDAO zoneDAO = SuiviObsmerModelDAOHelper.getActivityZoneDAO(transaction); - - while(reader.readRecord()) { - currRow++; - - int boatImmatriculation = Integer.parseInt(reader.get(BOAT.NAVS_COD.name()).trim()); - - Boat boat = boatDAO.findByImmatriculation(boatImmatriculation); - - - if (boat != null) { - -// int year = Integer.parseInt(reader.get("SYNA_AN").trim()); - int year = ImportHelper.readInt(reader, ACTIVITY_CALENDAR.SYNA_AN); - if (year == -1) { - error("Ligne non sauvegardé car l'année (SYNA_AN) n'est pas renseigné", currRow); - continue; - } - - ActivityCalendarKey key = new ActivityCalendarKey(boat, year); - ActivityCalendar calendar = availableCalendars.get(key); - - // If not available select it from Database - if (calendar == null) { - - calendar = calendarDAO.findByProperties( - ActivityCalendar.BOAT, boat, - ActivityCalendar.YEAR, year); - - // Create it if not exist in Database - if (calendar == null) { - //int fiability = Integer.parseInt(reader.get("INDQ_COD").trim()); - // fiability can be -1 if NA is set in CSV file - int fiability = ImportHelper.readInt(reader, ACTIVITY_CALENDAR.INDQ_COD); - - calendar = calendarDAO.create( - ActivityCalendar.BOAT, key.boat(), - ActivityCalendar.YEAR, key.year(), - ActivityCalendar.FIABILITY, fiability); - - calendar.setActivityMonth(new ArrayList<ActivityMonth>()); - -// if (log.isDebugEnabled()) { -// info("Création d'un calendrier " + year + -// " pour le navire immatriculé " + boatImmatriculation, currRow); -// } - } - availableCalendars.put(key, calendar); - } - - //int monthNum = Integer.parseInt(reader.get("SYNA_MOI").trim()); - int monthNum = ImportHelper.readInt(reader, ACTIVITY_CALENDAR.SYNA_MOI); - if (monthNum == -1) { - error("Ligne non sauvegardé car le mois (SYNA_MOI) n'est pas renseigné", currRow); - continue; - } - - //String harbourCode = reader.get("SYNA_POR_COD").trim(); - String professionCode = ImportHelper.read(reader, ACTIVITY_CALENDAR.MET_COD); - boolean active = professionCode != null && !professionCode.equals("INA"); - - ActivityMonth month = calendar.getActivityMonth(monthNum); - - if (month == null) { - month = monthDAO.create( - ActivityMonth.ACTIVITY_CALENDAR, calendar, - ActivityMonth.MONTH, monthNum); - - month.setActivityProfession(new ArrayList<ActivityProfession>()); - - calendar.addActivityMonth(month); - } - - month.setActive(active); - - if (active) { - - Integer nbSeaDays = ImportHelper.readInteger(reader, ACTIVITY_CALENDAR.SYNA_NOMJDM); - Integer nbFishingDays = ImportHelper.readInteger(reader, ACTIVITY_CALENDAR.SYNA_NOMJDP); - Integer nbBoardingPersons = ImportHelper.readInteger(reader, ACTIVITY_CALENDAR.SYNA_NOMHE); - - int harbourId = ImportHelper.readInt(reader, ACTIVITY_CALENDAR.SYNA_TPOR_COD); - String harbourCode = ImportHelper.read(reader, ACTIVITY_CALENDAR.SYNA_POR_COD); - String harbourLibelle = ImportHelper.read(reader, ACTIVITY_CALENDAR.SYNA_POR_LIB); - - month.setHarbourId(harbourId); - month.setHarbourCode(harbourCode); - month.setHarbourLibelle(harbourLibelle); - month.setNbBoardingPersons(nbBoardingPersons); - month.setNbFishingDays(nbFishingDays); - month.setNbSeaDays(nbSeaDays); - - // Can be equals to -1 if set to NA in Csv File (not a problem for ordering Profession) - int professionOrder = ImportHelper.readInt(reader, ACTIVITY_CALENDAR.META_ORDRE); - int professionId = ImportHelper.readInt(reader, ACTIVITY_CALENDAR.MET_ID); - String professionLibelle = ImportHelper.read(reader, ACTIVITY_CALENDAR.MET_LIB); - - ActivityProfession profession = month.getActivityProfession(professionOrder); - - if (profession == null) { - - profession = professionDAO.create( - ActivityProfession.ACTIVITY_MONTH, month, - ActivityProfession.PROFESSION_ORDER, professionOrder); - - profession.setActivityZone(new ArrayList<ActivityZone>()); - - month.addActivityProfession(profession); - } - - profession.setId(professionId); - profession.setCode(professionCode); - profession.setLibelle(professionLibelle); - -// String zoneCode = reader.get("SECT_COD").trim(); -// int gradiantCode = Integer.parseInt(reader.get("GRA_COD").trim()); -// String gradiantLibelle = reader.get("GRA_LIB").trim(); -// int zoneId = Integer.parseInt(reader.get("TSECT_COD").trim()); -// String zoneLibelle = reader.get("SECT_LIB").trim(); - - String zoneCode = ImportHelper.read(reader, ACTIVITY_CALENDAR.SECT_COD); - int gradiantCode = ImportHelper.readInt(reader, ACTIVITY_CALENDAR.GRA_COD); - String gradiantLibelle = ImportHelper.read(reader, ACTIVITY_CALENDAR.GRA_LIB); - int zoneId = ImportHelper.readInt(reader, ACTIVITY_CALENDAR.TSECT_COD); - String zoneLibelle = ImportHelper.read(reader, ACTIVITY_CALENDAR.SECT_LIB); - - ActivityZone zone = profession.getActivityZone(zoneCode); - - if (zone == null) { - zone = zoneDAO.create( - ActivityZone.ZONE_CODE, zoneCode, - ActivityZone.ACTIVITY_PROFESSION, profession); - - profession.addActivityZone(zone); - } - - zone.setZoneId(zoneId); - zone.setZoneLibelle(zoneLibelle); - zone.setGradiantCode(gradiantCode); - zone.setGradiantLibelle(gradiantLibelle); - } else { - //info("Ligne inactif", currRow); - } - result++; - } else { - warn("Navire inexistant dans le référentiel : " + boatImmatriculation, currRow); - } - - if (result % 1000 == 0) { - tic1 = System.currentTimeMillis(); - - transaction.commitTransaction(); - availableCalendars.clear(); - // Force garbage collector - System.gc(); - - tic2 = System.currentTimeMillis(); - if (log.isDebugEnabled()) { - log.debug("commit : " + (tic2 - tic1)); - } - firstTic = ImportHelper.logTimeAndMemory(log, firstTic, "calendrier d'activité ligne " + currRow); - } - } - - // For the last rows - transaction.commitTransaction(); - - long stopTime = System.currentTimeMillis(); - - String execTime = DurationFormatUtils.formatDurationHMS(stopTime - startTime); - - info("Nombre de ligne ajouté : " + result, -1); - info("Temps d'exécution : " + execTime, -1); - - transaction.closeContext(); - } catch (Exception eee) { - if (log.isErrorEnabled()) { - log.error("Problème lors de l'import du calendrier d'activité", eee); - } - try { - error("exception " + eee.getClass().getSimpleName() + " : " + eee.getMessage(), currRow); - } catch (IOException ex) { - if (log.isErrorEnabled()) { - log.error("IO error", ex); - } - } - } finally { - IOUtils.closeQuietly(writer); - SuiviObsmerContext.setActivityCalendarImport(false); - } - } - - protected void warn(String message, int numRow) throws IOException { - log("[WARN] " + message, numRow); - } - - protected void error(String message, int numRow) throws IOException { - log("[ERROR] " + message, numRow); - } - - protected void info(String message, int numRow) throws IOException { - log("[INFO] " + message, numRow); - } - - protected void log(String message, int numRow) throws IOException { - if (DISABLED) { - return; - } - Date date = new Date(); - DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.FRENCH); - String dateString = dateFormat.format(date); - String ligne = numRow != -1 ? "Ligne (" + numRow + ") : " : ""; - String msg = "[" + dateString + "] " + ligne + message; - writer.write(msg + "\n"); - writer.flush(); - if (log.isTraceEnabled()) { - log.trace("write log activityCalendar : " + msg); - } - } - -} Copied: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ActivityCalendarImport.java (from rev 326, trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/impl/ActivityCalendarImport.java) =================================================================== --- trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ActivityCalendarImport.java (rev 0) +++ trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ActivityCalendarImport.java 2010-02-09 01:30:52 UTC (rev 339) @@ -0,0 +1,368 @@ +/* + * *##% + * 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.services; + +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; +import fr.ifremer.suiviobsmer.entity.ActivityMonthDAO; +import fr.ifremer.suiviobsmer.entity.ActivityProfession; +import fr.ifremer.suiviobsmer.entity.ActivityProfessionDAO; +import fr.ifremer.suiviobsmer.entity.ActivityZone; +import fr.ifremer.suiviobsmer.entity.ActivityZoneDAO; +import fr.ifremer.suiviobsmer.entity.Boat; +import fr.ifremer.suiviobsmer.entity.BoatDAO; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.Writer; +import java.nio.charset.Charset; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang.time.DurationFormatUtils; +import org.nuiton.topia.TopiaContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * ActivityCalendarImport + * + * Created: 11 déc. 2009 + * + * @author fdesbois + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ +public class ActivityCalendarImport implements Runnable { + + private InputStream input; + + private Writer writer; + + private static final Logger log = LoggerFactory.getLogger(ActivityCalendarImport.class); + + private static final boolean DISABLED = false; + + public class ActivityCalendarKey { + + private Boat boat; + private String boatId; + private int year; + + public ActivityCalendarKey(Boat boat, int year) { + boatId = boat.getTopiaId(); + this.year = year; + this.boat = boat; + } + + public String boatId() { + return boatId; + } + + public Boat boat() { + return boat; + } + + public int year() { + return year; + } + + @Override + public boolean equals(Object key) { + if (!ActivityCalendarKey.class.isAssignableFrom(key.getClass())) { + throw new ClassCastException("Unable to cast object " + key.getClass() + " to " + this.getClass().getName()); + } + ActivityCalendarKey calendarKey = (ActivityCalendarKey)key; + return year == calendarKey.year() && boatId.equals(calendarKey.boatId()); + } + + @Override + public int hashCode() { + int hash = 7; + hash = 61 * hash + (this.boatId != null ? this.boatId.hashCode() : 0); + hash = 61 * hash + this.year; + return hash; + } + } + + public ActivityCalendarImport(InputStream input) throws IOException { + super(); + this.input = input; + String filename = SuiviObsmerContext.getProperty( + SuiviObsmerContext.PROP_FILENAME_LOG_ACTIVITY_IMPORT); + File file = new File(filename); + file.getParentFile().mkdirs(); + if (file.exists()) { + file.delete(); + file.createNewFile(); + } + writer = new BufferedWriter(new FileWriter(filename)); + } + + @Override + public void run() { + TopiaContext transaction = null; + SuiviObsmerContext.setActivityCalendarImport(true); + int currRow = 1; + try { + transaction = SuiviObsmerContext.getTopiaRootContext().beginTransaction(); + + CsvReader reader = new CsvReader(input, Charset.forName("UTF-8")); + + long startTime = System.currentTimeMillis(); + + reader.readHeaders(); + + int result = 0; + + long firstTic = startTime; + + long tic1, tic2; + + Map<ActivityCalendarKey, ActivityCalendar> availableCalendars = new HashMap<ActivityCalendarKey, ActivityCalendar>(); + + BoatDAO boatDAO = SuiviObsmerModelDAOHelper.getBoatDAO(transaction); + ActivityCalendarDAO calendarDAO = SuiviObsmerModelDAOHelper.getActivityCalendarDAO(transaction); + ActivityMonthDAO monthDAO = SuiviObsmerModelDAOHelper.getActivityMonthDAO(transaction); + ActivityProfessionDAO professionDAO = SuiviObsmerModelDAOHelper.getActivityProfessionDAO(transaction); + ActivityZoneDAO zoneDAO = SuiviObsmerModelDAOHelper.getActivityZoneDAO(transaction); + + while(reader.readRecord()) { + currRow++; + + int boatImmatriculation = Integer.parseInt(reader.get(BOAT.NAVS_COD.name()).trim()); + + Boat boat = boatDAO.findByImmatriculation(boatImmatriculation); + + + if (boat != null) { + +// int year = Integer.parseInt(reader.get("SYNA_AN").trim()); + int year = ImportHelper.readInt(reader, ACTIVITY_CALENDAR.SYNA_AN); + if (year == -1) { + error("Ligne non sauvegardé car l'année (SYNA_AN) n'est pas renseigné", currRow); + continue; + } + + ActivityCalendarKey key = new ActivityCalendarKey(boat, year); + ActivityCalendar calendar = availableCalendars.get(key); + + // If not available select it from Database + if (calendar == null) { + + calendar = calendarDAO.findByProperties( + ActivityCalendar.BOAT, boat, + ActivityCalendar.YEAR, year); + + // Create it if not exist in Database + if (calendar == null) { + //int fiability = Integer.parseInt(reader.get("INDQ_COD").trim()); + // fiability can be -1 if NA is set in CSV file + int fiability = ImportHelper.readInt(reader, ACTIVITY_CALENDAR.INDQ_COD); + + calendar = calendarDAO.create( + ActivityCalendar.BOAT, key.boat(), + ActivityCalendar.YEAR, key.year(), + ActivityCalendar.FIABILITY, fiability); + + calendar.setActivityMonth(new ArrayList<ActivityMonth>()); + } + availableCalendars.put(key, calendar); + } + + //int monthNum = Integer.parseInt(reader.get("SYNA_MOI").trim()); + int monthNum = ImportHelper.readInt(reader, ACTIVITY_CALENDAR.SYNA_MOI); + if (monthNum == -1) { + error("Ligne non sauvegardé car le mois (SYNA_MOI) n'est pas renseigné", currRow); + continue; + } + + //String harbourCode = reader.get("SYNA_POR_COD").trim(); + String professionCode = ImportHelper.read(reader, ACTIVITY_CALENDAR.MET_COD); + boolean active = professionCode != null && !professionCode.equals("INA"); + + ActivityMonth month = calendar.getActivityMonth(monthNum); + + if (month == null) { + month = monthDAO.create( + ActivityMonth.ACTIVITY_CALENDAR, calendar, + ActivityMonth.MONTH, monthNum); + + month.setActivityProfession(new ArrayList<ActivityProfession>()); + + calendar.addActivityMonth(month); + } + + month.setActive(active); + + if (active) { + + Integer nbSeaDays = ImportHelper.readInteger(reader, ACTIVITY_CALENDAR.SYNA_NOMJDM); + Integer nbFishingDays = ImportHelper.readInteger(reader, ACTIVITY_CALENDAR.SYNA_NOMJDP); + Integer nbBoardingPersons = ImportHelper.readInteger(reader, ACTIVITY_CALENDAR.SYNA_NOMHE); + + int harbourId = ImportHelper.readInt(reader, ACTIVITY_CALENDAR.SYNA_TPOR_COD); + String harbourCode = ImportHelper.read(reader, ACTIVITY_CALENDAR.SYNA_POR_COD); + String harbourLibelle = ImportHelper.read(reader, ACTIVITY_CALENDAR.SYNA_POR_LIB); + + month.setHarbourId(harbourId); + month.setHarbourCode(harbourCode); + month.setHarbourLibelle(harbourLibelle); + month.setNbBoardingPersons(nbBoardingPersons); + month.setNbFishingDays(nbFishingDays); + month.setNbSeaDays(nbSeaDays); + + // Can be equals to -1 if set to NA in Csv File (not a problem for ordering Profession) + int professionOrder = ImportHelper.readInt(reader, ACTIVITY_CALENDAR.META_ORDRE); + int professionId = ImportHelper.readInt(reader, ACTIVITY_CALENDAR.MET_ID); + String professionLibelle = ImportHelper.read(reader, ACTIVITY_CALENDAR.MET_LIB); + + ActivityProfession profession = month.getActivityProfession(professionOrder); + + if (profession == null) { + + profession = professionDAO.create( + ActivityProfession.ACTIVITY_MONTH, month, + ActivityProfession.PROFESSION_ORDER, professionOrder); + + profession.setActivityZone(new ArrayList<ActivityZone>()); + + month.addActivityProfession(profession); + } + + profession.setId(professionId); + profession.setCode(professionCode); + profession.setLibelle(professionLibelle); + + String zoneCode = ImportHelper.read(reader, ACTIVITY_CALENDAR.SECT_COD); + int gradiantCode = ImportHelper.readInt(reader, ACTIVITY_CALENDAR.GRA_COD); + String gradiantLibelle = ImportHelper.read(reader, ACTIVITY_CALENDAR.GRA_LIB); + int zoneId = ImportHelper.readInt(reader, ACTIVITY_CALENDAR.TSECT_COD); + String zoneLibelle = ImportHelper.read(reader, ACTIVITY_CALENDAR.SECT_LIB); + + ActivityZone zone = profession.getActivityZone(zoneCode); + + if (zone == null) { + zone = zoneDAO.create( + ActivityZone.ZONE_CODE, zoneCode, + ActivityZone.ACTIVITY_PROFESSION, profession); + + profession.addActivityZone(zone); + } + + zone.setZoneId(zoneId); + zone.setZoneLibelle(zoneLibelle); + zone.setGradiantCode(gradiantCode); + zone.setGradiantLibelle(gradiantLibelle); + } + result++; + } else { + warn("Navire inexistant dans le référentiel : " + boatImmatriculation, currRow); + } + + if (result % 1000 == 0) { + tic1 = System.currentTimeMillis(); + + transaction.commitTransaction(); + availableCalendars.clear(); + // Force garbage collector + System.gc(); + + tic2 = System.currentTimeMillis(); + if (log.isDebugEnabled()) { + log.debug("commit : " + (tic2 - tic1)); + } + firstTic = ImportHelper.logTimeAndMemory(log, firstTic, "calendrier d'activité ligne " + currRow); + } + } + + // For the last rows + transaction.commitTransaction(); + + long stopTime = System.currentTimeMillis(); + + String execTime = DurationFormatUtils.formatDurationHMS(stopTime - startTime); + + info("Nombre de ligne ajouté : " + result, -1); + info("Temps d'exécution : " + execTime, -1); + + transaction.closeContext(); + } catch (Exception eee) { + if (log.isErrorEnabled()) { + log.error("Problème lors de l'import du calendrier d'activité", eee); + } + try { + error("exception " + eee.getClass().getSimpleName() + " : " + eee.getMessage(), currRow); + } catch (IOException ex) { + if (log.isErrorEnabled()) { + log.error("IO error", ex); + } + } + } finally { + IOUtils.closeQuietly(writer); + SuiviObsmerContext.setActivityCalendarImport(false); + } + } + + protected void warn(String message, int numRow) throws IOException { + writeLog("[WARN] " + message, numRow); + } + + protected void error(String message, int numRow) throws IOException { + writeLog("[ERROR] " + message, numRow); + } + + protected void info(String message, int numRow) throws IOException { + writeLog("[INFO] " + message, numRow); + } + + protected void writeLog(String message, int numRow) throws IOException { + if (DISABLED) { + return; + } + Date date = new Date(); + DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.FRENCH); + String dateString = dateFormat.format(date); + String ligne = numRow != -1 ? "Ligne (" + numRow + ") : " : ""; + String msg = "[" + dateString + "] " + ligne + message; + writer.write(msg + "\n"); + writer.flush(); + if (log.isTraceEnabled()) { + log.trace("write log activityCalendar : " + msg); + } + } + +} Deleted: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceBoatImpl.java =================================================================== --- trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/impl/ServiceBoatImpl.java 2010-02-04 21:33:50 UTC (rev 325) +++ trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceBoatImpl.java 2010-02-09 01:30:52 UTC (rev 339) @@ -1,631 +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.impl; - -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 org.nuiton.topia.framework.TopiaQuery; -import org.nuiton.topia.framework.TopiaQuery.Op; -import fr.ifremer.suiviobsmer.bean.BoatFilter; -import fr.ifremer.suiviobsmer.bean.CompanyBoatInfos; -import fr.ifremer.suiviobsmer.bean.CompanyBoatInfosImpl; -import fr.ifremer.suiviobsmer.entity.*; -import fr.ifremer.suiviobsmer.entity.Boat; -import fr.ifremer.suiviobsmer.services.ServiceBoat; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.time.DurationFormatUtils; -import org.apache.log4j.PatternLayout; -import org.apache.log4j.RollingFileAppender; -import org.nuiton.topia.TopiaContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * ServiceBoatImpl - * - * Created: 24 nov. 2009 - * - * @author fdesbois - * @version $Revision$ - * - * Mise a jour: $Date$ - * par : $Author$ - */ -public class ServiceBoatImpl implements ServiceBoat { - - private static final Logger log = LoggerFactory.getLogger(ServiceBoatImpl.class); - - protected TopiaContext rootContext; - - public ServiceBoatImpl() throws SuiviObsmerException { - rootContext = SuiviObsmerContext.getTopiaRootContext(); - } - - @Override - public Map<Integer, Boat> getBoatsByFilter(BoatFilter filter) throws SuiviObsmerException { - TopiaContext transaction = null; - Map<Integer, Boat> results = new HashMap<Integer, Boat>(); - try { - transaction = rootContext.beginTransaction(); - - BoatDAO dao = SuiviObsmerModelDAOHelper.getBoatDAO(transaction); - TopiaQuery<Boat> query = dao.createQuery("B"); - - query = createQueryForBoatFilter(query, filter); - - if (StringUtils.isNotEmpty(filter.getOrderBy())) { - query.addOrder("B." + filter.getOrderBy()); - } - - query.addLoad(Boat.ACTIVITY_CALENDAR); - - if (log.isDebugEnabled()) { - log.debug("Query : " + query); - } - - results = query.executeToEntityMap(Boat.IMMATRICULATION, Integer.class); - - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, "Impossible de filtrer la liste des navires", eee); - } - return results; - } - - @Override - public int getNbBoatsByFilter(BoatFilter filter) throws SuiviObsmerException { - TopiaContext transaction = null; - int result = 0; - try { - transaction = rootContext.beginTransaction(); - - BoatDAO dao = SuiviObsmerModelDAOHelper.getBoatDAO(transaction); - TopiaQuery<Boat> query = dao.createQuery("B"); - - query = createQueryForBoatFilter(query, filter); - - result = query.executeCount(); - - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, "Impossible de filtrer la liste des navires", eee); - } - return result; - } - - protected TopiaQuery<Boat> createQueryForBoatFilter(TopiaQuery<Boat> query, BoatFilter filter) { - String main = query.getMainAlias(); - query = filter.prepareQueryForBoat(query, main).addDistinct(); - - // Sampling filter - if (filter.isSamplingFiltered()) { - // Add join for ElligibleBoat - String elligibleBoatClassName = ElligibleBoat.class.getName(); - query.addFrom(elligibleBoatClassName + " E").add("E." + ElligibleBoat.BOAT + " = " + main); - query = filter.prepareQueryForSampling(query, "E." + ElligibleBoat.SAMPLE_ROW); - - // Company - if (filter.getCompany() != null) { - //query.add("E." + ElligibleBoat.SAMPLE_ROW + "." + SampleRow.COMPANY, filter.getCompany()); - // Test only valid ElligibleBoat for that company - query.add("E." + ElligibleBoat.COMPANY_ACTIVE + " = :booleanTrue " + - "OR (E." + ElligibleBoat.COMPANY_ACTIVE + " IS NULL AND E." + ElligibleBoat.GLOBAL_ACTIVE + " = :booleanTrue)"); - query.addParam("booleanTrue", Boolean.TRUE); - } - } - - return query; - } - - /** - * Get boat infos and elligible boats for a company and a boat. This method - * is useful to get sampleRows elligibles for the boat. Only sampleRows not - * closed linked with the company argument will be returned. The result give - * a Map with sampleRowCode in key and ElligibleBoat in value. - * The ElligibleBoat entity contains the SampleRow and attributes useful - * to know if the link is active or specific for the company. - * - * @param boatImmatriculation immatriculation of the boat - * @param company the Company to filter the ElligibleBoats - * @return an ElligibleBoatsCompany wich contains the map of ElligibleBoat, - * the company and an empty list for deleted elements. - */ - @Override - public CompanyBoatInfos getCompanyBoatInfos(int boatImmatriculation, Company company) - throws SuiviObsmerException { - - Map<String, ElligibleBoat> elligibleBoats = new HashMap<String, ElligibleBoat>(); - CompanyBoatInfos result = new CompanyBoatInfosImpl(); - result.setCompany(company); - result.setElligibleBoats(elligibleBoats); - result.setDeletedElligibleBoats(new ArrayList<ElligibleBoat>()); - - TopiaContext transaction = null; - try { - transaction = rootContext.beginTransaction(); - - BoatDAO dao = SuiviObsmerModelDAOHelper.getBoatDAO(transaction); - - Boat boat = dao.findByImmatriculation(boatImmatriculation); - - BoatInfosDAO boatInfosDAO = SuiviObsmerModelDAOHelper.getBoatInfosDAO(transaction); - BoatInfos boatInfos = boatInfosDAO.findByProperties( - BoatInfos.BOAT, boat, BoatInfos.COMPANY, company); - if (boatInfos == null) { - boatInfos = new BoatInfosImpl(); - boatInfos.setBoat(boat); - boatInfos.setCompany(company); - } else { - // load data - boatInfos.getBoat(); - } - // load data - boatInfos.getBoat().sizeActivityCalendar(); - - result.setBoatInfos(boatInfos); - - for (ElligibleBoat elligible : boat.getElligibleBoat()) { - SampleRow sampleRow = elligible.getSampleRow(); - - // SampleRow non closed only - //if (!sampleRow.isFinished()) { - - String companyId = sampleRow.getCompany() != null ? - sampleRow.getCompany().getTopiaId() : ""; - - if (companyId.equals(company.getTopiaId())) { - elligibleBoats.put(sampleRow.getCode(), elligible); - } - //} - } - - // Last contact - ContactDAO contactDAO = SuiviObsmerModelDAOHelper.getContactDAO(transaction); - Contact contact = contactDAO.createQueryLastContactForBoat(boat, company). - addLoad(Contact.SAMPLE_ROW, Contact.OBSERVER). - executeToEntity(); - - if (contact != null) { - result.setLastContact(contact); - } - - - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, - "Impossible de récupérer les informations du navire " + - "immatriculé '" + boatImmatriculation + "'" + - " pour la société '" + company.getName() + "'", eee); - } - return result; - } - - @Override - public void createUpdateCompanyBoatInfos(CompanyBoatInfos companyBoatInfos) - throws SuiviObsmerException { - TopiaContext transaction = null; - try { - transaction = rootContext.beginTransaction(); - - BoatInfosDAO dao = SuiviObsmerModelDAOHelper.getBoatInfosDAO(transaction); - - BoatInfos boatInfos = companyBoatInfos.getBoatInfos(); - SuiviObsmerContext.prepareTopiaId(BoatInfos.class, boatInfos); - dao.update(boatInfos); - - ElligibleBoatDAO elligibleDAO = SuiviObsmerModelDAOHelper.getElligibleBoatDAO(transaction); - - for (ElligibleBoat elligible : companyBoatInfos.getElligibleBoatsValues()) { - SuiviObsmerContext.prepareTopiaId(ElligibleBoat.class, elligible); - elligibleDAO.update(elligible); - } - - // Delete ElligibleBoats for the company - for (ElligibleBoat elligible : companyBoatInfos.getDeletedElligibleBoats()) { - elligibleDAO.delete(elligible); - } - - transaction.commitTransaction(); - transaction.closeContext(); - } catch (Exception eee) { - Boat boat = companyBoatInfos.getBoatInfos().getBoat(); - Company company = companyBoatInfos.getCompany(); - SuiviObsmerContext.serviceException(transaction, - "Impossible de créer ou modifier les informations liés au navire " + - boat.getImmatriculation() + " pour la société " + company.getName(), eee); - } - } - - @Override - public List<Boat> getBoatsByImmatriculations(String immatriculations) throws SuiviObsmerException { - List<Boat> boats = new ArrayList<Boat>(); - TopiaContext transaction = null; - if (StringUtils.isEmpty(immatriculations)) { - return boats; - } - try { - transaction = rootContext.beginTransaction(); - - BoatDAO dao = SuiviObsmerModelDAOHelper.getBoatDAO(transaction); - - Pattern pattern = Pattern.compile("\\d{6}"); - Matcher matcher = pattern.matcher(immatriculations); - while(matcher.find()) { - String res = matcher.group(); - int immatriculation = Integer.parseInt(res); - Boat boat = dao.findByImmatriculation(immatriculation); - if (boat == null) { - throw new SuiviObsmerBusinessException(Type.NOT_EXISTS, ServiceBoat.class, - "Immatriculation " + immatriculation + " incorrect, ne référence aucun navire"); - } - boats.add(boat); - } - - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, - "La chaîne d'immatriculations est incorrect ! Chaque immatriculation doit posséder 6 chiffres", eee); - } - return boats; - } - - @Override - public Boat getBoat(String boatId) throws SuiviObsmerException { - TopiaContext transaction = null; - Boat result = null; - try { - transaction = rootContext.beginTransaction(); - - BoatDAO dao = SuiviObsmerModelDAOHelper.getBoatDAO(transaction); - - result = dao.findByTopiaId(boatId); - - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, "Impossible de charger le navire", eee); - } - return result; - } - - @Override - public List<String> getBoatNamesStartWith(String input) throws SuiviObsmerException { - TopiaContext transaction = null; - List<String> results = new ArrayList<String>(); - try { - transaction = rootContext.beginTransaction(); - - input = StringUtils.upperCase(input); - - BoatDAO dao = SuiviObsmerModelDAOHelper.getBoatDAO(transaction); - - results = (List<String>)dao.createQuery().addDistinct().setSelect(Boat.NAME).add(Boat.NAME, Op.LIKE, input + "%").execute(); - - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, - "Impossible de récupérer les navires avec un nom commencant par '" + input + "'", eee); - } - return results; - } - - /** - * Import boats from a CSV file. Warning, must be UTF-8 encoding. - * Use of CsvReader to manage InputStream and create or update boats. - * Header file must be : NAVS_COD,CARN_NOM,CARN_LONGUEUR_HT,CARN_ANNEE, - * QUARTIER_IMMA,PER_COD, PER_NOM,PER_PRENOM. - * Existing boats (with same immatriculation) are updated. - * - * @param input Stream corresponding to Csv file - * @return an array with two int : the first corresponding to total number - * of boats imported and the second corresponding only to new boats added. - * @throws SuiviObsmerException - * @see com.csvreader.CsvReader - */ - @Override - public int[] importBoatCsv(InputStream input) throws SuiviObsmerException { - TopiaContext transaction = null; - int[] result = new int[]{0,0}; - try { - transaction = rootContext.beginTransaction(); - - CsvReader reader = new CsvReader(input, Charset.forName("UTF-8")); - reader.readHeaders(); - - long startTime = System.currentTimeMillis(); - long tic; - - BoatDAO boatDAO = SuiviObsmerModelDAOHelper.getBoatDAO(transaction); - ShipOwnerDAO shipOwnerDAO = SuiviObsmerModelDAOHelper.getShipOwnerDAO(transaction); - - Map<String, ShipOwner> availableShipOwners = new HashMap<String, ShipOwner>(); - - tic = System.currentTimeMillis(); - while(reader.readRecord()) { - result[0]++; - -// if (log.isTraceEnabled()) { -// log.trace(" " + Arrays.asList(reader.getValues())); -// } - - - int immatriculation = ImportHelper.readInt(reader, BOAT.NAVS_COD); - String boatName = ImportHelper.read(reader, BOAT.CARN_NOM); - int boatLength = ImportHelper.readInt(reader, BOAT.CARN_LONGUEUR_HT); - int buildYear = ImportHelper.readInt(reader, BOAT.CARN_ANNEE); - String districtCode = ImportHelper.read(reader, BOAT.QUARTIER_IMMA); - String shipOwnerCode = ImportHelper.read(reader, BOAT.PER_COD); - String shipOwnerLastName = ImportHelper.read(reader, BOAT.PER_NOM); - 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); - - if (log.isDebugEnabled()) { - log.debug("Active : " + active + " (" + activeStr + ")"); - } - - // Find existing boat with immatriculation - Boat boat = boatDAO.findByImmatriculation(immatriculation); - - if (boat == null) { - boat = boatDAO.create(Boat.IMMATRICULATION, immatriculation); - result[1]++; - } - boat.setName(boatName); - boat.setDistrictCode(districtCode); - boat.setBuildYear(buildYear); - boat.setBoatLength(boatLength); - boat.setActive(active); - - // Find existing shipOwner with code - //ShipOwner shipOwner = shipOwnerDAO.findByCode(shipOwnerCode); - - ShipOwner shipOwner = availableShipOwners.get(shipOwnerCode); - - // If not available, select it from database - if (shipOwner == null) { - //shipOwner = new TopiaQuery(ShipOwner.class).add(ShipOwner.CODE, shipOwnerCode).executeToEntity(transaction); - shipOwner = shipOwnerDAO.findByCode(shipOwnerCode); - - // If not exist yet, create it - if (shipOwner == null) { - shipOwner = shipOwnerDAO.create(ShipOwner.CODE, shipOwnerCode); - } - - availableShipOwners.put(shipOwnerCode, shipOwner); - } - shipOwner.setFirstName(shipOwnerFirstName); - shipOwner.setLastName(shipOwnerLastName); - - boat.setShipOwner(shipOwner); - //transaction.commitTransaction(); - - if (result[0] % 1000 == 0) { - availableShipOwners.clear(); - - transaction.commitTransaction(); - tic = ImportHelper.logTimeAndMemory(log, tic, "navires ligne " + result[0]); - } - } - - // For the last rows - transaction.commitTransaction(); - - long stopTime = System.currentTimeMillis(); - - String execTime = DurationFormatUtils.formatDurationHMS(stopTime - startTime); - - if (log.isInfoEnabled()) { - log.info("Durée de l'import : " + execTime); - } - - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, - "Problème d'import du fichier CSV. Vérifiez l'en-tête du fichier : [ NAVS_COD,CARN_NOM," + - "CARN_LONGUEUR_HT,CARN_ANNEE,QUARTIER_IMMA,PER_COD,PER_NOM,PER_PRENOM,NAVS_ACTIVE ]"/* et l'encodage [ UTF-8 ] */ + - " Voir documentation pour plus de détails.", - eee); - } - return result; - } - - @Override - public InputStream exportBoatCsv(BoatFilter filter) throws SuiviObsmerException { - TopiaContext transaction = null; - InputStream result = null; - CsvWriter writer = null; - try { - transaction = rootContext.beginTransaction(); - - File file = File.createTempFile("wao-boats-", ".csv"); - file.deleteOnExit(); - - 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); - } - writer.write(header); - } - writer.endRecord(); - - // Get boats from database filterd by filter in argument - BoatDAO dao = SuiviObsmerModelDAOHelper.getBoatDAO(transaction); - TopiaQuery<Boat> query = dao.createQuery("B"); - query = filter.prepareQueryForBoat(query, "B"); - - // Reset limit : no pagination needed for results - List<Boat> boats = query.resetLimit().executeToEntityList(); - - int curr = 0; - for (Boat boat : boats) { - curr++; - String[] record = new String[ImportHelper.BOAT_NB_HEADERS]; - - if (log.isDebugEnabled()) { - log.debug("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 : ""; - - - 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(); - } - } - - writer.writeRecord(record); - writer.flush(); - } - result = new FileInputStream(file); - - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, - "Impossible d'exporter les navires sélectionnés", eee); - } finally { - if (writer != null) { - writer.close(); - } - } - return result; - } - - @Override - public void importActivityCalendarCsv(InputStream input) throws SuiviObsmerException { - if (!SuiviObsmerContext.isActivityCalendarImportRun()) { - try { - ActivityCalendarImport calendarImport = new ActivityCalendarImport(input); - new Thread(calendarImport).start(); - } catch (IOException eee) { - SuiviObsmerContext.serviceException(null, - "Problème d'import du fichier CSV des calendriers d'activité", eee); - } - } - } - - @Override - public ActivityCalendar getLastActivityCalendar(WaoUser user, Boat boat) throws SuiviObsmerException { - TopiaContext transaction = null; - ActivityCalendar result = null; - try { - transaction = rootContext.beginTransaction(); - - ActivityCalendarDAO dao = SuiviObsmerModelDAOHelper.getActivityCalendarDAO(transaction); - - TopiaQuery<ActivityCalendar> query = dao.createQuery("A"). - add("A." + ActivityCalendar.BOAT, boat); - - TopiaQuery<ActivityCalendar> subquery = dao.createQuery("B"). - setSelect("MAX(B." + ActivityCalendar.YEAR + ")"). - add("B." + ActivityCalendar.BOAT + " = A." + ActivityCalendar.BOAT). - addGroup("B." + ActivityCalendar.BOAT); - - query.add("A." + ActivityCalendar.YEAR + " = (" + subquery.fullQuery() + ")"); - - query.addLoad(ActivityCalendar.BOAT); - result = query.executeToEntity(transaction); - - // load other complex data from collections - List<ActivityMonth> months = result.getActivityMonth(); - for (ActivityMonth month : months) { - List<ActivityProfession> professions = month.getActivityProfession(); - for (ActivityProfession profession : professions) { - List<ActivityZone> zones = profession.getActivityZone(); - zones.size(); - } - } - - // Log ActivityCalendar access only for non admin user - if (!user.getAdmin()) { - Company company = user.getCompany(); - SuiviObsmerContext.addActivityCalendarAccessLog( - "Calendrier " + result.getYear() + " du navire " + - boat.getName() + " (" + boat.getImmatriculation() + ") vu " + - "par " + user.getFullName() + " de la société " + - company.getName()); - } - - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, - "Impossible de charger le dernier calendrier d'activité du navire " + - boat.getName() + " (" + boat.getImmatriculation() + ")", eee); - } - return result; - } - - @Override - public InputStream getActivityCalendarLogFile() throws FileNotFoundException { - String filename = SuiviObsmerContext.getProperty( - SuiviObsmerContext.PROP_FILENAME_LOG_ACTIVITY_IMPORT); - File file = new File(filename); - return new FileInputStream(file); - } - - @Override - public InputStream getActivityCalendarLogAccessFile() throws FileNotFoundException { - String filename = SuiviObsmerContext.getProperty( - SuiviObsmerContext.PROP_FILENAME_LOG_ACTIVITY_ACCESS); - File file = new File(filename); - return new FileInputStream(file); - } -} Copied: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceBoatImpl.java (from rev 337, trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/impl/ServiceBoatImpl.java) =================================================================== --- trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceBoatImpl.java (rev 0) +++ trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceBoatImpl.java 2010-02-09 01:30:52 UTC (rev 339) @@ -0,0 +1,629 @@ +/* + * *##% + * 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.services; + +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 org.nuiton.topia.TopiaException; +import org.nuiton.topia.framework.TopiaQuery; +import org.nuiton.topia.framework.TopiaQuery.Op; +import fr.ifremer.suiviobsmer.bean.BoatFilter; +import fr.ifremer.suiviobsmer.bean.CompanyBoatInfos; +import fr.ifremer.suiviobsmer.bean.CompanyBoatInfosImpl; +import fr.ifremer.suiviobsmer.entity.*; +import fr.ifremer.suiviobsmer.services.ServiceBoat; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.time.DurationFormatUtils; +import org.nuiton.topia.TopiaContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * ServiceBoatImpl + * + * Created: 24 nov. 2009 + * + * @author fdesbois + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ +public class ServiceBoatImpl implements ServiceBoat { + + private static final Logger log = LoggerFactory.getLogger(ServiceBoatImpl.class); + + protected TopiaContext rootContext; + + public ServiceBoatImpl() throws SuiviObsmerException { + rootContext = SuiviObsmerContext.getTopiaRootContext(); + } + + @Override + public Map<Integer, Boat> getBoatsByFilter(BoatFilter filter) throws SuiviObsmerException { + TopiaContext transaction = null; + Map<Integer, Boat> results = new HashMap<Integer, Boat>(); + try { + transaction = rootContext.beginTransaction(); + + BoatDAO dao = SuiviObsmerModelDAOHelper.getBoatDAO(transaction); + TopiaQuery query = dao.createQuery("B"); + + query = createQueryForBoatFilter(query, filter); + + if (StringUtils.isNotEmpty(filter.getOrderBy())) { + query.addOrder("B." + filter.getOrderBy()); + } + + query.addLoad(Boat.ACTIVITY_CALENDAR); + + if (log.isDebugEnabled()) { + log.debug("Query : " + query); + } + + results = dao.findAllMappedByQuery(query, Boat.IMMATRICULATION, Integer.class); + + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, "Impossible de filtrer la liste des navires", eee); + } + return results; + } + + @Override + public int getNbBoatsByFilter(BoatFilter filter) throws SuiviObsmerException { + TopiaContext transaction = null; + int result = 0; + try { + transaction = rootContext.beginTransaction(); + + BoatDAO dao = SuiviObsmerModelDAOHelper.getBoatDAO(transaction); + TopiaQuery query = dao.createQuery("B"); + + query = createQueryForBoatFilter(query, filter); + + result = query.executeCount(); + + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, "Impossible de filtrer la liste des navires", eee); + } + return result; + } + + protected TopiaQuery createQueryForBoatFilter(TopiaQuery query, BoatFilter filter) throws TopiaException { + String main = query.getMainAlias(); + query = filter.prepareQueryForBoat(query, main).addDistinct(); + + // Sampling filter + if (filter.isSamplingFiltered()) { + // Add join for ElligibleBoat + //String elligibleBoatClassName = ElligibleBoat.class.getName(); + query.addFrom(ElligibleBoat.class, "E").add("E." + ElligibleBoat.BOAT + " = " + main); + query = filter.prepareQueryForSampling(query, "E." + ElligibleBoat.SAMPLE_ROW); + + // Company + if (filter.getCompany() != null) { + //query.add("E." + ElligibleBoat.SAMPLE_ROW + "." + SampleRow.COMPANY, filter.getCompany()); + // Test only valid ElligibleBoat for that company + query.add("E." + ElligibleBoat.COMPANY_ACTIVE + " = :booleanTrue " + + "OR (E." + ElligibleBoat.COMPANY_ACTIVE + " IS NULL AND E." + ElligibleBoat.GLOBAL_ACTIVE + " = :booleanTrue)"); + query.addParam("booleanTrue", Boolean.TRUE); + } + } + + return query; + } + + /** + * Get boat infos and elligible boats for a company and a boat. This method + * is useful to get sampleRows elligibles for the boat. Only sampleRows not + * closed linked with the company argument will be returned. The result give + * a Map with sampleRowCode in key and ElligibleBoat in value. + * The ElligibleBoat entity contains the SampleRow and attributes useful + * to know if the link is active or specific for the company. + * + * @param boatImmatriculation immatriculation of the boat + * @param company the Company to filter the ElligibleBoats + * @return an ElligibleBoatsCompany wich contains the map of ElligibleBoat, + * the company and an empty list for deleted elements. + */ + @Override + public CompanyBoatInfos getCompanyBoatInfos(int boatImmatriculation, Company company) + throws SuiviObsmerException { + + Map<String, ElligibleBoat> elligibleBoats = new HashMap<String, ElligibleBoat>(); + CompanyBoatInfos result = new CompanyBoatInfosImpl(); + result.setCompany(company); + result.setElligibleBoats(elligibleBoats); + result.setDeletedElligibleBoats(new ArrayList<ElligibleBoat>()); + + TopiaContext transaction = null; + try { + transaction = rootContext.beginTransaction(); + + BoatDAO dao = SuiviObsmerModelDAOHelper.getBoatDAO(transaction); + + Boat boat = dao.findByImmatriculation(boatImmatriculation); + + BoatInfosDAO boatInfosDAO = SuiviObsmerModelDAOHelper.getBoatInfosDAO(transaction); + BoatInfos boatInfos = boatInfosDAO.findByProperties( + BoatInfos.BOAT, boat, BoatInfos.COMPANY, company); + if (boatInfos == null) { + boatInfos = new BoatInfosImpl(); + boatInfos.setBoat(boat); + boatInfos.setCompany(company); + } else { + // load data + boatInfos.getBoat(); + } + // load data + boatInfos.getBoat().sizeActivityCalendar(); + + result.setBoatInfos(boatInfos); + + for (ElligibleBoat elligible : boat.getElligibleBoat()) { + SampleRow sampleRow = elligible.getSampleRow(); + + // SampleRow non closed only + //if (!sampleRow.isFinished()) { + + String companyId = sampleRow.getCompany() != null ? + sampleRow.getCompany().getTopiaId() : ""; + + if (companyId.equals(company.getTopiaId())) { + elligibleBoats.put(sampleRow.getCode(), elligible); + } + //} + } + + // Last contact + ContactDAO contactDAO = SuiviObsmerModelDAOHelper.getContactDAO(transaction); + TopiaQuery query = contactDAO.createQueryLastContactForBoat(boat, company). + addLoad(Contact.SAMPLE_ROW, Contact.OBSERVER); + + Contact contact = contactDAO.findByQuery(query); + + if (contact != null) { + result.setLastContact(contact); + } + + + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, + "Impossible de récupérer les informations du navire " + + "immatriculé '" + boatImmatriculation + "'" + + " pour la société '" + company.getName() + "'", eee); + } + return result; + } + + @Override + public void createUpdateCompanyBoatInfos(CompanyBoatInfos companyBoatInfos) + throws SuiviObsmerException { + TopiaContext transaction = null; + try { + transaction = rootContext.beginTransaction(); + + BoatInfosDAO dao = SuiviObsmerModelDAOHelper.getBoatInfosDAO(transaction); + + BoatInfos boatInfos = companyBoatInfos.getBoatInfos(); + SuiviObsmerContext.prepareTopiaId(BoatInfos.class, boatInfos); + dao.update(boatInfos); + + ElligibleBoatDAO elligibleDAO = SuiviObsmerModelDAOHelper.getElligibleBoatDAO(transaction); + + for (ElligibleBoat elligible : companyBoatInfos.getElligibleBoatsValues()) { + SuiviObsmerContext.prepareTopiaId(ElligibleBoat.class, elligible); + elligibleDAO.update(elligible); + } + + // Delete ElligibleBoats for the company + for (ElligibleBoat elligible : companyBoatInfos.getDeletedElligibleBoats()) { + elligibleDAO.delete(elligible); + } + + transaction.commitTransaction(); + transaction.closeContext(); + } catch (Exception eee) { + Boat boat = companyBoatInfos.getBoatInfos().getBoat(); + Company company = companyBoatInfos.getCompany(); + SuiviObsmerContext.serviceException(transaction, + "Impossible de créer ou modifier les informations liés au navire " + + boat.getImmatriculation() + " pour la société " + company.getName(), eee); + } + } + + @Override + public List<Boat> getBoatsByImmatriculations(String immatriculations) throws SuiviObsmerException { + List<Boat> boats = new ArrayList<Boat>(); + TopiaContext transaction = null; + if (StringUtils.isEmpty(immatriculations)) { + return boats; + } + try { + transaction = rootContext.beginTransaction(); + + BoatDAO dao = SuiviObsmerModelDAOHelper.getBoatDAO(transaction); + + Pattern pattern = Pattern.compile("\\d{6}"); + Matcher matcher = pattern.matcher(immatriculations); + while(matcher.find()) { + String res = matcher.group(); + int immatriculation = Integer.parseInt(res); + Boat boat = dao.findByImmatriculation(immatriculation); + if (boat == null) { + throw new SuiviObsmerBusinessException(Type.NOT_EXISTS, ServiceBoat.class, + "Immatriculation " + immatriculation + " incorrect, ne référence aucun navire"); + } + boats.add(boat); + } + + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, + "La chaîne d'immatriculations est incorrect ! Chaque immatriculation doit posséder 6 chiffres", eee); + } + return boats; + } + + @Override + public Boat getBoat(String boatId) throws SuiviObsmerException { + TopiaContext transaction = null; + Boat result = null; + try { + transaction = rootContext.beginTransaction(); + + BoatDAO dao = SuiviObsmerModelDAOHelper.getBoatDAO(transaction); + + result = dao.findByTopiaId(boatId); + + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, "Impossible de charger le navire", eee); + } + return result; + } + + @Override + public List<String> getBoatNamesStartWith(String input) throws SuiviObsmerException { + TopiaContext transaction = null; + List<String> results = new ArrayList<String>(); + try { + transaction = rootContext.beginTransaction(); + + input = StringUtils.upperCase(input); + + BoatDAO dao = SuiviObsmerModelDAOHelper.getBoatDAO(transaction); + + results = (List<String>)dao.createQuery().addDistinct().setSelect(Boat.NAME).add(Boat.NAME, Op.LIKE, input + "%").execute(); + + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, + "Impossible de récupérer les navires avec un nom commencant par '" + input + "'", eee); + } + return results; + } + + /** + * Import boats from a CSV file. Warning, must be UTF-8 encoding. + * Use of CsvReader to manage InputStream and create or update boats. + * Header file must be : NAVS_COD,CARN_NOM,CARN_LONGUEUR_HT,CARN_ANNEE, + * QUARTIER_IMMA,PER_COD, PER_NOM,PER_PRENOM. + * Existing boats (with same immatriculation) are updated. + * + * @param input Stream corresponding to Csv file + * @return an array with two int : the first corresponding to total number + * of boats imported and the second corresponding only to new boats added. + * @throws SuiviObsmerException + * @see com.csvreader.CsvReader + */ + @Override + public int[] importBoatCsv(InputStream input) throws SuiviObsmerException { + TopiaContext transaction = null; + int[] result = new int[]{0,0}; + try { + transaction = rootContext.beginTransaction(); + + CsvReader reader = new CsvReader(input, Charset.forName("UTF-8")); + reader.readHeaders(); + + long startTime = System.currentTimeMillis(); + long tic; + + BoatDAO boatDAO = SuiviObsmerModelDAOHelper.getBoatDAO(transaction); + ShipOwnerDAO shipOwnerDAO = SuiviObsmerModelDAOHelper.getShipOwnerDAO(transaction); + + Map<String, ShipOwner> availableShipOwners = new HashMap<String, ShipOwner>(); + + tic = System.currentTimeMillis(); + while(reader.readRecord()) { + result[0]++; + +// if (log.isTraceEnabled()) { +// log.trace(" " + Arrays.asList(reader.getValues())); +// } + + + int immatriculation = ImportHelper.readInt(reader, BOAT.NAVS_COD); + String boatName = ImportHelper.read(reader, BOAT.CARN_NOM); + int boatLength = ImportHelper.readInt(reader, BOAT.CARN_LONGUEUR_HT); + int buildYear = ImportHelper.readInt(reader, BOAT.CARN_ANNEE); + String districtCode = ImportHelper.read(reader, BOAT.QUARTIER_IMMA); + String shipOwnerCode = ImportHelper.read(reader, BOAT.PER_COD); + String shipOwnerLastName = ImportHelper.read(reader, BOAT.PER_NOM); + 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); + + if (log.isDebugEnabled()) { + log.debug("Active : " + active + " (" + activeStr + ")"); + } + + // Find existing boat with immatriculation + Boat boat = boatDAO.findByImmatriculation(immatriculation); + + if (boat == null) { + boat = boatDAO.create(Boat.IMMATRICULATION, immatriculation); + result[1]++; + } + boat.setName(boatName); + boat.setDistrictCode(districtCode); + boat.setBuildYear(buildYear); + boat.setBoatLength(boatLength); + boat.setActive(active); + + // Find existing shipOwner with code + //ShipOwner shipOwner = shipOwnerDAO.findByCode(shipOwnerCode); + + ShipOwner shipOwner = availableShipOwners.get(shipOwnerCode); + + // If not available, select it from database + if (shipOwner == null) { + //shipOwner = new TopiaQuery(ShipOwner.class).add(ShipOwner.CODE, shipOwnerCode).executeToEntity(transaction); + shipOwner = shipOwnerDAO.findByCode(shipOwnerCode); + + // If not exist yet, create it + if (shipOwner == null) { + shipOwner = shipOwnerDAO.create(ShipOwner.CODE, shipOwnerCode); + } + + availableShipOwners.put(shipOwnerCode, shipOwner); + } + shipOwner.setFirstName(shipOwnerFirstName); + shipOwner.setLastName(shipOwnerLastName); + + boat.setShipOwner(shipOwner); + //transaction.commitTransaction(); + + if (result[0] % 1000 == 0) { + availableShipOwners.clear(); + + transaction.commitTransaction(); + tic = ImportHelper.logTimeAndMemory(log, tic, "navires ligne " + result[0]); + } + } + + // For the last rows + transaction.commitTransaction(); + + long stopTime = System.currentTimeMillis(); + + String execTime = DurationFormatUtils.formatDurationHMS(stopTime - startTime); + + if (log.isInfoEnabled()) { + log.info("Durée de l'import : " + execTime); + } + + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, + "Problème d'import du fichier CSV. Vérifiez l'en-tête du fichier : [ NAVS_COD,CARN_NOM," + + "CARN_LONGUEUR_HT,CARN_ANNEE,QUARTIER_IMMA,PER_COD,PER_NOM,PER_PRENOM,NAVS_ACTIVE ]"/* et l'encodage [ UTF-8 ] */ + + " Voir documentation pour plus de détails.", + eee); + } + return result; + } + + @Override + public InputStream exportBoatCsv(BoatFilter filter) throws SuiviObsmerException { + TopiaContext transaction = null; + InputStream result = null; + CsvWriter writer = null; + try { + transaction = rootContext.beginTransaction(); + + File file = File.createTempFile("wao-boats-", ".csv"); + file.deleteOnExit(); + + 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); + } + writer.write(header); + } + writer.endRecord(); + + // Get boats from database filterd by filter in argument + BoatDAO dao = SuiviObsmerModelDAOHelper.getBoatDAO(transaction); + TopiaQuery query = dao.createQuery("B"); + query = filter.prepareQueryForBoat(query, "B"); + + // Reset limit : no pagination needed for results + query.resetLimit(); + List<Boat> boats = dao.findAllByQuery(query); + + for (Boat boat : boats) { + String[] record = new String[ImportHelper.BOAT_NB_HEADERS]; + + if (log.isDebugEnabled()) { + log.debug("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 : ""; + + + 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(); + } + } + + writer.writeRecord(record); + writer.flush(); + } + result = new FileInputStream(file); + + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, + "Impossible d'exporter les navires sélectionnés", eee); + } finally { + if (writer != null) { + writer.close(); + } + } + return result; + } + + @Override + public void importActivityCalendarCsv(InputStream input) throws SuiviObsmerException { + if (!SuiviObsmerContext.isActivityCalendarImportRun()) { + try { + ActivityCalendarImport calendarImport = new ActivityCalendarImport(input); + new Thread(calendarImport).start(); + } catch (IOException eee) { + SuiviObsmerContext.serviceException(null, + "Problème d'import du fichier CSV des calendriers d'activité", eee); + } + } + } + + @Override + public ActivityCalendar getLastActivityCalendar(WaoUser user, Boat boat) throws SuiviObsmerException { + TopiaContext transaction = null; + ActivityCalendar result = null; + try { + transaction = rootContext.beginTransaction(); + + ActivityCalendarDAO dao = SuiviObsmerModelDAOHelper.getActivityCalendarDAO(transaction); + + TopiaQuery query = dao.createQuery("A"). + add("A." + ActivityCalendar.BOAT, boat); + + TopiaQuery subquery = dao.createQuery("B"). + setSelect("MAX(B." + ActivityCalendar.YEAR + ")"). + add("B." + ActivityCalendar.BOAT + " = A." + ActivityCalendar.BOAT). + addGroup("B." + ActivityCalendar.BOAT); + + query.add("A." + ActivityCalendar.YEAR + " = (" + subquery.fullQuery() + ")"); + + query.addLoad(ActivityCalendar.BOAT); + result = dao.findByQuery(query); + + // load other complex data from collections + List<ActivityMonth> months = result.getActivityMonth(); + for (ActivityMonth month : months) { + List<ActivityProfession> professions = month.getActivityProfession(); + for (ActivityProfession profession : professions) { + List<ActivityZone> zones = profession.getActivityZone(); + zones.size(); + } + } + + // Log ActivityCalendar access only for non admin user + if (!user.getAdmin()) { + Company company = user.getCompany(); + SuiviObsmerContext.addActivityCalendarAccessLog( + "Calendrier " + result.getYear() + " du navire " + + boat.getName() + " (" + boat.getImmatriculation() + ") vu " + + "par " + user.getFullName() + " de la société " + + company.getName()); + } + + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, + "Impossible de charger le dernier calendrier d'activité du navire " + + boat.getName() + " (" + boat.getImmatriculation() + ")", eee); + } + return result; + } + + @Override + public InputStream getActivityCalendarLogFile() throws FileNotFoundException { + String filename = SuiviObsmerContext.getProperty( + SuiviObsmerContext.PROP_FILENAME_LOG_ACTIVITY_IMPORT); + File file = new File(filename); + return new FileInputStream(file); + } + + @Override + public InputStream getActivityCalendarLogAccessFile() throws FileNotFoundException { + String filename = SuiviObsmerContext.getProperty( + SuiviObsmerContext.PROP_FILENAME_LOG_ACTIVITY_ACCESS); + File file = new File(filename); + return new FileInputStream(file); + } +} Deleted: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceContactImpl.java =================================================================== --- trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/impl/ServiceContactImpl.java 2010-02-04 21:33:50 UTC (rev 325) +++ trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceContactImpl.java 2010-02-09 01:30:52 UTC (rev 339) @@ -1,534 +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.impl; - -import com.csvreader.CsvReader; -import com.csvreader.CsvWriter; -import fr.ifremer.suiviobsmer.ImportHelper; -import fr.ifremer.suiviobsmer.ImportHelper.*; -import fr.ifremer.suiviobsmer.SuiviObsmerBusinessException; -import fr.ifremer.suiviobsmer.SuiviObsmerBusinessException.Type; -import fr.ifremer.suiviobsmer.SuiviObsmerException; -import fr.ifremer.suiviobsmer.SuiviObsmerModelDAOHelper; -import fr.ifremer.suiviobsmer.SuiviObsmerContext; -import fr.ifremer.suiviobsmer.bean.ContactState; -import java.io.IOException; -import java.io.InputStream; -import org.nuiton.topia.framework.TopiaQuery; -import fr.ifremer.suiviobsmer.bean.states.ContactStateEnum; -import fr.ifremer.suiviobsmer.bean.ContactFilter; -import fr.ifremer.suiviobsmer.bean.ImportResults; -import fr.ifremer.suiviobsmer.bean.ImportResultsImpl; -import fr.ifremer.suiviobsmer.entity.Boat; -import fr.ifremer.suiviobsmer.entity.BoatDAO; -import fr.ifremer.suiviobsmer.entity.Company; -import fr.ifremer.suiviobsmer.entity.CompanyDAO; -import fr.ifremer.suiviobsmer.entity.Contact; -import fr.ifremer.suiviobsmer.entity.ContactDAO; -import fr.ifremer.suiviobsmer.entity.ContactImpl; -import fr.ifremer.suiviobsmer.entity.ElligibleBoat; -import fr.ifremer.suiviobsmer.entity.ElligibleBoatDAO; -import fr.ifremer.suiviobsmer.entity.FishingZone; -import fr.ifremer.suiviobsmer.entity.Profession; -import fr.ifremer.suiviobsmer.entity.SampleRow; -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 java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.nio.charset.Charset; -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.Collection; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.apache.commons.lang.BooleanUtils; -import org.apache.commons.lang.StringUtils; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.persistence.TopiaEntity; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * ServiceContactImpl - * - * Created: 3 déc. 2009 - * - * @author fdesbois - * @version $Revision$ - * - * Mise a jour: $Date$ - * par : $Author$ - */ -public class ServiceContactImpl implements ServiceContact { - - private static final Logger log = LoggerFactory.getLogger(ServiceContactImpl.class); - - protected TopiaContext rootContext; - - public ServiceContactImpl() throws SuiviObsmerException { - rootContext = SuiviObsmerContext.getTopiaRootContext(); - } - - @Override - public Map<String, Contact> getContacts(ContactFilter filter) throws SuiviObsmerException { - Map<String, Contact> results = new HashMap<String, Contact>(); - TopiaContext transaction = null; - try { - transaction = rootContext.beginTransaction(); - - ContactDAO dao = SuiviObsmerModelDAOHelper.getContactDAO(transaction); - - TopiaQuery<Contact> query = dao.createQuery("C").addDistinct(); - - query = filter.prepareQueryForContact(query); - - query.addOrderDesc("C." + TopiaEntity.TOPIA_CREATE_DATE).addLoad(Contact.OBSERVER + "." + WaoUser.COMPANY); - - if (log.isDebugEnabled()) { - log.debug("Query : " + query); - } - - results = query.executeToEntityMap(); - - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, - "Impossible de filtrer la liste des contacts", eee); - } - return results; - } - - @Override - public int getNbContacts(ContactFilter filter) throws SuiviObsmerException { - TopiaContext transaction = null; - int result = 0; - try { - transaction = rootContext.beginTransaction(); - - ContactDAO dao = SuiviObsmerModelDAOHelper.getContactDAO(transaction); - TopiaQuery<Contact> query = dao.createQuery("C"); - query = filter.prepareQueryForContact(query); - - result = query.executeCount(); - - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, - "Impossible de compter le nombre de contacts filtrés", eee); - } - return result; - } - - @Override - public Contact getNewContact(WaoUser user, SampleRow row, Boat boat) { - Contact result = new ContactImpl(); - result.setObserver(user); - result.setSampleRow(row); - result.setBoat(boat); - result.setState(ContactStateEnum.CONTACT_START.getStringValue()); - return result; - } - - @Override - public void saveContact(Contact contact, boolean delete) throws SuiviObsmerException { - TopiaContext transaction = null; - try { - transaction = rootContext.beginTransaction(); - - ContactDAO dao = SuiviObsmerModelDAOHelper.getContactDAO(transaction); - - if (log.isDebugEnabled()) { - log.debug("Create date : " + contact.getTopiaCreateDate()); - } - - SuiviObsmerContext.prepareTopiaId(Contact.class, contact); - if (delete) { - dao.delete(contact); - } else { - dao.update(contact); - } - - transaction.commitTransaction(); - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, - "Impossible de sauvegarder le contact", eee); - } - } - - @Override - public InputStream exportContactCsv(ContactFilter filter) - throws SuiviObsmerException { - TopiaContext transaction = null; - InputStream result = null; - CsvWriter writer = null; - try { - transaction = rootContext.beginTransaction(); - - // No contacts from arguments, select all existing from database -// if (contacts == null) { -// ContactDAO dao = SuiviObsmerModelDAOHelper.getContactDAO(transaction); -// if (user.getAdmin()) { -// contacts = dao.findAll(); -// } else { -// // Filtered by company for a simple user -// contacts = dao.createQuery().add(Contact.OBSERVER + "." + WaoUser.COMPANY, user.getCompany()). -// executeToEntityList(); -// } -// } - - //String alea = SuiviObsmerContext.createRandomString(16); - //String filename = "/tmp/wao-contacts-" + alea + ".csv"; - File file = File.createTempFile("wao-contacts-", ".csv"); - file.deleteOnExit(); - - if (log.isDebugEnabled()) { - log.debug("Export contacts into : " + file.getAbsolutePath()); - } - - 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(); - - - DateFormat dateFormat = ImportHelper.getContactDateFormat(); - - // Get contacts from database - ContactDAO dao = SuiviObsmerModelDAOHelper.getContactDAO(transaction); - TopiaQuery<Contact> query = dao.createQuery("C"); - - // No page limit in this case - query = filter.prepareQueryForContact(query).resetLimit(); - - if (log.isDebugEnabled()) { - log.debug("Exec query : " + query); - } - - List<Contact> contacts = query.executeToEntityList(); - - int curr = 0; - for (Contact contact : contacts) { - curr++; - String[] record = new String[ImportHelper.CONTACT_NB_HEADERS]; - - // 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(); - if (contact.getTideBeginDate() != null) { - record[CONTACT.CONT_DEBUT_MAREE.forContactCsv()] = dateFormat.format(contact.getTideBeginDate()); - } - if (contact.getTideEndDate() != null) { - record[CONTACT.CONT_FIN_MAREE.forContactCsv()] = 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(); - if (contact.getDataInputDate() != null) { - record[CONTACT.CONT_ALLEGRO.forContactCsv()] = dateFormat.format(contact.getDataInputDate()); - } - record[CONTACT.CONT_SOCIETE_VALID.forContactCsv()] = - ImportHelper.formatContactValidation(contact.getValidationCompany()); - record[CONTACT.CONT_PROGRAM_VALID.forContactCsv()] = - ImportHelper.formatContactValidation(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(); - - // 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(); - - // FishingZone part - List<FishingZone> zones = row.getFishingZone(); - String fishingDistrict = ""; - for (FishingZone zone : zones) { - fishingDistrict += 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; - - // 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(); - - // 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(); - - writer.writeRecord(record); - writer.flush(); - } - result = new FileInputStream(file); - - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, - "Impossible d'exporter les contacts", eee); - } finally { - if (writer != null) { - writer.close(); - } - } - return result; - } - - @Override - public ImportResults importContactCsv(WaoUser user, InputStream input) throws SuiviObsmerException { - TopiaContext transaction = null; - ImportResults result = new ImportResultsImpl(); - int currRow = 1; - CsvReader reader = null; - try { - transaction = rootContext.beginTransaction(); - - reader = new CsvReader(input, Charset.forName("UTF-8")); - reader.readHeaders(); - - ContactDAO dao = SuiviObsmerModelDAOHelper.getContactDAO(transaction); - WaoUserDAO userDAO = SuiviObsmerModelDAOHelper.getWaoUserDAO(transaction); - CompanyDAO companyDAO = SuiviObsmerModelDAOHelper.getCompanyDAO(transaction); - SampleRowDAO rowDAO = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); - BoatDAO boatDAO = SuiviObsmerModelDAOHelper.getBoatDAO(transaction); - - DateFormat dateFormat = ImportHelper.getContactDateFormat(); - - long tic; - tic = System.currentTimeMillis(); - while(reader.readRecord()) { - currRow++; - - String observerId = ImportHelper.read(reader, CONTACT.OBSERV_ID); - String state = ImportHelper.read(reader, CONTACT.CONT_ETAT); - - ContactState contactState = ContactState.createContactStateEnum(state); - - if (contactState == null) { - throw new SuiviObsmerBusinessException(Type.IMPORT_ERROR, this.getClass(), - "Erreur ligne " + currRow + " : " + - "Etat du contact invalide '" + state + "', valeurs possibles : " + - ContactState.availableStates()); - } - - WaoUser observer = userDAO.findByLogin(observerId); - if (observer != null) { - Company company = user.getCompany(); - // For an admin, get the company from database - if (user.getAdmin()) { - // FIXME-FD20100104 findContains not optimized in TopiaDAOImpl - company = companyDAO.findContainsWaoUser(observer); - // For a user, check if the observer as the same company as the current user - } else if (!observer.getCompany().equals(company)) { - throw new SuiviObsmerBusinessException(Type.IMPORT_ERROR, this.getClass(), - "Erreur ligne " + currRow + " : " + - "L'observateur avec pour login '" + observerId + "' n'appartient pas à votre société !"); - } - - if (company != null) { - String rowCode = ImportHelper.readSampleRowCode(reader); - - SampleRow row = rowDAO.findByProperties(SampleRow.CODE, rowCode, SampleRow.COMPANY, company); - - if (row != null) { - int boatImmatriculation = ImportHelper.readInt(reader, BOAT.NAVS_COD); - - Boat boat = boatDAO.findByImmatriculation(boatImmatriculation); - - if (boat != null) { - - ElligibleBoatDAO elligibleDAO = SuiviObsmerModelDAOHelper.getElligibleBoatDAO(transaction); - ElligibleBoat elligible = elligibleDAO.findByProperties( - ElligibleBoat.BOAT, boat, ElligibleBoat.SAMPLE_ROW, row); - - if (elligible == null) { - // Create new elligible boat not active in a global way - elligible = elligibleDAO.create( - ElligibleBoat.BOAT, boat, ElligibleBoat.SAMPLE_ROW, row); - if (log.isTraceEnabled()) { - log.trace("Create elligibleBoat for : " + boat.getImmatriculation() + " - " + row.getCode()); - } - } - elligible.setCompanyActive(Boolean.TRUE); - - Contact contact = null; - - String createDateString = ImportHelper.read(reader, CONTACT.CONT_CREATION); - String contactCode = ImportHelper.read(reader, CONTACT.CONT_CODE); - Date createDate = ImportHelper.parseContactCreateDate(contactCode, createDateString); - - if (log.isDebugEnabled()) { - log.debug("Ligne " + currRow + " : Create date : " + createDate); - } - - if (/*!StringUtils.isEmpty(contactCode) && */StringUtils.isNotEmpty(createDateString)) { - // Get entity from database - contact = dao.createQuery(). - add(TopiaEntity.TOPIA_CREATE_DATE, createDate). - add(Contact.OBSERVER + "." + WaoUser.COMPANY, company). - add(Contact.BOAT, boat). - add(Contact.SAMPLE_ROW, row). - executeToEntity(); - } - - if (contact != null && contact.getValidationCompany() != null) { - result.addError(currRow, "Le contact est déjà validé dans l'application et ne peut pas être importé"); - result.incNbRefused(); - continue; - } - - // new contact to import - boolean newContact = false; - if (contact == null) { - contact = dao.create( - TopiaEntity.TOPIA_CREATE_DATE, createDate, - Contact.SAMPLE_ROW, row, - Contact.BOAT, boat); - newContact = true; - } - - Date tideBegin = ImportHelper.readDate(reader, CONTACT.CONT_DEBUT_MAREE); - Date tideEnd = ImportHelper.readDate(reader, CONTACT.CONT_FIN_MAREE); - Date dataInput = ImportHelper.readDate(reader, CONTACT.CONT_ALLEGRO); - int nbObservants = ImportHelper.readInt(reader, CONTACT.CONT_NB_OBSERV); - if (nbObservants == -1) { - nbObservants = 0; - } - boolean mammalsCapture = - ImportHelper.parseContactMammals(reader, CONTACT.CONT_MAM_CAPT); - boolean mammalsObsv = - ImportHelper.parseContactMammals(reader, CONTACT.CONT_MAM_OBS); - - contact.setObserver(observer); - contact.setState(state); - contact.setTideBeginDate(tideBegin); - contact.setTideEndDate(tideEnd); - contact.setNbObservants(nbObservants); - contact.setMammalsCapture(mammalsCapture); - contact.setMammalsObservation(mammalsObsv); - contact.setDataInputDate(dataInput); - - // Import validations only for superadmin and a new contact : useful for archives - if (newContact && user.getAdmin() && user.getLogin().equals("admin")) { - if (log.isDebugEnabled()) { - log.debug("SuperAdmin import :: validations"); - } - Boolean companyValidation = ImportHelper.parseContactValidation(reader, CONTACT.CONT_SOCIETE_VALID); - Boolean programValidation = ImportHelper.parseContactValidation(reader, CONTACT.CONT_PROGRAM_VALID); - contact.setValidationCompany(companyValidation); - contact.setValidationProgram(programValidation); - - // Add realTideTime for this contact if validations are ok and state is BOARDING_DONE - if (BooleanUtils.isTrue(companyValidation) && BooleanUtils.isNotFalse(programValidation) && - contact.getState().equals(ContactState.BOARDING_DONE.toString())) { - boolean ok = contact.getSampleRow().addRealTideTime(contact); - if (!ok) { - DateFormat dateFormat1 = new SimpleDateFormat("MM/yyyy"); - result.addError(currRow, "Impossible de mettre à jour le nombre de marée réels, vérifiez le mois " + - "de " + dateFormat1.format(contact.getTideBeginDate()) + " pour la ligne du plan " + row.getCode()); - result.incNbRefused(); - continue; - } - } - } - - result.incNbImported(); - - } else { - result.addError(currRow, "Navire inexistant avec l'immatriculation : " + boatImmatriculation); - result.incNbRefused(); - } - } else { - result.addError(currRow, "Ligne d'échantillon inexistante ou incompatible avec la société " + - "pour le code : " + rowCode); - result.incNbRefused(); - } - } else { - result.addError(currRow, "Cet utilisateur n'est lié à aucune société : " + user.getFullName()); - result.incNbRefused(); - } - } else { - result.addError(currRow, "Utilisateur inexistant avec l'identifiant : " + observerId); - result.incNbRefused(); - } - - if (result.getNbRowsImported() % 1000 == 0) { - transaction.commitTransaction(); - tic = ImportHelper.logTimeAndMemory(log, tic, "contacts ligne " + currRow); - } - } - - transaction.commitTransaction(); - - transaction.closeContext(); - } catch (ParseException eee) { - SuiviObsmerContext.serviceException(transaction, - "Erreur ligne " + currRow + " : " + - "Le format des dates est incorrect, il doit être de la forme : JJ/MM/AAAA", eee); - } catch (Exception eee) { - if (log.isDebugEnabled()) { - try { - log.debug("Ligne : " + currRow + " :: " + Arrays.toString(reader.getValues())); - } catch (IOException ex) { - log.error("Reader error", ex); - } - } - SuiviObsmerContext.serviceException(transaction, - "Impossible d'importer les contacts", eee); - } - return result; - } - -} Copied: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceContactImpl.java (from rev 337, trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/impl/ServiceContactImpl.java) =================================================================== --- trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceContactImpl.java (rev 0) +++ trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceContactImpl.java 2010-02-09 01:30:52 UTC (rev 339) @@ -0,0 +1,514 @@ +/* + * *##% + * 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.services; + +import com.csvreader.CsvReader; +import com.csvreader.CsvWriter; +import fr.ifremer.suiviobsmer.ImportHelper; +import fr.ifremer.suiviobsmer.ImportHelper.*; +import fr.ifremer.suiviobsmer.SuiviObsmerBusinessException; +import fr.ifremer.suiviobsmer.SuiviObsmerBusinessException.Type; +import fr.ifremer.suiviobsmer.SuiviObsmerException; +import fr.ifremer.suiviobsmer.SuiviObsmerModelDAOHelper; +import fr.ifremer.suiviobsmer.SuiviObsmerContext; +import fr.ifremer.suiviobsmer.bean.ContactState; +import java.io.IOException; +import java.io.InputStream; +import org.nuiton.topia.framework.TopiaQuery; +import fr.ifremer.suiviobsmer.bean.ContactFilter; +import fr.ifremer.suiviobsmer.bean.ImportResults; +import fr.ifremer.suiviobsmer.bean.ImportResultsImpl; +import fr.ifremer.suiviobsmer.entity.Boat; +import fr.ifremer.suiviobsmer.entity.BoatDAO; +import fr.ifremer.suiviobsmer.entity.Company; +import fr.ifremer.suiviobsmer.entity.CompanyDAO; +import fr.ifremer.suiviobsmer.entity.Contact; +import fr.ifremer.suiviobsmer.entity.ContactDAO; +import fr.ifremer.suiviobsmer.entity.ContactImpl; +import fr.ifremer.suiviobsmer.entity.ElligibleBoat; +import fr.ifremer.suiviobsmer.entity.ElligibleBoatDAO; +import fr.ifremer.suiviobsmer.entity.FishingZone; +import fr.ifremer.suiviobsmer.entity.Profession; +import fr.ifremer.suiviobsmer.entity.SampleRow; +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 java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.nio.charset.Charset; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.apache.commons.lang.BooleanUtils; +import org.apache.commons.lang.StringUtils; +import org.nuiton.topia.TopiaContext; +import org.nuiton.topia.persistence.TopiaEntity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * ServiceContactImpl + * + * Created: 3 déc. 2009 + * + * @author fdesbois + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ +public class ServiceContactImpl implements ServiceContact { + + private static final Logger log = LoggerFactory.getLogger(ServiceContactImpl.class); + + protected TopiaContext rootContext; + + public ServiceContactImpl() throws SuiviObsmerException { + rootContext = SuiviObsmerContext.getTopiaRootContext(); + } + + @Override + public Map<String, Contact> getContacts(ContactFilter filter) throws SuiviObsmerException { + Map<String, Contact> results = new HashMap<String, Contact>(); + TopiaContext transaction = null; + try { + transaction = rootContext.beginTransaction(); + + ContactDAO dao = SuiviObsmerModelDAOHelper.getContactDAO(transaction); + + TopiaQuery query = dao.createQuery("C").addDistinct(); + + query = filter.prepareQueryForContact(query); + + query.addOrderDesc("C." + TopiaEntity.TOPIA_CREATE_DATE).addLoad(Contact.OBSERVER + "." + WaoUser.COMPANY); + + if (log.isDebugEnabled()) { + log.debug("Query : " + query); + } + + results = dao.findAllMappedByQuery(query); + + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, + "Impossible de filtrer la liste des contacts", eee); + } + return results; + } + + @Override + public int getNbContacts(ContactFilter filter) throws SuiviObsmerException { + TopiaContext transaction = null; + int result = 0; + try { + transaction = rootContext.beginTransaction(); + + ContactDAO dao = SuiviObsmerModelDAOHelper.getContactDAO(transaction); + TopiaQuery query = dao.createQuery("C"); + query = filter.prepareQueryForContact(query); + + result = query.executeCount(); + + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, + "Impossible de compter le nombre de contacts filtrés", eee); + } + return result; + } + + @Override + public Contact getNewContact(WaoUser user, SampleRow row, Boat boat) { + Contact result = new ContactImpl(); + result.setObserver(user); + result.setSampleRow(row); + result.setBoat(boat); + result.setState(ContactState.CONTACT_START.toString()); + return result; + } + + @Override + public void saveContact(Contact contact, boolean delete) throws SuiviObsmerException { + TopiaContext transaction = null; + try { + transaction = rootContext.beginTransaction(); + + ContactDAO dao = SuiviObsmerModelDAOHelper.getContactDAO(transaction); + + if (log.isDebugEnabled()) { + log.debug("Create date : " + contact.getTopiaCreateDate()); + } + + SuiviObsmerContext.prepareTopiaId(Contact.class, contact); + if (delete) { + dao.delete(contact); + } else { + dao.update(contact); + } + + transaction.commitTransaction(); + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, + "Impossible de sauvegarder le contact", eee); + } + } + + @Override + public InputStream exportContactCsv(ContactFilter filter) + throws SuiviObsmerException { + TopiaContext transaction = null; + InputStream result = null; + CsvWriter writer = null; + try { + transaction = rootContext.beginTransaction(); + + File file = File.createTempFile("wao-contacts-", ".csv"); + file.deleteOnExit(); + + if (log.isDebugEnabled()) { + log.debug("Export contacts into : " + file.getAbsolutePath()); + } + + 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(); + + + DateFormat dateFormat = ImportHelper.getContactDateFormat(); + + // Get contacts from database + ContactDAO dao = SuiviObsmerModelDAOHelper.getContactDAO(transaction); + TopiaQuery query = dao.createQuery("C"); + + // No page limit in this case + query = filter.prepareQueryForContact(query).resetLimit(); + + if (log.isDebugEnabled()) { + log.debug("Exec query : " + query); + } + + List<Contact> contacts = dao.findAllByQuery(query); + + for (Contact contact : contacts) { + String[] record = new String[ImportHelper.CONTACT_NB_HEADERS]; + + // 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(); + if (contact.getTideBeginDate() != null) { + record[CONTACT.CONT_DEBUT_MAREE.forContactCsv()] = dateFormat.format(contact.getTideBeginDate()); + } + if (contact.getTideEndDate() != null) { + record[CONTACT.CONT_FIN_MAREE.forContactCsv()] = 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(); + if (contact.getDataInputDate() != null) { + record[CONTACT.CONT_ALLEGRO.forContactCsv()] = dateFormat.format(contact.getDataInputDate()); + } + record[CONTACT.CONT_SOCIETE_VALID.forContactCsv()] = + ImportHelper.formatContactValidation(contact.getValidationCompany()); + record[CONTACT.CONT_PROGRAM_VALID.forContactCsv()] = + ImportHelper.formatContactValidation(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(); + + // 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(); + + // FishingZone part + List<FishingZone> zones = row.getFishingZone(); + String fishingDistrict = ""; + for (FishingZone zone : zones) { + fishingDistrict += 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; + + // 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(); + + // 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(); + + writer.writeRecord(record); + writer.flush(); + } + result = new FileInputStream(file); + + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, + "Impossible d'exporter les contacts", eee); + } finally { + if (writer != null) { + writer.close(); + } + } + return result; + } + + @Override + public ImportResults importContactCsv(WaoUser user, InputStream input) throws SuiviObsmerException { + TopiaContext transaction = null; + ImportResults result = new ImportResultsImpl(); + int currRow = 1; + CsvReader reader = null; + try { + transaction = rootContext.beginTransaction(); + + reader = new CsvReader(input, Charset.forName("UTF-8")); + reader.readHeaders(); + + ContactDAO dao = SuiviObsmerModelDAOHelper.getContactDAO(transaction); + WaoUserDAO userDAO = SuiviObsmerModelDAOHelper.getWaoUserDAO(transaction); + CompanyDAO companyDAO = SuiviObsmerModelDAOHelper.getCompanyDAO(transaction); + SampleRowDAO rowDAO = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); + BoatDAO boatDAO = SuiviObsmerModelDAOHelper.getBoatDAO(transaction); + + long tic; + tic = System.currentTimeMillis(); + while(reader.readRecord()) { + currRow++; + + String observerId = ImportHelper.read(reader, CONTACT.OBSERV_ID); + String state = ImportHelper.read(reader, CONTACT.CONT_ETAT); + + ContactState contactState = ContactState.createContactStateEnum(state); + + if (contactState == null) { + throw new SuiviObsmerBusinessException(Type.IMPORT_ERROR, this.getClass(), + "Erreur ligne " + currRow + " : " + + "Etat du contact invalide '" + state + "', valeurs possibles : " + + ContactState.availableStates()); + } + + WaoUser observer = userDAO.findByLogin(observerId); + if (observer != null) { + Company company = user.getCompany(); + // For an admin, get the company from database + if (user.getAdmin()) { + // FIXME-FD20100104 findContains not optimized in TopiaDAOImpl + company = companyDAO.findContainsWaoUser(observer); + // For a user, check if the observer as the same company as the current user + } else if (!observer.getCompany().equals(company)) { + throw new SuiviObsmerBusinessException(Type.IMPORT_ERROR, this.getClass(), + "Erreur ligne " + currRow + " : " + + "L'observateur avec pour login '" + observerId + "' n'appartient pas à votre société !"); + } + + if (company != null) { + String rowCode = ImportHelper.readSampleRowCode(reader); + + SampleRow row = rowDAO.findByProperties(SampleRow.CODE, rowCode, SampleRow.COMPANY, company); + + if (row != null) { + int boatImmatriculation = ImportHelper.readInt(reader, BOAT.NAVS_COD); + + Boat boat = boatDAO.findByImmatriculation(boatImmatriculation); + + if (boat != null) { + + ElligibleBoatDAO elligibleDAO = SuiviObsmerModelDAOHelper.getElligibleBoatDAO(transaction); + ElligibleBoat elligible = elligibleDAO.findByProperties( + ElligibleBoat.BOAT, boat, ElligibleBoat.SAMPLE_ROW, row); + + if (elligible == null) { + // Create new elligible boat not active in a global way + elligible = elligibleDAO.create( + ElligibleBoat.BOAT, boat, ElligibleBoat.SAMPLE_ROW, row); + if (log.isTraceEnabled()) { + log.trace("Create elligibleBoat for : " + boat.getImmatriculation() + " - " + row.getCode()); + } + } + elligible.setCompanyActive(Boolean.TRUE); + + Contact contact = null; + + String createDateString = ImportHelper.read(reader, CONTACT.CONT_CREATION); + String contactCode = ImportHelper.read(reader, CONTACT.CONT_CODE); + Date createDate = ImportHelper.parseContactCreateDate(contactCode, createDateString); + + if (log.isDebugEnabled()) { + log.debug("Ligne " + currRow + " : Create date : " + createDate); + } + + if (/*!StringUtils.isEmpty(contactCode) && */StringUtils.isNotEmpty(createDateString)) { + // Get entity from database + TopiaQuery query = dao.createQuery(). + add(TopiaEntity.TOPIA_CREATE_DATE, createDate). + add(Contact.OBSERVER + "." + WaoUser.COMPANY, company). + add(Contact.BOAT, boat). + add(Contact.SAMPLE_ROW, row); + contact = dao.findByQuery(query); + } + + if (contact != null && contact.getValidationCompany() != null) { + result.addError(currRow, "Le contact est déjà validé dans l'application et ne peut pas être importé"); + result.incNbRefused(); + continue; + } + + // new contact to import + boolean newContact = false; + if (contact == null) { + contact = dao.create( + TopiaEntity.TOPIA_CREATE_DATE, createDate, + Contact.SAMPLE_ROW, row, + Contact.BOAT, boat); + newContact = true; + } + + Date tideBegin = ImportHelper.readDate(reader, CONTACT.CONT_DEBUT_MAREE); + Date tideEnd = ImportHelper.readDate(reader, CONTACT.CONT_FIN_MAREE); + Date dataInput = ImportHelper.readDate(reader, CONTACT.CONT_ALLEGRO); + int nbObservants = ImportHelper.readInt(reader, CONTACT.CONT_NB_OBSERV); + if (nbObservants == -1) { + nbObservants = 0; + } + boolean mammalsCapture = + ImportHelper.parseContactMammals(reader, CONTACT.CONT_MAM_CAPT); + boolean mammalsObsv = + ImportHelper.parseContactMammals(reader, CONTACT.CONT_MAM_OBS); + + contact.setObserver(observer); + contact.setState(state); + contact.setTideBeginDate(tideBegin); + contact.setTideEndDate(tideEnd); + contact.setNbObservants(nbObservants); + contact.setMammalsCapture(mammalsCapture); + contact.setMammalsObservation(mammalsObsv); + contact.setDataInputDate(dataInput); + + // Import validations only for superadmin and a new contact : useful for archives + if (newContact && user.getAdmin() && user.getLogin().equals("admin")) { + if (log.isDebugEnabled()) { + log.debug("SuperAdmin import :: validations"); + } + Boolean companyValidation = ImportHelper.parseContactValidation(reader, CONTACT.CONT_SOCIETE_VALID); + Boolean programValidation = ImportHelper.parseContactValidation(reader, CONTACT.CONT_PROGRAM_VALID); + contact.setValidationCompany(companyValidation); + contact.setValidationProgram(programValidation); + + // Add realTideTime for this contact if validations are ok and state is BOARDING_DONE + if (BooleanUtils.isTrue(companyValidation) && BooleanUtils.isNotFalse(programValidation) && + contact.getState().equals(ContactState.BOARDING_DONE.toString())) { + boolean ok = contact.getSampleRow().addRealTideTime(contact); + if (!ok) { + DateFormat dateFormat1 = new SimpleDateFormat("MM/yyyy"); + result.addError(currRow, "Impossible de mettre à jour le nombre de marée réels, vérifiez le mois " + + "de " + dateFormat1.format(contact.getTideBeginDate()) + " pour la ligne du plan " + row.getCode()); + result.incNbRefused(); + continue; + } + } + } + + result.incNbImported(); + + } else { + result.addError(currRow, "Navire inexistant avec l'immatriculation : " + boatImmatriculation); + result.incNbRefused(); + } + } else { + result.addError(currRow, "Ligne d'échantillon inexistante ou incompatible avec la société " + + "pour le code : " + rowCode); + result.incNbRefused(); + } + } else { + result.addError(currRow, "Cet utilisateur n'est lié à aucune société : " + user.getFullName()); + result.incNbRefused(); + } + } else { + result.addError(currRow, "Utilisateur inexistant avec l'identifiant : " + observerId); + result.incNbRefused(); + } + + if (result.getNbRowsImported() % 1000 == 0) { + transaction.commitTransaction(); + tic = ImportHelper.logTimeAndMemory(log, tic, "contacts ligne " + currRow); + } + } + + transaction.commitTransaction(); + + transaction.closeContext(); + } catch (ParseException eee) { + SuiviObsmerContext.serviceException(transaction, + "Erreur ligne " + currRow + " : " + + "Le format des dates est incorrect, il doit être de la forme : JJ/MM/AAAA", eee); + } catch (Exception eee) { + if (log.isDebugEnabled()) { + try { + log.debug("Ligne : " + currRow + " :: " + Arrays.toString(reader.getValues())); + } catch (IOException ex) { + log.error("Reader error", ex); + } + } + SuiviObsmerContext.serviceException(transaction, + "Impossible d'importer les contacts", eee); + } + return result; + } + +} Modified: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceNewsImpl.java =================================================================== --- trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/impl/ServiceNewsImpl.java 2010-02-04 21:33:50 UTC (rev 325) +++ trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceNewsImpl.java 2010-02-09 01:30:52 UTC (rev 339) @@ -19,7 +19,7 @@ * ##%* */ -package fr.ifremer.suiviobsmer.impl; +package fr.ifremer.suiviobsmer.services; import fr.ifremer.suiviobsmer.SuiviObsmerContext; import fr.ifremer.suiviobsmer.SuiviObsmerException; Deleted: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceReferentialImpl.java =================================================================== --- trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/impl/ServiceReferentialImpl.java 2010-02-04 21:33:50 UTC (rev 325) +++ trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceReferentialImpl.java 2010-02-09 01:30:52 UTC (rev 339) @@ -1,216 +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.impl; - -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; -import fr.ifremer.suiviobsmer.bean.SamplingFilter; -import fr.ifremer.suiviobsmer.entity.Company; -import fr.ifremer.suiviobsmer.entity.FishingZone; -import fr.ifremer.suiviobsmer.entity.FishingZoneDAO; -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 java.io.InputStream; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import org.apache.commons.lang.StringUtils; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.framework.TopiaQuery; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * ServiceReferentialImpl - * - * Created: 30 nov. 2009 - * - * @author fdesbois - * @version $Revision$ - * - * Mise a jour: $Date$ - * par : $Author$ - */ -public class ServiceReferentialImpl implements ServiceReferential { - - private static final Logger log = LoggerFactory.getLogger(ServiceReferentialImpl.class); - - protected TopiaContext rootContext; - - public ServiceReferentialImpl() throws SuiviObsmerException { - rootContext = SuiviObsmerContext.getTopiaRootContext(); - } - - @Override - public List<String> getFacades(SamplingFilter filter) throws SuiviObsmerException { - TopiaContext transaction = null; - List<String> results = new ArrayList<String>(); - try { - transaction = rootContext.beginTransaction(); - - FishingZoneDAO dao = SuiviObsmerModelDAOHelper.getFishingZoneDAO(transaction); - TopiaQuery<FishingZone> query = dao.createQuery("F"); - - query = prepareQueryForFishingZoneFilter(query, filter); - - results = (List<String>)query.setSelect("DISTINCT F." + FishingZone.FACADE_NAME).execute(); - - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, "Impossible de charger la liste des facades", eee); - } - return results; - } - - @Override - public List<String> getSectors(SamplingFilter filter) throws SuiviObsmerException { - TopiaContext transaction = null; - List<String> results = new ArrayList<String>(); - try { - transaction = rootContext.beginTransaction(); - - FishingZoneDAO dao = SuiviObsmerModelDAOHelper.getFishingZoneDAO(transaction); - TopiaQuery<FishingZone> query = dao.createQuery("F"); - - query = prepareQueryForFishingZoneFilter(query, filter); - - if (StringUtils.isNotEmpty(filter.getFacadeName())) { - query.add("F." + FishingZone.FACADE_NAME, filter.getFacadeName()); - } - - results = (List<String>)query.setSelect("DISTINCT F." + FishingZone.SECTOR_NAME).execute(); - - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, "Impossible de charger la liste des secteurs de pêche", eee); - } - return results; - } - - protected TopiaQuery<FishingZone> prepareQueryForFishingZoneFilter(TopiaQuery<FishingZone> query, SamplingFilter filter) { - if (filter.getCompany() != null || StringUtils.isNotEmpty(filter.getProgramName())) { - query.addFrom(SampleRow.class.getName() + " S"). - add("S IN elements(F." + FishingZone.SAMPLE_ROW + ")"); - } - - if (filter.getCompany() != null) { - query.add("S." + SampleRow.COMPANY, filter.getCompany()); - } - - if (filter.getProgramName() != null) { - query.add("S." + SampleRow.PROGRAM_NAME, filter.getProgramName()); - } - - return query; - } - - @Override - public List<Profession> getProfessions() throws SuiviObsmerException { - TopiaContext transaction = null; - List<Profession> results = new ArrayList<Profession>(); - try { - transaction = rootContext.beginTransaction(); - - ProfessionDAO dao = SuiviObsmerModelDAOHelper.getProfessionDAO(transaction); - - results = dao.findAll(); - - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, - "Impossible de charger la liste des métiers", eee); - } - return results; - } - - @Override - public List<FishingZone> getFishingZones() throws SuiviObsmerException { - TopiaContext transaction = null; - List<FishingZone> results = new ArrayList<FishingZone>(); - try { - transaction = rootContext.beginTransaction(); - - FishingZoneDAO dao = SuiviObsmerModelDAOHelper.getFishingZoneDAO(transaction); - - results = dao.findAll(); - - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, - "Impossible de charger la liste des zones de pêche", eee); - } - return results; - } - - @Override - public int importFishingZoneCsv(InputStream input) throws SuiviObsmerException { - TopiaContext transaction = null; - int result = 0; - try { - transaction = rootContext.beginTransaction(); - - CsvReader reader = new CsvReader(input, Charset.forName("UTF-8")); - reader.readHeaders(); - - FishingZoneDAO dao = SuiviObsmerModelDAOHelper.getFishingZoneDAO(transaction); - - while(reader.readRecord()) { - if (log.isTraceEnabled()) { - 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(); - - FishingZone zone = dao.findByProperties( - FishingZone.FACADE_NAME, facadeName, - FishingZone.SECTOR_NAME, sectorName, - FishingZone.DISTRICT_CODE, districtCode); - - if (zone == null) { - zone = dao.create( - FishingZone.FACADE_NAME, facadeName, - FishingZone.SECTOR_NAME, sectorName, - FishingZone.DISTRICT_CODE, districtCode); - result++; - } - } - - transaction.commitTransaction(); - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, - "Problème d'import du fichier CSV. Vérifiez l'en-tête du fichier : [ PECHE_DIVISION," + - "PECHE_ZONE,PECHE_FACADE ]. Voir documentation pour plus de détails.", - eee); - } - return result; - } - -} Copied: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceReferentialImpl.java (from rev 337, trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/impl/ServiceReferentialImpl.java) =================================================================== --- trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceReferentialImpl.java (rev 0) +++ trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceReferentialImpl.java 2010-02-09 01:30:52 UTC (rev 339) @@ -0,0 +1,212 @@ +/* + * *##% + * 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.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; +import fr.ifremer.suiviobsmer.bean.SamplingFilter; +import fr.ifremer.suiviobsmer.entity.FishingZone; +import fr.ifremer.suiviobsmer.entity.FishingZoneDAO; +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 java.io.InputStream; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.apache.commons.lang.StringUtils; +import org.nuiton.topia.TopiaContext; +import org.nuiton.topia.TopiaException; +import org.nuiton.topia.framework.TopiaQuery; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * ServiceReferentialImpl + * + * Created: 30 nov. 2009 + * + * @author fdesbois + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ +public class ServiceReferentialImpl implements ServiceReferential { + + private static final Logger log = LoggerFactory.getLogger(ServiceReferentialImpl.class); + + protected TopiaContext rootContext; + + public ServiceReferentialImpl() throws SuiviObsmerException { + rootContext = SuiviObsmerContext.getTopiaRootContext(); + } + + @Override + public List<String> getFacades(SamplingFilter filter) throws SuiviObsmerException { + TopiaContext transaction = null; + List<String> results = new ArrayList<String>(); + try { + transaction = rootContext.beginTransaction(); + + FishingZoneDAO dao = SuiviObsmerModelDAOHelper.getFishingZoneDAO(transaction); + TopiaQuery query = dao.createQuery("F"); + + query = prepareQueryForFishingZoneFilter(query, filter); + + results = (List<String>)query.setSelect("DISTINCT F." + FishingZone.FACADE_NAME).execute(); + + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, "Impossible de charger la liste des facades", eee); + } + return results; + } + + @Override + public List<String> getSectors(SamplingFilter filter) throws SuiviObsmerException { + TopiaContext transaction = null; + List<String> results = new ArrayList<String>(); + try { + transaction = rootContext.beginTransaction(); + + FishingZoneDAO dao = SuiviObsmerModelDAOHelper.getFishingZoneDAO(transaction); + TopiaQuery query = dao.createQuery("F"); + + query = prepareQueryForFishingZoneFilter(query, filter); + + if (StringUtils.isNotEmpty(filter.getFacadeName())) { + query.add("F." + FishingZone.FACADE_NAME, filter.getFacadeName()); + } + + results = (List<String>)query.setSelect("DISTINCT F." + FishingZone.SECTOR_NAME).execute(); + + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, "Impossible de charger la liste des secteurs de pêche", eee); + } + return results; + } + + protected TopiaQuery prepareQueryForFishingZoneFilter(TopiaQuery query, SamplingFilter filter) throws TopiaException { + if (filter.getCompany() != null || StringUtils.isNotEmpty(filter.getProgramName())) { + query.addFrom(SampleRow.class.getName() + " S"). + add("S IN elements(F." + FishingZone.SAMPLE_ROW + ")"); + } + + if (filter.getCompany() != null) { + query.add("S." + SampleRow.COMPANY, filter.getCompany()); + } + + if (filter.getProgramName() != null) { + query.add("S." + SampleRow.PROGRAM_NAME, filter.getProgramName()); + } + + return query; + } + + @Override + public List<Profession> getProfessions() throws SuiviObsmerException { + TopiaContext transaction = null; + List<Profession> results = new ArrayList<Profession>(); + try { + transaction = rootContext.beginTransaction(); + + ProfessionDAO dao = SuiviObsmerModelDAOHelper.getProfessionDAO(transaction); + + results = dao.findAll(); + + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, + "Impossible de charger la liste des métiers", eee); + } + return results; + } + + @Override + public List<FishingZone> getFishingZones() throws SuiviObsmerException { + TopiaContext transaction = null; + List<FishingZone> results = new ArrayList<FishingZone>(); + try { + transaction = rootContext.beginTransaction(); + + FishingZoneDAO dao = SuiviObsmerModelDAOHelper.getFishingZoneDAO(transaction); + + results = dao.findAll(); + + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, + "Impossible de charger la liste des zones de pêche", eee); + } + return results; + } + + @Override + public int importFishingZoneCsv(InputStream input) throws SuiviObsmerException { + TopiaContext transaction = null; + int result = 0; + try { + transaction = rootContext.beginTransaction(); + + CsvReader reader = new CsvReader(input, Charset.forName("UTF-8")); + reader.readHeaders(); + + FishingZoneDAO dao = SuiviObsmerModelDAOHelper.getFishingZoneDAO(transaction); + + while(reader.readRecord()) { + if (log.isTraceEnabled()) { + 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(); + + FishingZone zone = dao.findByDistrictCode(districtCode); + + if (zone == null) { + zone = dao.create(FishingZone.DISTRICT_CODE, districtCode); + } + zone.setFacadeName(facadeName); + zone.setSectorName(sectorName); + result++; + } + + transaction.commitTransaction(); + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, + "Problème d'import du fichier CSV. Vérifiez l'en-tête du fichier : [ PECHE_DIVISION," + + "PECHE_ZONE,PECHE_FACADE ]. Voir documentation pour plus de détails.", + eee); + } + return result; + } + +} Deleted: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceSamplingImpl.java =================================================================== --- trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/impl/ServiceSamplingImpl.java 2010-02-04 21:33:50 UTC (rev 325) +++ trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceSamplingImpl.java 2010-02-09 01:30:52 UTC (rev 339) @@ -1,773 +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.impl; - -import com.csvreader.CsvReader; -import fr.ifremer.suiviobsmer.ImportHelper; -import fr.ifremer.suiviobsmer.ImportHelper.FISHING_ZONE; -import fr.ifremer.suiviobsmer.ImportHelper.SAMPLING; -import fr.ifremer.suiviobsmer.SuiviObsmerBusinessException; -import fr.ifremer.suiviobsmer.SuiviObsmerBusinessException.Type; -import fr.ifremer.suiviobsmer.SuiviObsmerException; -import fr.ifremer.suiviobsmer.SuiviObsmerModelDAOHelper; -import fr.ifremer.suiviobsmer.SuiviObsmerContext; -import fr.ifremer.suiviobsmer.bean.FacadeRow; -import fr.ifremer.suiviobsmer.bean.FacadeRowImpl; -import fr.ifremer.suiviobsmer.bean.ImportResults; -import fr.ifremer.suiviobsmer.bean.ImportResultsImpl; -import fr.ifremer.suiviobsmer.bean.SamplingFilter; -import fr.ifremer.suiviobsmer.entity.*; -import fr.ifremer.suiviobsmer.entity.SampleRow; -import fr.ifremer.suiviobsmer.services.ServiceSampling; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.Charset; -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.apache.commons.lang.StringUtils; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.framework.TopiaQuery; -import org.nuiton.topia.framework.TopiaQuery.Op; -import org.nuiton.topia.persistence.util.EntityLoador; -import org.nuiton.util.DateUtils; -import org.nuiton.util.PeriodDates; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * ServiceSamplingImpl - * - * Created: 30 nov. 2009 - * - * @author fdesbois - * @version $Revision$ - * - * Mise a jour: $Date$ - * par : $Author$ - */ -public class ServiceSamplingImpl implements ServiceSampling { - - private static final Logger log = LoggerFactory.getLogger(ServiceSamplingImpl.class); - - protected TopiaContext rootContext; - - public ServiceSamplingImpl() throws SuiviObsmerException { - rootContext = SuiviObsmerContext.getTopiaRootContext(); - } - - @Override - public void createUpdateSampleRow(SampleRow row, List<Boat> boats, SampleRowLog rowLog) throws SuiviObsmerException { - TopiaContext transaction = null; - try { - transaction = rootContext.beginTransaction(); - - SampleRowLogDAO logDAO = SuiviObsmerModelDAOHelper.getSampleRowLogDAO(transaction); - SuiviObsmerContext.prepareTopiaId(SampleRowLog.class, rowLog); - logDAO.update(rowLog); - - boolean newRow = SuiviObsmerContext.prepareTopiaId(SampleRow.class, row); - - if (log.isDebugEnabled()) { - log.debug("new sampleRow : " + newRow); - log.debug("samplRow topiaId : " + row.getTopiaId()); - } - - String pattern = DateUtils.MONTH_PATTERN; - DateFormat dateFormat = new SimpleDateFormat(pattern); - - SampleRow oldRow = null; - Profession oldProfession = null; - Company oldCompany = null; - Map<String, SampleMonth> oldMonths = new HashMap<String, SampleMonth>(); - List<FishingZone> oldZones = new ArrayList<FishingZone>(); - // UPDATE - if (!newRow) { - // Prepare data for logging or deleting oldMonths - TopiaContext transaction2 = rootContext.beginTransaction(); - SampleRowDAO oldDAO = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction2); - oldRow = oldDAO.findByTopiaId(row.getTopiaId()); - oldCompany = oldRow.getCompany(); - oldProfession = oldRow.getProfession(); - for (SampleMonth month : oldRow.getSampleMonth()) { - oldMonths.put(month.getTopiaId(), month); - } - oldZones = oldRow.getFishingZone(); - transaction2.closeContext(); - - // NbObservants - if (oldRow.getNbObservants() != row.getNbObservants()) { - rowLog.addChange("Le nombre d'observateurs est passé de " + oldRow.getNbObservants() + " à " + row.getNbObservants()); - } - // AverageTideTime - if (oldRow.getAverageTideTime() != row.getAverageTideTime()) { - rowLog.addChange("La durée moyenne d'une marée est passé de " + oldRow.getAverageTideTime() + " jours à " + row.getAverageTideTime()); - } - } else { - rowLog.addChange("Le nombre d'observateurs est " + row.getNbObservants()); - rowLog.addChange("La durée moyenne d'une marée est " + row.getAverageTideTime()); - } - // ChangeLog Company - rowLog.addChangeCompany(oldCompany, row.getCompany()); - // ChangeLog Program - String oldProgram = oldRow != null ? oldRow.getProgramName() : null; - rowLog.addChangeProgram(oldProgram, row.getProgramName()); - // ChangeLog Period - PeriodDates oldPeriod = null; - if (oldRow != null) { - oldPeriod = new PeriodDates(oldRow.getPeriodBegin(), oldRow.getPeriodEnd()); - } - PeriodDates newPeriod = new PeriodDates(row.getPeriodBegin(), row.getPeriodEnd()); - rowLog.addChangePeriod(oldPeriod, newPeriod, pattern); - - // Save Profession - ProfessionDAO professionDAO = SuiviObsmerModelDAOHelper.getProfessionDAO(transaction); - SuiviObsmerContext.prepareTopiaId(Profession.class, row.getProfession()); - rowLog.addChangeProfession(oldProfession, row.getProfession()); - professionDAO.update(row.getProfession()); - - // Save sampleMonth - SampleMonthDAO monthDAO = SuiviObsmerModelDAOHelper.getSampleMonthDAO(transaction); - - // Delete oldMonths - List<SampleMonth> newMonths = row.getSampleMonth(); - for (SampleMonth oldMonth : oldMonths.values()) { - if (!newMonths.contains(oldMonth)) { - String date = dateFormat.format(oldMonth.getPeriodDate()); - // Delete old month : add to log - monthDAO.delete(oldMonth); - rowLog.addChange("Le mois " + date + " a été supprimé, " + - "l'ancienne valeur d'effort était " + oldMonth.getExpectedTidesValue()); - } - } - // Create or update months - for (SampleMonth month : newMonths) { - boolean monthCreated = SuiviObsmerContext.prepareTopiaId(SampleMonth.class, month); - String date = dateFormat.format(month.getPeriodDate()); - if (monthCreated) { - // log create month - rowLog.addChange("Le mois " + date + " a été créé avec un nombre de marées de " + month.getExpectedTidesValue()); - } else { - SampleMonth oldMonth = oldMonths.get(month.getTopiaId()); - if (oldMonth.getExpectedTidesValue() != month.getExpectedTidesValue()) { - // log change month value - rowLog.addChange("Le nombre de marées du mois " + date + " est passé de " + - oldMonth.getExpectedTidesValue() + " à " + month.getExpectedTidesValue()); - } - } - monthDAO.update(month); - } - - // Remove no longer elligibleBoats - row.removeNoLongerElligibleBoats(boats); - // Save new elligibleBoats - ElligibleBoatDAO dao = SuiviObsmerModelDAOHelper.getElligibleBoatDAO(transaction); - for (Boat boat : boats) { - if (!row.hasElligibleBoat(boat)) { - ElligibleBoat elligibleBoat = dao.create(); - elligibleBoat.setSampleRow(row); - elligibleBoat.setGlobalActive(true); - elligibleBoat.setBoat(boat); - row.addElligibleBoat(elligibleBoat); - } - } - - // ChangeLog boats - String oldBoats = oldRow != null ? oldRow.getMainElligibleBoatsAsString() : ""; - rowLog.addChangeBoats(oldBoats, row.getMainElligibleBoatsAsString()); - - - // Remove no longer linked FishingZone - List<FishingZone> newZones = row.getFishingZone(); - for (FishingZone oldZone : oldZones) { - if (!newZones.contains(oldZone)) { - updateFishingZones(transaction, oldZone.getTopiaId(), row, true); - rowLog.addChange("La zone de pêche " + oldZone.getCode() + " a été dissociée de la ligne"); - } - } - // Add new linked FishingZone - // ConcurrentModificationException ???? - for (FishingZone zone : new ArrayList<FishingZone>(newZones)) { - if (!oldZones.contains(zone)) { - updateFishingZones(transaction, zone.getTopiaId(), row, false); - rowLog.addChange("La zone de pêche " + zone.getCode() + " a été associée à la ligne"); - } - } - - // Save sampleRow : create or update - SampleRowDAO rowDAO = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); - if (log.isDebugEnabled()) { - log.debug("update row : " + row); - } - row.addSampleRowLog(rowLog); - rowDAO.update(row); - - if (log.isDebugEnabled()) { - log.debug("Change log : " + rowLog.getLogText()); - log.debug("commit transaction !"); - } - transaction.commitTransaction(); - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, - "Impossible de sauvegarder la ligne d'échantillon", eee); - } - } - - protected void updateFishingZones(TopiaContext transaction, String zoneId, SampleRow row, boolean delete) throws TopiaException { - // FIXME find a way to avoid saving links from FishingZone instead of SampleRow : - // variable inverse="true" in hibernate mapping of FishingZone, how to set this variable to SampleRow instead - FishingZoneDAO fishingZoneDAO = SuiviObsmerModelDAOHelper.getFishingZoneDAO(transaction); - FishingZone zoneFromDB = fishingZoneDAO.findByTopiaId(zoneId); - if (delete) { - zoneFromDB.removeSampleRow(row); - } else { - zoneFromDB.addSampleRow(row); - } - fishingZoneDAO.update(zoneFromDB); - } - -// @Override -// public List<SampleRowLog> getSampleRowLogs(SampleRow sampleRow) throws SuiviObsmerException { -// TopiaContext transaction = null; -// List<SampleRowLog> results = new ArrayList<SampleRowLog>(); -// try { -// transaction = rootContext.beginTransaction(); -// -// SampleRowLogDAO dao = SuiviObsmerModelDAOHelper.getSampleRowLogDAO(transaction); -// results = dao.createQuery().add(SampleRowLog.SAMPLE_ROW, sampleRow).addOrderDesc(TopiaEntity.TOPIA_CREATE_DATE).executeToEntityList(); -// -// transaction.closeContext(); -// } catch (Exception eee) { -// SuiviObsmerContext.serviceException(transaction, -// "Impossible de récupérer l'historique de la ligne d'échantillonnage", eee); -// } -// return results; -// } - - @Override - public FacadeRow getSampleRowsOrderedByFishingZone(PeriodDates period, Company company) throws SuiviObsmerException { - TopiaContext transaction = null; - FacadeRow result = new FacadeRowImpl(); - try { - if (period.getFromDate() == null || period.getThruDate() == null) { - throw new IllegalArgumentException("PeriodBegin date and/or PeriodEnd date can't be null !"); - } - transaction = rootContext.beginTransaction(); - - SampleRowDAO dao = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); - - TopiaQuery<SampleRow> query = dao.createQuery("S").addDistinct(). - addFrom(FishingZone.class.getName() + " F").add("S IN elements(F." + FishingZone.SAMPLE_ROW + ")"); - - if (company != null) { - query.add("S." + SampleRow.COMPANY, company); - } - - // Prepare period dates - period.initDayOfMonthExtremities(); - query.add("S." + SampleRow.PERIOD_BEGIN, Op.LT, period.getThruDate()). - add("S." + SampleRow.PERIOD_END, Op.GT, period.getFromDate()); - - // Order By facade, sector, districtCode, sampleRowCode - String zoneOrder = "F." + FishingZone.FACADE_NAME + " , F." + FishingZone.SECTOR_NAME + ", F." + FishingZone.DISTRICT_CODE; - query.addOrder(zoneOrder).addOrder("S." + SampleRow.CODE).addSelect(zoneOrder); - // Load data - //query.addLoad(SampleRow.PROFESSION, SampleRow.COMPANY); - - if (log.isDebugEnabled()) { - log.debug("Query : " + query); - } - - List<SampleRow> results = query.executeToEntityList(); - - for (SampleRow row : results) { - // use FacadeRow to complete ordering using maps - result.addRow(row); - } - - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, - "Impossible de récupérer la liste des lignes du plan d'échantillonnage", eee); - } - return result; - } - - @Override - public List<String> getPrograms(Company company) throws SuiviObsmerException { - TopiaContext transaction = null; - List<String> results = new ArrayList<String>(); - try { - transaction = rootContext.beginTransaction(); - - SampleRowDAO dao = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); - TopiaQuery<SampleRow> query = dao.createQuery(); - - if (company != null) { - query.add(SampleRow.COMPANY, company); - } - - results = (List<String>)query.setSelect("DISTINCT " + SampleRow.PROGRAM_NAME).execute(); - - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, - "Impossible de charger la liste des programmes", eee); - } - return results; - } - - @Override - public List<SampleRow> getSampleRowsByFilter(SamplingFilter filter) throws SuiviObsmerException { - TopiaContext transaction = null; - List<SampleRow> results = new ArrayList<SampleRow>(); - try { - transaction = rootContext.beginTransaction(); - - SampleRowDAO dao = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); - - TopiaQuery<SampleRow> query = dao.createQuery("S").addDistinct().addOrder("S." + SampleRow.CODE); - - query = filter.prepareQueryForSampling(query, "S"); - - if (log.isDebugEnabled()) { - log.debug("Query : " + query); - } - -// if (finished) { -// // Only rows which are not finished will be kept -// Date current = SuiviObsmerContext.getCurrentDate(); -// query.add(SampleRow.PERIOD_END, Op.GE, current); -// } - -// if (filter.getCompany() != null) { -// query.add("S." + SampleRow.COMPANY, filter.getCompany()); -// } - - results = query.executeToEntityList(); - - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, - "Impossible de récupérer la liste des lignes du plan d'échantillonnage", eee); - } - return results; - } - - @Override - public SampleRow getSampleRow(String sampleRowId) throws SuiviObsmerException { - TopiaContext transaction = null; - SampleRow result = null; - try { - transaction = rootContext.beginTransaction(); - - SampleRowDAO dao = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); - - result = dao.findByTopiaId(sampleRowId); - - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, - "Impossible de charger la ligne d'échantillon ayant pour identifiant : " + sampleRowId, - eee); - } - return result; - } - - @Override - public void deleteSampleRow(SampleRow sampleRow) throws SuiviObsmerException { - TopiaContext transaction = null; - try { - transaction = rootContext.beginTransaction(); - - SampleRowDAO dao = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); - - SampleRow row = dao.findByTopiaId(sampleRow.getTopiaId()); - - dao.delete(row); - - transaction.commitTransaction(); - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, - "Impossible de supprimer la ligne d'échantillon : " + sampleRow.getCode(), - eee); - } - } - - @Override - public String getNewSampleRowCode(Date beginDate) throws SuiviObsmerException { - TopiaContext transaction = null; - String result = null; - if (beginDate == null) { - return result; - } - try { - transaction = SuiviObsmerContext.getTopiaRootContext().beginTransaction(); - - Calendar begin = new GregorianCalendar(); - begin.setTime(beginDate); - int year = begin.get(Calendar.YEAR); - - SampleRowDAO dao = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); - TopiaQuery<SampleRow> query = dao.createQuery().add(SampleRow.CODE, Op.LIKE, year + "_%"); - - String maxCode = query.executeToString("MAX(" + SampleRow.CODE + ")"); - - if (log.isDebugEnabled()) { - log.debug("Max code found : " + maxCode); - } - - int num = 1; - if (!StringUtils.isEmpty(maxCode)) { - String[] part = maxCode.split("_"); - num = Integer.parseInt(part[1]) + 1; - } - String str = StringUtils.leftPad("" + num, 4, "0"); - result = year + "_" + str; - - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, - "Impossible de récupérer un nouveau code pour une ligne d'échantillonnage", - eee); - } - return result; - } - - @Override - public SampleRow getNewSampleRow() { - SampleRow row = new SampleRowImpl(); - row.setProfession(new ProfessionImpl()); - row.setFishingZone(new ArrayList<FishingZone>()); - //row.setProgram(new ProgramImpl()); - row.setElligibleBoat(new ArrayList<ElligibleBoat>()); - row.setSampleMonth(new ArrayList<SampleMonth>()); - return row; - } - - @Override - public SampleMonth getNewSampleMonth(Date period, SampleRow row) { - SampleMonth month = new SampleMonthImpl(); - month.setSampleRow(row); - month.setPeriodDate(period); - return month; - } - - /** - * Create a new profession from an existing one. Copy all attributes values from - * the profession in argument to a new profession not created yet in database. - * - * @param profession the profession source - * @return a new Profession - */ - @Override - public Profession getNewProfession(Profession profession) { - Profession newProfession = new ProfessionImpl(); - EntityLoador<Profession> loador = EntityLoador.newEntityLoador(Profession.class, - Profession.CODE_DCF5, Profession.LIBELLE, Profession.MESH_SIZE, Profession.OTHER, Profession.SIZE, Profession.SPECIES); - loador.load(profession, newProfession, false); - return newProfession; - } - - @Override - public ImportResults importSamplingPlanCsv(InputStream input) throws SuiviObsmerException { - TopiaContext transaction = null; - ImportResults result = new ImportResultsImpl(); - //int[] result = new int[3]; - int currRow = 0; - SampleRow row = null; - try { - transaction = rootContext.beginTransaction(); - - CsvReader reader = new CsvReader(input, Charset.forName("UTF-8")); - reader.readHeaders(); - - SampleRowDAO dao = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); - - //int nbImported = 0; - //int nbRefused = 0; - - while(reader.readRecord()) { - currRow++; - if (log.isTraceEnabled()) { - log.trace(" " + Arrays.asList(reader.getValues())); - } - - String code = ImportHelper.readSampleRowCode(reader); //reader.get(SAMPLING.PLAN_CODE.name()).trim(); - - if (StringUtils.isEmpty(code)) { - continue; - } - - String districts = reader.get(FISHING_ZONE.PECHE_DIVISION.name()); - - row = dao.findByCode(code); - // Refuse existing SampleRow - if (row != null) { -// if (log.isInfoEnabled()) { -// log.info("Ligne " + currRow + " refusé [CODE = " + code + "] Code déjà existant : " + -// Arrays.asList(reader.getValues())); -// } - result.addError(currRow, "[CODE = " + code + "] refusé : Code déjà existant"); - result.incNbRefused(); //nbRefused++; - -// } else if (StringUtils.isEmpty(programName)) { -// throw new SuiviObsmerBusinessException(Type.IMPORT_ERROR, this.getClass(), -// "Erreur à la ligne " + currRow + " [CODE = " + code + "] : " + -// "Cette ligne n'est lié à aucun programme !"); - // Refuse Fishing zones empty - } else if (StringUtils.isEmpty(districts)) { -// if (log.isInfoEnabled()) { -// log.info("Ligne " + currRow + " refusé [CODE = " + code + "] Zone de pêche non renseigné : " + -// Arrays.asList(reader.getValues())); -// } - result.addError(currRow, "[CODE = " + code + "] refusé : Zone de pêche non renseigné"); - result.incNbRefused(); //nbRefused++; - } else { - row = dao.create(SampleRow.CODE, code); - - String companyName = ImportHelper.read(reader, SAMPLING.SOCIETE_NOM); - - // Create link with company if set in file - if (!StringUtils.isEmpty(companyName)) { - CompanyDAO companyDAO = SuiviObsmerModelDAOHelper.getCompanyDAO(transaction); - Company company = companyDAO.findByName(companyName); - if (company == null) { - throw new SuiviObsmerBusinessException(Type.IMPORT_ERROR, this.getClass(), - "Erreur à la ligne " + currRow + " [CODE = " + code + "] : " + - "La société portant le nom '" + companyName + "' n'existe pas dans l'application"); -// result.addError(currRow, "[CODE = " + code + "] refusé : La société '" + companyName + "' n'existe pas dans l'application"); -// result.incNbRefused(); -// continue; - } - row.setCompany(company); - } - - // Import profession. Creation if not exist - Profession profession = importProfession(transaction, reader); - row.setProfession(profession); - - // Import zones and set them to the row - // throw SuiviObsmerException if FishingZone doesn't exist - importFishingZones(transaction, districts, currRow, row); - - updateRow(transaction, row, reader); - result.incNbImported(); //nbImported++; - } - // Commit row by row - transaction.commitTransaction(); - } - - transaction.closeContext(); - - } catch (NumberFormatException eee) { - SuiviObsmerContext.serviceException(transaction, - "Erreur à la ligne " + currRow + " [CODE = " + row.getCode() + "] : " + - "Le format de la durée moyenne des marées est incorrect, il doit être de la forme : 1.9 ", eee); - } catch (ParseException eee) { - SuiviObsmerContext.serviceException(transaction, - "Erreur à la ligne " + currRow + " [CODE = " + row.getCode() + "] : " + - "Le format des dates est incorrect, il doit être de la forme : MM/AAAA", eee); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, - "Erreur à la ligne " + currRow + " [CODE = " + row.getCode() + "]", - eee); - } - return result; - } - - /** - * Import a profession from CSV File from importSamplingPlanCsv method. - * This profession is imported for a new SampleRow line. - * Key value for the profession : codeDCF5, meshSize, size, other. - * If profession already exists, update libelle and species. - * @param transaction Topia transaction for using ProfessionDAO - * @param reader CsvReader for getting Profession parameters - * @return an existing Profession or a new one - * @throws IOException for reader errors - * @throws TopiaException for dao errors - */ - protected Profession importProfession(TopiaContext transaction, CsvReader reader) - throws IOException, TopiaException { - - String codeDCF5 = reader.get(SAMPLING.METIER_CODE_DCF5.name()).trim(); - String maillage = reader.get(SAMPLING.METIER_MAILLAGE.name()).trim(); - String taille = reader.get(SAMPLING.METIER_TAILLE.name()).trim(); - String autre = reader.get(SAMPLING.METIER_AUTRE.name()).trim(); - String libelle = reader.get(SAMPLING.METIER_LIBELLE.name()).trim(); - String especes = reader.get(SAMPLING.METIER_ESPECES.name()).trim(); - - ProfessionDAO dao = SuiviObsmerModelDAOHelper.getProfessionDAO(transaction); - Map<String, Object> existParams = new HashMap<String, Object>(); - existParams.put(Profession.CODE_DCF5, codeDCF5); - existParams.put(Profession.MESH_SIZE, maillage); - existParams.put(Profession.SIZE, taille); - existParams.put(Profession.OTHER, autre); - - Profession profession = dao.findByProperties(existParams); - - if (profession == null) { - profession = dao.create(existParams); - } - - profession.setLibelle(libelle); - profession.setSpecies(especes); - - return profession; - } - - /** - * Import a fishingZone from CSV File from importSamplingPlanCsv method. - * These fishingZones are imported for a new SampleRow line. - * Key value for the fishingZone : districtCode. - * The districts argument contains multiple districtCode separating with " - ". - * The fishingZone must be exist in database. - * @param transaction Topia transaction for using FishingZoneDAO - * @param districts String which contains several fishingZone districtCodes - * @param currRow Row number in the line for the SampleRow - * @param row SampleRow linked with districts (from Csv file) - * @throws TopiaException for dao errors - * @throws SuiviObsmerException if a FishingZone doesn't exist. - */ - protected void importFishingZones(TopiaContext transaction, String districts, int currRow, SampleRow row) - throws TopiaException, SuiviObsmerException { - - FishingZoneDAO dao = SuiviObsmerModelDAOHelper.getFishingZoneDAO(transaction); - - List<String> districtList = new ArrayList<String>(Arrays.asList(districts.split(" / "))); - - if (log.isDebugEnabled()) { - log.debug("FishingZone districts : " + districts); - log.debug("FishingZone nb zones : " + districtList.size()); - } - for (String districtCode : districtList) { - FishingZone zone = dao.findByDistrictCode(districtCode.trim()); - if (zone == null) { - throw new SuiviObsmerBusinessException(Type.IMPORT_ERROR, this.getClass(), - "Erreur à la ligne " + currRow + " [CODE = " + row.getCode() + "] : " + - "Cette ligne est lié à une zone inexistante : " + districtCode); - } - row.addFishingZone(zone); - } - } - - /** - * Update a SampleRow from CSV File from importSamplingPlanCsv method. - * Program must be set to get beginDate and endDate for getting correct months. - * SampleMonth will be created corresponding to program period. - * Careful : fixed columns set to 16 and months columns start to 13. - * Updatable fields : fishingZoneInfos, nbObservants, averageTideTime, sampleMonths. - * @param transaction Topia transaction for using FishingZoneDAO - * @param sampleRow - * @param reader CsvReader to get values for updatable fields - * @throws IOException for CsvReader errors - * @throws TopiaException for SampleMonthDAO errors - * @throws ParseException for format errors - * @see #getMonthAndYear(java.lang.String) - */ - protected void updateRow(TopiaContext transaction, SampleRow sampleRow, CsvReader reader) - throws IOException, TopiaException, ParseException { - - String fishingZoneInfos = ImportHelper.read(reader, SAMPLING.PECHE_AUTRE); - int nbObservants = ImportHelper.readInt(reader, SAMPLING.PLAN_NB_OBSERV); - String averageStr = ImportHelper.read(reader, SAMPLING.PLAN_DUREE_MOY); - averageStr = averageStr.replaceAll(",", "."); - double averageTideTime = Double.parseDouble(averageStr); - String programName = ImportHelper.read(reader, SAMPLING.PROGRAMME_CODE); - String comment = ImportHelper.read(reader, SAMPLING.PLAN_COMMENT); - PeriodDates period = ImportHelper.readPeriod(reader, SAMPLING.PROGRAMME_DEBUT, SAMPLING.PROGRAMME_FIN); - - sampleRow.setFishingZonesInfos(fishingZoneInfos); - sampleRow.setNbObservants(nbObservants); - sampleRow.setAverageTideTime(averageTideTime); - sampleRow.setProgramName(programName); - sampleRow.setPeriodBegin(period.getFromDate()); - sampleRow.setPeriodEnd(period.getThruDate()); - sampleRow.setComment(comment); - - // 16 fixed columns : 13 before months and 3 after - final int nbFixedColumns = 16; - // Months begin at 14th column - final int firstMonthColumnId = 13; - int nbTotalColumns = reader.getColumnCount(); - // Note : nbTotalColumns must be > nbFixedColumns - int lastMonthColumnId = firstMonthColumnId + nbTotalColumns - nbFixedColumns; - - DateFormat dateFormat = new SimpleDateFormat(SAMPLING.defaultDatePattern()); - - for (int i = firstMonthColumnId; i < lastMonthColumnId; i++) { - - Date monthDate = dateFormat.parse(reader.getHeader(i)); - Integer monthValue = StringUtils.isEmpty(reader.get(i)) ? null : Integer.parseInt(reader.get(i)); - - if (monthValue != null && DateUtils.between(monthDate, sampleRow.getPeriodBegin(), sampleRow.getPeriodEnd())) { - SampleMonthDAO dao = SuiviObsmerModelDAOHelper.getSampleMonthDAO(transaction); - - SampleMonth month = sampleRow.getSampleMonth(monthDate); - - if (month == null) { - month = dao.create( - SampleMonth.SAMPLE_ROW, sampleRow, - SampleMonth.PERIOD_DATE, monthDate); - sampleRow.addSampleMonth(month); - } - month.setExpectedTidesValue(monthValue); - } -// else if (monthValue != null) { -// // exception, outOfBounds month -// if (log.isErrorEnabled()) { -// log.error("Month out of bounds : value=" + monthValue + " _ monthDate=" + monthDate + -// " _ periode=" + sampleRow.getPeriodBegin() + " au " + sampleRow.getPeriodEnd()); -// } -// } - } - } - -// protected static final int TAB_MONTH = 0; -// protected static final int TAB_YEAR = 1; - -// @Deprecated -// protected int[] getMonthAndYear(String str) throws ParseException { -// DateFormat dateFormat = new SimpleDateFormat("MM/yyyy"); -// int[] result = new int[2]; -// -// Date date = dateFormat.parse(str); -// Calendar calendar = new GregorianCalendar(); -// calendar.setTime(date); -// -// result[TAB_MONTH] = calendar.get(Calendar.MONTH) + 1; -// result[TAB_YEAR] = calendar.get(Calendar.YEAR); -// return result; -// } - -} Copied: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceSamplingImpl.java (from rev 337, trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/impl/ServiceSamplingImpl.java) =================================================================== --- trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceSamplingImpl.java (rev 0) +++ trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceSamplingImpl.java 2010-02-09 01:30:52 UTC (rev 339) @@ -0,0 +1,759 @@ +/* + * *##% + * 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.services; + +import com.csvreader.CsvReader; +import fr.ifremer.suiviobsmer.ImportHelper; +import fr.ifremer.suiviobsmer.ImportHelper.FISHING_ZONE; +import fr.ifremer.suiviobsmer.ImportHelper.SAMPLING; +import fr.ifremer.suiviobsmer.SuiviObsmerBusinessException; +import fr.ifremer.suiviobsmer.SuiviObsmerBusinessException.Type; +import fr.ifremer.suiviobsmer.SuiviObsmerException; +import fr.ifremer.suiviobsmer.SuiviObsmerModelDAOHelper; +import fr.ifremer.suiviobsmer.SuiviObsmerContext; +import fr.ifremer.suiviobsmer.bean.FacadeRow; +import fr.ifremer.suiviobsmer.bean.FacadeRowImpl; +import fr.ifremer.suiviobsmer.bean.ImportResults; +import fr.ifremer.suiviobsmer.bean.ImportResultsImpl; +import fr.ifremer.suiviobsmer.bean.SamplingFilter; +import fr.ifremer.suiviobsmer.entity.*; +import fr.ifremer.suiviobsmer.services.ServiceSampling; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.Charset; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.apache.commons.lang.StringUtils; +import org.nuiton.topia.TopiaContext; +import org.nuiton.topia.TopiaException; +import org.nuiton.topia.framework.TopiaQuery; +import org.nuiton.topia.framework.TopiaQuery.Op; +import org.nuiton.topia.persistence.util.EntityLoador; +import org.nuiton.util.DateUtils; +import org.nuiton.util.PeriodDates; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * ServiceSamplingImpl + * + * Created: 30 nov. 2009 + * + * @author fdesbois + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ +public class ServiceSamplingImpl implements ServiceSampling { + + private static final Logger log = LoggerFactory.getLogger(ServiceSamplingImpl.class); + + protected TopiaContext rootContext; + + public ServiceSamplingImpl() throws SuiviObsmerException { + rootContext = SuiviObsmerContext.getTopiaRootContext(); + } + + @Override + public void createUpdateSampleRow(SampleRow row, List<Boat> boats, SampleRowLog rowLog) throws SuiviObsmerException { + TopiaContext transaction = null; + try { + transaction = rootContext.beginTransaction(); + + SampleRowLogDAO logDAO = SuiviObsmerModelDAOHelper.getSampleRowLogDAO(transaction); + SuiviObsmerContext.prepareTopiaId(SampleRowLog.class, rowLog); + logDAO.update(rowLog); + + boolean newRow = SuiviObsmerContext.prepareTopiaId(SampleRow.class, row); + + if (log.isDebugEnabled()) { + log.debug("new sampleRow : " + newRow); + log.debug("samplRow topiaId : " + row.getTopiaId()); + } + + String pattern = DateUtils.MONTH_PATTERN; + DateFormat dateFormat = new SimpleDateFormat(pattern); + + SampleRow oldRow = null; + Profession oldProfession = null; + Company oldCompany = null; + Map<String, SampleMonth> oldMonths = new HashMap<String, SampleMonth>(); + List<FishingZone> oldZones = new ArrayList<FishingZone>(); + // UPDATE + if (!newRow) { + // Prepare data for logging or deleting oldMonths + TopiaContext transaction2 = rootContext.beginTransaction(); + SampleRowDAO oldDAO = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction2); + oldRow = oldDAO.findByTopiaId(row.getTopiaId()); + oldCompany = oldRow.getCompany(); + oldProfession = oldRow.getProfession(); + for (SampleMonth month : oldRow.getSampleMonth()) { + oldMonths.put(month.getTopiaId(), month); + } + oldZones = oldRow.getFishingZone(); + transaction2.closeContext(); + + // NbObservants + if (oldRow.getNbObservants() != row.getNbObservants()) { + rowLog.addChange("Le nombre d'observateurs est passé de " + oldRow.getNbObservants() + " à " + row.getNbObservants()); + } + // AverageTideTime + if (oldRow.getAverageTideTime() != row.getAverageTideTime()) { + rowLog.addChange("La durée moyenne d'une marée est passé de " + oldRow.getAverageTideTime() + " jours à " + row.getAverageTideTime()); + } + } else { + rowLog.addChange("Le nombre d'observateurs est " + row.getNbObservants()); + rowLog.addChange("La durée moyenne d'une marée est " + row.getAverageTideTime()); + } + // ChangeLog Company + rowLog.addChangeCompany(oldCompany, row.getCompany()); + // ChangeLog Program + String oldProgram = oldRow != null ? oldRow.getProgramName() : null; + rowLog.addChangeProgram(oldProgram, row.getProgramName()); + // ChangeLog Period + PeriodDates oldPeriod = null; + if (oldRow != null) { + oldPeriod = new PeriodDates(oldRow.getPeriodBegin(), oldRow.getPeriodEnd()); + } + PeriodDates newPeriod = new PeriodDates(row.getPeriodBegin(), row.getPeriodEnd()); + rowLog.addChangePeriod(oldPeriod, newPeriod, pattern); + + // Save Profession + ProfessionDAO professionDAO = SuiviObsmerModelDAOHelper.getProfessionDAO(transaction); + SuiviObsmerContext.prepareTopiaId(Profession.class, row.getProfession()); + rowLog.addChangeProfession(oldProfession, row.getProfession()); + professionDAO.update(row.getProfession()); + + // Save sampleMonth + SampleMonthDAO monthDAO = SuiviObsmerModelDAOHelper.getSampleMonthDAO(transaction); + + // Delete oldMonths + List<SampleMonth> newMonths = row.getSampleMonth(); + for (SampleMonth oldMonth : oldMonths.values()) { + if (!newMonths.contains(oldMonth)) { + String date = dateFormat.format(oldMonth.getPeriodDate()); + // Delete old month : add to log + monthDAO.delete(oldMonth); + rowLog.addChange("Le mois " + date + " a été supprimé, " + + "l'ancienne valeur d'effort était " + oldMonth.getExpectedTidesValue()); + } + } + // Create or update months + for (SampleMonth month : newMonths) { + boolean monthCreated = SuiviObsmerContext.prepareTopiaId(SampleMonth.class, month); + String date = dateFormat.format(month.getPeriodDate()); + if (monthCreated) { + // log create month + rowLog.addChange("Le mois " + date + " a été créé avec un nombre de marées de " + month.getExpectedTidesValue()); + } else { + SampleMonth oldMonth = oldMonths.get(month.getTopiaId()); + if (oldMonth.getExpectedTidesValue() != month.getExpectedTidesValue()) { + // log change month value + rowLog.addChange("Le nombre de marées du mois " + date + " est passé de " + + oldMonth.getExpectedTidesValue() + " à " + month.getExpectedTidesValue()); + } + } + monthDAO.update(month); + } + + // Remove no longer elligibleBoats + row.removeNoLongerElligibleBoats(boats); + // Save new elligibleBoats + ElligibleBoatDAO dao = SuiviObsmerModelDAOHelper.getElligibleBoatDAO(transaction); + for (Boat boat : boats) { + if (!row.hasElligibleBoat(boat)) { + ElligibleBoat elligibleBoat = dao.create(); + elligibleBoat.setSampleRow(row); + elligibleBoat.setGlobalActive(true); + elligibleBoat.setBoat(boat); + row.addElligibleBoat(elligibleBoat); + } + } + + // ChangeLog boats + String oldBoats = oldRow != null ? oldRow.getMainElligibleBoatsAsString() : ""; + rowLog.addChangeBoats(oldBoats, row.getMainElligibleBoatsAsString()); + + + // Remove no longer linked FishingZone + List<FishingZone> newZones = row.getFishingZone(); + for (FishingZone oldZone : oldZones) { + if (!newZones.contains(oldZone)) { + updateFishingZones(transaction, oldZone.getTopiaId(), row, true); + rowLog.addChange("La zone de pêche " + oldZone.getCode() + " a été dissociée de la ligne"); + } + } + // Add new linked FishingZone + // ConcurrentModificationException ???? + for (FishingZone zone : new ArrayList<FishingZone>(newZones)) { + if (!oldZones.contains(zone)) { + updateFishingZones(transaction, zone.getTopiaId(), row, false); + rowLog.addChange("La zone de pêche " + zone.getCode() + " a été associée à la ligne"); + } + } + + // Save sampleRow : create or update + SampleRowDAO rowDAO = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); + if (log.isDebugEnabled()) { + log.debug("update row : " + row); + } + row.addSampleRowLog(rowLog); + rowDAO.update(row); + + if (log.isDebugEnabled()) { + log.debug("Change log : " + rowLog.getLogText()); + log.debug("commit transaction !"); + } + transaction.commitTransaction(); + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, + "Impossible de sauvegarder la ligne d'échantillon", eee); + } + } + + protected void updateFishingZones(TopiaContext transaction, String zoneId, SampleRow row, boolean delete) throws TopiaException { + // FIXME find a way to avoid saving links from FishingZone instead of SampleRow : + // variable inverse="true" in hibernate mapping of FishingZone, how to set this variable to SampleRow instead + FishingZoneDAO fishingZoneDAO = SuiviObsmerModelDAOHelper.getFishingZoneDAO(transaction); + FishingZone zoneFromDB = fishingZoneDAO.findByTopiaId(zoneId); + if (delete) { + zoneFromDB.removeSampleRow(row); + } else { + zoneFromDB.addSampleRow(row); + } + fishingZoneDAO.update(zoneFromDB); + } + +// @Override +// public List<SampleRowLog> getSampleRowLogs(SampleRow sampleRow) throws SuiviObsmerException { +// TopiaContext transaction = null; +// List<SampleRowLog> results = new ArrayList<SampleRowLog>(); +// try { +// transaction = rootContext.beginTransaction(); +// +// SampleRowLogDAO dao = SuiviObsmerModelDAOHelper.getSampleRowLogDAO(transaction); +// results = dao.createQuery().add(SampleRowLog.SAMPLE_ROW, sampleRow).addOrderDesc(TopiaEntity.TOPIA_CREATE_DATE).executeToEntityList(); +// +// transaction.closeContext(); +// } catch (Exception eee) { +// SuiviObsmerContext.serviceException(transaction, +// "Impossible de récupérer l'historique de la ligne d'échantillonnage", eee); +// } +// return results; +// } + + @Override + public FacadeRow getSampleRowsOrderedByFishingZone(PeriodDates period, Company company) throws SuiviObsmerException { + TopiaContext transaction = null; + FacadeRow result = new FacadeRowImpl(); + try { + if (period.getFromDate() == null || period.getThruDate() == null) { + throw new IllegalArgumentException("PeriodBegin date and/or PeriodEnd date can't be null !"); + } + transaction = rootContext.beginTransaction(); + + SampleRowDAO dao = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); + + TopiaQuery query = dao.createQuery("S").addDistinct(). + addFrom(FishingZone.class.getName() + " F"). + add("S IN elements(F." + FishingZone.SAMPLE_ROW + ")"); + + if (company != null) { + query.add("S." + SampleRow.COMPANY, company); + } + + // Prepare period dates + period.initDayOfMonthExtremities(); + query.add("S." + SampleRow.PERIOD_BEGIN, Op.LT, period.getThruDate()). + add("S." + SampleRow.PERIOD_END, Op.GT, period.getFromDate()); + + // Order By facade, sector, districtCode, sampleRowCode + String zoneOrder = "F." + FishingZone.FACADE_NAME + " , F." + FishingZone.SECTOR_NAME + ", F." + FishingZone.DISTRICT_CODE; + query.addOrder(zoneOrder).addOrder("S." + SampleRow.CODE).addSelect(zoneOrder); + // Load data + //query.addLoad(SampleRow.PROFESSION, SampleRow.COMPANY); + + if (log.isDebugEnabled()) { + log.debug("Query : " + query); + } + + List<SampleRow> results = dao.findAllByQuery(query); + + for (SampleRow row : results) { + // use FacadeRow to complete ordering using maps + result.addRow(row); + } + + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, + "Impossible de récupérer la liste des lignes du plan d'échantillonnage", eee); + } + return result; + } + + @Override + public List<String> getPrograms(Company company) throws SuiviObsmerException { + TopiaContext transaction = null; + List<String> results = new ArrayList<String>(); + try { + transaction = rootContext.beginTransaction(); + + SampleRowDAO dao = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); + TopiaQuery query = dao.createQuery(); + + if (company != null) { + query.add(SampleRow.COMPANY, company); + } + + results = (List<String>)query.setSelect("DISTINCT " + SampleRow.PROGRAM_NAME).execute(); + + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, + "Impossible de charger la liste des programmes", eee); + } + return results; + } + + @Override + public List<SampleRow> getSampleRowsByFilter(SamplingFilter filter) throws SuiviObsmerException { + TopiaContext transaction = null; + List<SampleRow> results = new ArrayList<SampleRow>(); + try { + transaction = rootContext.beginTransaction(); + + SampleRowDAO dao = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); + + TopiaQuery query = dao.createQuery("S").addDistinct().addOrder("S." + SampleRow.CODE); + + query = filter.prepareQueryForSampling(query, "S"); + + if (log.isDebugEnabled()) { + log.debug("Query : " + query); + } + +// if (finished) { +// // Only rows which are not finished will be kept +// Date current = SuiviObsmerContext.getCurrentDate(); +// query.add(SampleRow.PERIOD_END, Op.GE, current); +// } + +// if (filter.getCompany() != null) { +// query.add("S." + SampleRow.COMPANY, filter.getCompany()); +// } + + results = dao.findAllByQuery(query); + + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, + "Impossible de récupérer la liste des lignes du plan d'échantillonnage", eee); + } + return results; + } + + @Override + public SampleRow getSampleRow(String sampleRowId) throws SuiviObsmerException { + TopiaContext transaction = null; + SampleRow result = null; + try { + transaction = rootContext.beginTransaction(); + + SampleRowDAO dao = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); + + result = dao.findByTopiaId(sampleRowId); + + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, + "Impossible de charger la ligne d'échantillon ayant pour identifiant : " + sampleRowId, + eee); + } + return result; + } + + @Override + public void deleteSampleRow(SampleRow sampleRow) throws SuiviObsmerException { + TopiaContext transaction = null; + try { + transaction = rootContext.beginTransaction(); + + SampleRowDAO dao = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); + + SampleRow row = dao.findByTopiaId(sampleRow.getTopiaId()); + + dao.delete(row); + + transaction.commitTransaction(); + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, + "Impossible de supprimer la ligne d'échantillon : " + sampleRow.getCode(), + eee); + } + } + + @Override + public String getNewSampleRowCode(Date beginDate) throws SuiviObsmerException { + TopiaContext transaction = null; + String result = null; + if (beginDate == null) { + return result; + } + try { + transaction = SuiviObsmerContext.getTopiaRootContext().beginTransaction(); + + Calendar begin = new GregorianCalendar(); + begin.setTime(beginDate); + int year = begin.get(Calendar.YEAR); + + SampleRowDAO dao = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); + TopiaQuery query = dao.createQuery().add(SampleRow.CODE, Op.LIKE, year + "_%"); + + String maxCode = query.executeToString("MAX(" + SampleRow.CODE + ")"); + + if (log.isDebugEnabled()) { + log.debug("Max code found : " + maxCode); + } + + int num = 1; + if (!StringUtils.isEmpty(maxCode)) { + String[] part = maxCode.split("_"); + num = Integer.parseInt(part[1]) + 1; + } + String str = StringUtils.leftPad("" + num, 4, "0"); + result = year + "_" + str; + + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, + "Impossible de récupérer un nouveau code pour une ligne d'échantillonnage", + eee); + } + return result; + } + + @Override + public SampleRow getNewSampleRow() { + SampleRow row = new SampleRowImpl(); + row.setProfession(new ProfessionImpl()); + row.setFishingZone(new ArrayList<FishingZone>()); + //row.setProgram(new ProgramImpl()); + row.setElligibleBoat(new ArrayList<ElligibleBoat>()); + row.setSampleMonth(new ArrayList<SampleMonth>()); + return row; + } + + @Override + public SampleMonth getNewSampleMonth(Date period, SampleRow row) { + SampleMonth month = new SampleMonthImpl(); + month.setSampleRow(row); + month.setPeriodDate(period); + return month; + } + + /** + * Create a new profession from an existing one. Copy all attributes values from + * the profession in argument to a new profession not created yet in database. + * + * @param profession the profession source + * @return a new Profession + */ + @Override + public Profession getNewProfession(Profession profession) { + Profession newProfession = new ProfessionImpl(); + EntityLoador<Profession> loador = EntityLoador.newEntityLoador(Profession.class, + Profession.CODE_DCF5, Profession.LIBELLE, Profession.MESH_SIZE, Profession.OTHER, Profession.SIZE, Profession.SPECIES); + loador.load(profession, newProfession, false); + return newProfession; + } + + @Override + public ImportResults importSamplingPlanCsv(InputStream input) throws SuiviObsmerException { + TopiaContext transaction = null; + ImportResults result = new ImportResultsImpl(); + //int[] result = new int[3]; + int currRow = 0; + SampleRow row = null; + try { + transaction = rootContext.beginTransaction(); + + CsvReader reader = new CsvReader(input, Charset.forName("UTF-8")); + reader.readHeaders(); + + SampleRowDAO dao = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); + + //int nbImported = 0; + //int nbRefused = 0; + + while(reader.readRecord()) { + + currRow++; + + if (log.isTraceEnabled()) { + log.trace(" " + Arrays.asList(reader.getValues())); + } + + String code = ImportHelper.readSampleRowCode(reader); //reader.get(SAMPLING.PLAN_CODE.name()).trim(); + + if (StringUtils.isEmpty(code)) { + continue; + } + + String districts = reader.get(FISHING_ZONE.PECHE_DIVISION.name()); + + row = dao.findByCode(code); + // Refuse existing SampleRow + if (row != null) { + result.addError(currRow, "[CODE = " + code + "] refusé : Code déjà existant"); + result.incNbRefused(); + // Refuse Fishing zones empty + } else if (StringUtils.isEmpty(districts)) { + result.addError(currRow, "[CODE = " + code + "] refusé : Zone de pêche non renseigné"); + result.incNbRefused(); //nbRefused++; + } else { + row = dao.create(SampleRow.CODE, code); + + String companyName = ImportHelper.read(reader, SAMPLING.SOCIETE_NOM); + + // Create link with company if set in file + if (!StringUtils.isEmpty(companyName)) { + CompanyDAO companyDAO = SuiviObsmerModelDAOHelper.getCompanyDAO(transaction); + Company company = companyDAO.findByName(companyName); + if (company == null) { + throw new SuiviObsmerBusinessException(Type.IMPORT_ERROR, this.getClass(), + "Erreur à la ligne " + currRow + " [CODE = " + code + "] : " + + "La société portant le nom '" + companyName + "' n'existe pas dans l'application"); + } + row.setCompany(company); + } + + // Import profession. Creation if not exist + Profession profession = importProfession(transaction, reader); + row.setProfession(profession); + + // Import zones and set them to the row + // throw SuiviObsmerException if FishingZone doesn't exist + importFishingZones(transaction, districts, currRow, row); + + updateRow(transaction, row, reader); + result.incNbImported(); //nbImported++; + } + // Commit row by row + transaction.commitTransaction(); + } + + transaction.closeContext(); + + } catch (NumberFormatException eee) { + SuiviObsmerContext.serviceException(transaction, + "Erreur à la ligne " + currRow + " [CODE = " + row.getCode() + "] : " + + "Le format de la durée moyenne des marées est incorrect, il doit être de la forme : 1.9 ", eee); + } catch (ParseException eee) { + SuiviObsmerContext.serviceException(transaction, + "Erreur à la ligne " + currRow + " [CODE = " + row.getCode() + "] : " + + "Le format des dates est incorrect, il doit être de la forme : MM/AAAA", eee); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, + "Erreur à la ligne " + currRow + " [CODE = " + row.getCode() + "]", + eee); + } + return result; + } + + /** + * Import a profession from CSV File from importSamplingPlanCsv method. + * This profession is imported for a new SampleRow line. + * Key value for the profession : codeDCF5, meshSize, size, other. + * If profession already exists, update libelle and species. + * @param transaction Topia transaction for using ProfessionDAO + * @param reader CsvReader for getting Profession parameters + * @return an existing Profession or a new one + * @throws IOException for reader errors + * @throws TopiaException for dao errors + */ + protected Profession importProfession(TopiaContext transaction, CsvReader reader) + throws IOException, TopiaException { + + String codeDCF5 = reader.get(SAMPLING.METIER_CODE_DCF5.name()).trim(); + String maillage = reader.get(SAMPLING.METIER_MAILLAGE.name()).trim(); + String taille = reader.get(SAMPLING.METIER_TAILLE.name()).trim(); + String autre = reader.get(SAMPLING.METIER_AUTRE.name()).trim(); + String libelle = reader.get(SAMPLING.METIER_LIBELLE.name()).trim(); + String especes = reader.get(SAMPLING.METIER_ESPECES.name()).trim(); + + ProfessionDAO dao = SuiviObsmerModelDAOHelper.getProfessionDAO(transaction); + Map<String, Object> existParams = new HashMap<String, Object>(); + existParams.put(Profession.CODE_DCF5, codeDCF5); + existParams.put(Profession.MESH_SIZE, maillage); + existParams.put(Profession.SIZE, taille); + existParams.put(Profession.OTHER, autre); + + Profession profession = dao.findByProperties(existParams); + + if (profession == null) { + profession = dao.create(existParams); + } + + profession.setLibelle(libelle); + profession.setSpecies(especes); + + return profession; + } + + /** + * Import a fishingZone from CSV File from importSamplingPlanCsv method. + * These fishingZones are imported for a new SampleRow line. + * Key value for the fishingZone : districtCode. + * The districts argument contains multiple districtCode separating with " - ". + * The fishingZone must be exist in database. + * @param transaction Topia transaction for using FishingZoneDAO + * @param districts String which contains several fishingZone districtCodes + * @param currRow Row number in the line for the SampleRow + * @param row SampleRow linked with districts (from Csv file) + * @throws TopiaException for dao errors + * @throws SuiviObsmerException if a FishingZone doesn't exist. + */ + protected void importFishingZones(TopiaContext transaction, String districts, int currRow, SampleRow row) + throws TopiaException, SuiviObsmerException { + + FishingZoneDAO dao = SuiviObsmerModelDAOHelper.getFishingZoneDAO(transaction); + + List<String> districtList = new ArrayList<String>(Arrays.asList(districts.split(" / "))); + + if (log.isDebugEnabled()) { + log.debug("FishingZone districts : " + districts); + log.debug("FishingZone nb zones : " + districtList.size()); + } + for (String districtCode : districtList) { + FishingZone zone = dao.findByDistrictCode(districtCode.trim()); + if (zone == null) { + throw new SuiviObsmerBusinessException(Type.IMPORT_ERROR, this.getClass(), + "Erreur à la ligne " + currRow + " [CODE = " + row.getCode() + "] : " + + "Cette ligne est lié à une zone inexistante : " + districtCode); + } + row.addFishingZone(zone); + } + } + + /** + * Update a SampleRow from CSV File from importSamplingPlanCsv method. + * Program must be set to get beginDate and endDate for getting correct months. + * SampleMonth will be created corresponding to program period. + * Careful : fixed columns set to 16 and months columns start to 13. + * Updatable fields : fishingZoneInfos, nbObservants, averageTideTime, sampleMonths. + * @param transaction Topia transaction for using FishingZoneDAO + * @param sampleRow + * @param reader CsvReader to get values for updatable fields + * @throws IOException for CsvReader errors + * @throws TopiaException for SampleMonthDAO errors + * @throws ParseException for format errors + * @see #getMonthAndYear(java.lang.String) + */ + protected void updateRow(TopiaContext transaction, SampleRow sampleRow, CsvReader reader) + throws IOException, TopiaException, ParseException { + + String fishingZoneInfos = ImportHelper.read(reader, SAMPLING.PECHE_AUTRE); + int nbObservants = ImportHelper.readInt(reader, SAMPLING.PLAN_NB_OBSERV); + String averageStr = ImportHelper.read(reader, SAMPLING.PLAN_DUREE_MOY); + averageStr = averageStr.replaceAll(",", "."); + double averageTideTime = Double.parseDouble(averageStr); + String programName = ImportHelper.read(reader, SAMPLING.PROGRAMME_CODE); + String comment = ImportHelper.read(reader, SAMPLING.PLAN_COMMENT); + PeriodDates period = ImportHelper.readPeriod(reader, SAMPLING.PROGRAMME_DEBUT, SAMPLING.PROGRAMME_FIN); + + sampleRow.setFishingZonesInfos(fishingZoneInfos); + sampleRow.setNbObservants(nbObservants); + sampleRow.setAverageTideTime(averageTideTime); + sampleRow.setProgramName(programName); + sampleRow.setPeriodBegin(period.getFromDate()); + sampleRow.setPeriodEnd(period.getThruDate()); + sampleRow.setComment(comment); + + // 16 fixed columns : 13 before months and 3 after + final int nbFixedColumns = 16; + // Months begin at 14th column + final int firstMonthColumnId = 13; + int nbTotalColumns = reader.getColumnCount(); + // Note : nbTotalColumns must be > nbFixedColumns + int lastMonthColumnId = firstMonthColumnId + nbTotalColumns - nbFixedColumns; + + DateFormat dateFormat = new SimpleDateFormat(SAMPLING.defaultDatePattern()); + + for (int i = firstMonthColumnId; i < lastMonthColumnId; i++) { + + Date monthDate = dateFormat.parse(reader.getHeader(i)); + Integer monthValue = StringUtils.isEmpty(reader.get(i)) ? null : Integer.parseInt(reader.get(i)); + + if (monthValue != null && DateUtils.between(monthDate, sampleRow.getPeriodBegin(), sampleRow.getPeriodEnd())) { + SampleMonthDAO dao = SuiviObsmerModelDAOHelper.getSampleMonthDAO(transaction); + + SampleMonth month = sampleRow.getSampleMonth(monthDate); + + if (month == null) { + month = dao.create( + SampleMonth.SAMPLE_ROW, sampleRow, + SampleMonth.PERIOD_DATE, monthDate); + sampleRow.addSampleMonth(month); + } + month.setExpectedTidesValue(monthValue); + } +// else if (monthValue != null) { +// // exception, outOfBounds month +// if (log.isErrorEnabled()) { +// log.error("Month out of bounds : value=" + monthValue + " _ monthDate=" + monthDate + +// " _ periode=" + sampleRow.getPeriodBegin() + " au " + sampleRow.getPeriodEnd()); +// } +// } + } + } + +// protected static final int TAB_MONTH = 0; +// protected static final int TAB_YEAR = 1; + +// @Deprecated +// protected int[] getMonthAndYear(String str) throws ParseException { +// DateFormat dateFormat = new SimpleDateFormat("MM/yyyy"); +// int[] result = new int[2]; +// +// Date date = dateFormat.parse(str); +// Calendar calendar = new GregorianCalendar(); +// calendar.setTime(date); +// +// result[TAB_MONTH] = calendar.get(Calendar.MONTH) + 1; +// result[TAB_YEAR] = calendar.get(Calendar.YEAR); +// return result; +// } + +} Deleted: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceSynthesisImpl.java =================================================================== --- trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/impl/ServiceSynthesisImpl.java 2010-02-04 21:33:50 UTC (rev 325) +++ trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceSynthesisImpl.java 2010-02-09 01:30:52 UTC (rev 339) @@ -1,327 +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.impl; - -import fr.ifremer.suiviobsmer.SuiviObsmerContext; -import fr.ifremer.suiviobsmer.SuiviObsmerException; -import fr.ifremer.suiviobsmer.SuiviObsmerModelDAOHelper; -import fr.ifremer.suiviobsmer.bean.BoardingResult; -import fr.ifremer.suiviobsmer.bean.BoardingResultImpl; -import fr.ifremer.suiviobsmer.bean.SamplingFilter; -import fr.ifremer.suiviobsmer.entity.Boat; -import fr.ifremer.suiviobsmer.entity.Company; -import fr.ifremer.suiviobsmer.entity.Contact; -import fr.ifremer.suiviobsmer.entity.ContactDAO; -import fr.ifremer.suiviobsmer.entity.SampleMonth; -import fr.ifremer.suiviobsmer.entity.SampleMonthDAO; -import fr.ifremer.suiviobsmer.entity.SampleRow; -import fr.ifremer.suiviobsmer.services.ServiceSynthesis; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.SortedMap; -import java.util.TreeMap; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.framework.TopiaQuery; -import org.nuiton.topia.framework.TopiaQuery.Op; -import org.nuiton.util.PeriodDates; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * ServiceSynthesisImpl - * - * Created: 7 janv. 2010 - * - * @author fdesbois - * @version $Revision$ - * - * Mise a jour: $Date$ - * par : $Author$ - */ -public class ServiceSynthesisImpl implements ServiceSynthesis { - - private static final Logger log = LoggerFactory.getLogger(ServiceSynthesisImpl.class); - - protected TopiaContext rootContext; - - public ServiceSynthesisImpl() throws SuiviObsmerException { - rootContext = SuiviObsmerContext.getTopiaRootContext(); - } - - @Override - public List<SortedMap<Date, Integer>> getDataSampling(SamplingFilter filter) throws SuiviObsmerException { - TopiaContext transaction = null; - List<SortedMap<Date, Integer>> results = new ArrayList<SortedMap<Date, Integer>>(); - try { - transaction = rootContext.beginTransaction(); - - PeriodDates period = filter.getPeriod(); - if (period == null || period.getFromDate() == null || period.getThruDate() == null) { - return results; - } - - SortedMap<Date, Integer> serie1 = new TreeMap<Date,Integer>(); - SortedMap<Date, Integer> serie2 = new TreeMap<Date,Integer>(); - results.add(serie1); - results.add(serie2); - - // Prepare results - for (Date month : period.getMonths()) { - serie1.put(month, 0); - serie2.put(month, 0); - } - - SampleMonthDAO dao = SuiviObsmerModelDAOHelper.getSampleMonthDAO(transaction); - String periodDate = "M." + SampleMonth.PERIOD_DATE; - TopiaQuery<SampleMonth> query = dao.createQuery("M"). - setSelect(periodDate). - addSelect("SUM(M." + SampleMonth.REAL_TIDES_VALUE + ")"). - addSelect("SUM(M." + SampleMonth.EXPECTED_TIDES_VALUE + ")"). - add(periodDate + " BETWEEN :fromDate AND :thruDate"). - addParam("fromDate", period.getFromDate()).addParam("thruDate", period.getThruDate()). - addGroup(periodDate).addOrder(periodDate); - - query = filter.prepareQueryForSampling(query, "M." + SampleMonth.SAMPLE_ROW); - - if (log.isTraceEnabled()) { - log.trace("Exec query : " + query); - } - - List<Object[]> res = (List<Object[]>)query.execute(); - - for (Object[] tab : res) { - Date date = (Date)tab[0]; - int sumReal = ((Long)tab[1]).intValue(); - int sumExpected = ((Long)tab[2]).intValue(); - serie1.put(date, sumExpected); - serie2.put(date, sumReal); - if (log.isTraceEnabled()) { - DateFormat dateFormat = new SimpleDateFormat(period.getPattern()); - log.trace("Res : " + dateFormat.format(date) + " : " + sumReal + " / " + sumExpected); - } - } - - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, - "Impossible de récupérer les données pour le graphique dynamique des efforts de marées", eee); - } - return results; - } - - /** - * We need to select the boats and for each one, the number of boardings - * done. The number of boardings is calculated with the number of contacts - * finished linked with each boat. The {@code fromDate} is used to filter - * results since this date. For observer view, only results for his - * company is needed. - * - * @param company the company used to filter results - * @param fromDate the since date used to filter contact results - * @return a BoardingResult which contains the number of boats for boardings - * from 1 to {@link MAX_BOARDINGS}, the boat with the max boarding and its - * value. - * @throws SuiviObsmerException - */ - @Override - public BoardingResult getBoardingBoats(Company company, Date fromDate) - throws SuiviObsmerException { - TopiaContext transaction = null; - Map<String, Integer> map = new LinkedHashMap<String, Integer>(); - BoardingResult result = new BoardingResultImpl(); - result.setData(map); - try { - transaction = rootContext.beginTransaction(); - - // Initialiaze max boardings and its max key value - final int MAX_BOARDINGS = 12; - final String MAX_BOARDINGS_KEY = MAX_BOARDINGS + " +"; - - // Prepare map which contains for each entry the number of boardings - // for the key and the number of boats for the value. - for (int i = 1; i < MAX_BOARDINGS; i++) { - map.put(String.valueOf(i), 0); - } - map.put(MAX_BOARDINGS_KEY, 0); - - ContactDAO dao = - SuiviObsmerModelDAOHelper.getContactDAO(transaction); - // The number of boardings is the number of finished contacts - // Use fromDate to filter contacts finished from this date - // No need to use boat filter for this method - TopiaQuery<Contact> query = - dao.createQueryDoneContactsFromDate(null, fromDate); - - String contact = query.getMainAlias(); - String sampleRow = contact + "." + Contact.SAMPLE_ROW; - - // Only for sampleRows with averageTideTime less or equals to 2 days - query.add(sampleRow + "." + SampleRow.AVERAGE_TIDE_TIME, Op.LE, 2.); - - // Add filter on sampleRow company if needed - if (company != null) { - query.add(sampleRow + "." + SampleRow.COMPANY, company); - } - - // Prepare aliases for mapping results in select part - String countAlias = "nbBoardings"; - String boatAlias = "boat"; - // Use a map for each result with boat and its number of boardings - // Order by number of boardings to easily find the max value (the - // first result) - query.setSelect("new map(" + contact + "." + Contact.BOAT + " as " + - boatAlias + ", COUNT(*) as " + countAlias + ")"). - addGroup(contact + "." + Contact.BOAT). - addOrderDesc("COUNT(*)"); - - if (log.isTraceEnabled()) { - log.trace("Exec query : " + query); - } - - List<Map<String, Object>> nbBoardingsByBoat = query.execute(); - - if (!nbBoardingsByBoat.isEmpty()) { - for (Map<String, Object> row : nbBoardingsByBoat) { - Long count = (Long)row.get(countAlias); - int intValue = count.intValue(); - String value = count.toString(); - if (intValue >= MAX_BOARDINGS) { - value = MAX_BOARDINGS_KEY; - } - // Increment the number of boats for the current number of - // boardings - Integer nbBoats = map.get(value); - map.put(value, nbBoats + 1); - } - - // Set the max boat and its number of boardings value - Map<String, Object> max = nbBoardingsByBoat.get(0); - result.setMaxBoardingBoat((Boat)max.get(boatAlias)); - Long maxValue = (Long)max.get(countAlias); - result.setMaxBoardingValue(maxValue.intValue()); - } - - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, - "Impossible de récupérer les données pour le graphique " + - "dynamique des efforts de marées", eee); - } - return result; - } - - @Override - public Map<Company, Double> getNonComplianceBoardingIndicator(Company company) throws SuiviObsmerException { - TopiaContext transaction = null; - // Carefull with results, the company may not be present in the map : - // only if there is no unfinished sampleRow or no contact done - Map<Company, Double> results = new HashMap<Company, Double>(); - try { - transaction = rootContext.beginTransaction(); - - ContactDAO dao = SuiviObsmerModelDAOHelper.getContactDAO(transaction); - - // Only for done contacts with no constraint - TopiaQuery<Contact> query = - dao.createQueryDoneContactsFromDate(null, null); - - String contactKey = query.getMainAlias(); - String sampleRowKey = contactKey + "." + Contact.SAMPLE_ROW; - String companyKey = sampleRowKey + "." + SampleRow.COMPANY; - - // Only for unfinished sampleRows - Date current = SuiviObsmerContext.getCurrentDate(); - query.add(sampleRowKey + "." + SampleRow.PERIOD_END, Op.GE, current); - - if (company != null) { - query.add(companyKey, company); - } - - // Prepare results - query.setSelect(companyKey). - addSelect("COUNT(*)"). - addGroup(companyKey); - - if (log.isTraceEnabled()) { - log.trace("Exec query for total : " + query); - } - - List<Object[]> totalResults = query.execute(); - - // Use the same query and add the constraint of non compliance - //i.e. nbObservantsReal (contact) < nbObservantsExpected (sampleRow) - query.add(contactKey + "." + Contact.NB_OBSERVANTS + " < " + - sampleRowKey + "." + SampleRow.NB_OBSERVANTS); - - if (log.isTraceEnabled()) { - log.trace("Exec query for result : " + query); - } - - List<Object[]> diffResults = query.execute(); - - // Use the map to set the number of non compliance results - for (Object[] row : diffResults) { - Company rowCompany = (Company)row[0]; - Long rowCount = (Long)row[1]; - if (log.isTraceEnabled()) { - log.trace("result row : " + rowCompany.getName() + " = " + rowCount); - } - results.put(rowCompany, rowCount.doubleValue()); - } - - // Get the previous value from the map and make the division to have - // the result percent of non compliance. Put 0 in the map if no - // previous result is set - for (Object[] row : totalResults) { - Company rowCompany = (Company)row[0]; - Long rowCount = (Long)row[1]; - if (log.isTraceEnabled()) { - log.trace("total row : " + rowCompany.getName() + " = " + rowCount); - } - Double value = results.get(rowCompany); - if (value == null) { - results.put(rowCompany, 0.); - } else { - results.put(rowCompany, value / rowCount); - } - } - - transaction.closeContext(); - } catch (Exception eee) { - String msgEnd = ""; - if (company != null) { - msgEnd = " pour la société " + company.getName(); - } - SuiviObsmerContext.serviceException(transaction, - "Impossible de récupérer l'indicateur de non respect du " + - "nombre d'observateurs embarqués" + msgEnd, eee); - } - return results; - } - -} Copied: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceSynthesisImpl.java (from rev 337, trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/impl/ServiceSynthesisImpl.java) =================================================================== --- trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceSynthesisImpl.java (rev 0) +++ trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceSynthesisImpl.java 2010-02-09 01:30:52 UTC (rev 339) @@ -0,0 +1,406 @@ +/* + * *##% + * 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.services; + +import fr.ifremer.suiviobsmer.SuiviObsmerContext; +import fr.ifremer.suiviobsmer.SuiviObsmerException; +import fr.ifremer.suiviobsmer.SuiviObsmerModelDAOHelper; +import fr.ifremer.suiviobsmer.bean.BoardingResult; +import fr.ifremer.suiviobsmer.bean.BoardingResultImpl; +import fr.ifremer.suiviobsmer.bean.ContactStateStatistics; +import fr.ifremer.suiviobsmer.bean.ContactStateStatisticsImpl; +import fr.ifremer.suiviobsmer.bean.SamplingFilter; +import fr.ifremer.suiviobsmer.entity.Boat; +import fr.ifremer.suiviobsmer.entity.Company; +import fr.ifremer.suiviobsmer.entity.Contact; +import fr.ifremer.suiviobsmer.entity.ContactDAO; +import fr.ifremer.suiviobsmer.entity.SampleMonth; +import fr.ifremer.suiviobsmer.entity.SampleMonthDAO; +import fr.ifremer.suiviobsmer.entity.SampleRow; +import fr.ifremer.suiviobsmer.entity.WaoUser; +import fr.ifremer.suiviobsmer.services.ServiceSynthesis; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.SortedMap; +import java.util.TreeMap; +import org.nuiton.topia.TopiaContext; +import org.nuiton.topia.framework.TopiaQuery; +import org.nuiton.topia.framework.TopiaQuery.Op; +import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.util.PeriodDates; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * ServiceSynthesisImpl + * + * Created: 7 janv. 2010 + * + * @author fdesbois + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ +public class ServiceSynthesisImpl implements ServiceSynthesis { + + private static final Logger log = LoggerFactory.getLogger(ServiceSynthesisImpl.class); + + protected TopiaContext rootContext; + + public ServiceSynthesisImpl() throws SuiviObsmerException { + rootContext = SuiviObsmerContext.getTopiaRootContext(); + } + + @Override + public List<SortedMap<Date, Integer>> getDataSampling(SamplingFilter filter) throws SuiviObsmerException { + TopiaContext transaction = null; + List<SortedMap<Date, Integer>> results = new ArrayList<SortedMap<Date, Integer>>(); + try { + transaction = rootContext.beginTransaction(); + + PeriodDates period = filter.getPeriod(); + if (period == null || period.getFromDate() == null || period.getThruDate() == null) { + return results; + } + + SortedMap<Date, Integer> serie1 = new TreeMap<Date,Integer>(); + SortedMap<Date, Integer> serie2 = new TreeMap<Date,Integer>(); + results.add(serie1); + results.add(serie2); + + // Prepare results + for (Date month : period.getMonths()) { + serie1.put(month, 0); + serie2.put(month, 0); + } + + SampleMonthDAO dao = SuiviObsmerModelDAOHelper.getSampleMonthDAO(transaction); + String periodDate = "M." + SampleMonth.PERIOD_DATE; + TopiaQuery query = dao.createQuery("M"). + setSelect(periodDate). + addSelect("SUM(M." + SampleMonth.REAL_TIDES_VALUE + ")"). + addSelect("SUM(M." + SampleMonth.EXPECTED_TIDES_VALUE + ")"). + add(periodDate + " BETWEEN :fromDate AND :thruDate"). + addParam("fromDate", period.getFromDate()).addParam("thruDate", period.getThruDate()). + addGroup(periodDate).addOrder(periodDate); + + query = filter.prepareQueryForSampling(query, "M." + SampleMonth.SAMPLE_ROW); + + if (log.isTraceEnabled()) { + log.trace("Exec query : " + query); + } + + List<Object[]> res = (List<Object[]>)query.execute(); + + for (Object[] tab : res) { + Date date = (Date)tab[0]; + int sumReal = ((Long)tab[1]).intValue(); + int sumExpected = ((Long)tab[2]).intValue(); + serie1.put(date, sumExpected); + serie2.put(date, sumReal); + if (log.isTraceEnabled()) { + DateFormat dateFormat = new SimpleDateFormat(period.getPattern()); + log.trace("Res : " + dateFormat.format(date) + " : " + sumReal + " / " + sumExpected); + } + } + + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, + "Impossible de récupérer les données pour le graphique dynamique des efforts de marées", eee); + } + return results; + } + + /** + * We need to select the boats and for each one, the number of boardings + * done. The number of boardings is calculated with the number of contacts + * finished linked with each boat. The {@code fromDate} is used to filter + * results since this date. For observer view, only results for his + * company is needed. + * + * @param company the company used to filter results + * @param fromDate the since date used to filter contact results + * @return a BoardingResult which contains the number of boats for boardings + * from 1 to {@link MAX_BOARDINGS}, the boat with the max boarding and its + * value. + * @throws SuiviObsmerException + */ + @Override + public BoardingResult getBoardingBoats(Company company, Date fromDate) + throws SuiviObsmerException { + TopiaContext transaction = null; + Map<String, Integer> map = new LinkedHashMap<String, Integer>(); + BoardingResult result = new BoardingResultImpl(); + result.setData(map); + try { + transaction = rootContext.beginTransaction(); + + // Initialiaze max boardings and its max key value + final int maxBoardings = 12; + final String maxBoardingsKey = maxBoardings + " +"; + + // Prepare map which contains for each entry the number of boardings + // for the key and the number of boats for the value. + for (int i = 1; i < maxBoardings; i++) { + map.put(String.valueOf(i), 0); + } + map.put(maxBoardingsKey, 0); + + ContactDAO dao = + SuiviObsmerModelDAOHelper.getContactDAO(transaction); + // The number of boardings is the number of finished contacts + // Use fromDate to filter contacts finished from this date + // No need to use boat filter for this method + TopiaQuery query = + dao.createQueryDoneContactsFromDate(null, fromDate); + + String contact = query.getMainAlias(); + String sampleRow = contact + "." + Contact.SAMPLE_ROW; + + // Only for sampleRows with averageTideTime less or equals to 2 days + query.add(sampleRow + "." + SampleRow.AVERAGE_TIDE_TIME, Op.LE, 2.); + + // Add filter on sampleRow company if needed + if (company != null) { + query.add(sampleRow + "." + SampleRow.COMPANY, company); + } + + // Prepare aliases for mapping results in select part + String countAlias = "nbBoardings"; + String boatAlias = "boat"; + // Use a map for each result with boat and its number of boardings + // Order by number of boardings to easily find the max value (the + // first result) + query.setSelect("new map(" + contact + "." + Contact.BOAT + " as " + + boatAlias + ", COUNT(*) as " + countAlias + ")"). + addGroup(contact + "." + Contact.BOAT). + addOrderDesc("COUNT(*)"); + + if (log.isTraceEnabled()) { + log.trace("Exec query : " + query); + } + + List<Map<String, Object>> nbBoardingsByBoat = query.execute(); + + if (!nbBoardingsByBoat.isEmpty()) { + for (Map<String, Object> row : nbBoardingsByBoat) { + Long count = (Long)row.get(countAlias); + int intValue = count.intValue(); + String value = count.toString(); + if (intValue >= maxBoardings) { + value = maxBoardingsKey; + } + // Increment the number of boats for the current number of + // boardings + Integer nbBoats = map.get(value); + map.put(value, nbBoats + 1); + } + + // Set the max boat and its number of boardings value + Map<String, Object> max = nbBoardingsByBoat.get(0); + result.setMaxBoardingBoat((Boat)max.get(boatAlias)); + Long maxValue = (Long)max.get(countAlias); + result.setMaxBoardingValue(maxValue.intValue()); + } + + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, + "Impossible de récupérer les données pour le graphique " + + "dynamique des efforts de marées", eee); + } + return result; + } + + @Override + public Map<Company, Double> getNonComplianceBoardingIndicator(Company company) throws SuiviObsmerException { + TopiaContext transaction = null; + // Carefull with results, the company may not be present in the map : + // only if there is no unfinished sampleRow or no contact done + Map<Company, Double> results = new HashMap<Company, Double>(); + try { + transaction = rootContext.beginTransaction(); + + ContactDAO dao = SuiviObsmerModelDAOHelper.getContactDAO(transaction); + + // Only for done contacts with no constraint + TopiaQuery query = + dao.createQueryDoneContactsFromDate(null, null); + + String contactKey = query.getMainAlias(); + String sampleRowKey = contactKey + "." + Contact.SAMPLE_ROW; + String companyKey = sampleRowKey + "." + SampleRow.COMPANY; + + // Only for unfinished sampleRows + Date current = SuiviObsmerContext.getCurrentDate(); + query.add(sampleRowKey + "." + SampleRow.PERIOD_END, Op.GE, current); + + if (company != null) { + query.add(companyKey, company); + } + + // Prepare results + query.setSelect(companyKey, "COUNT(*)").addGroup(companyKey); + + if (log.isDebugEnabled()) { + log.debug("Exec query for total : " + query); + } + + List<Object[]> totalResults = query.execute(); + + // Use the same query and add the constraint of non compliance + //i.e. nbObservantsReal (contact) < nbObservantsExpected (sampleRow) + query.add(contactKey + "." + Contact.NB_OBSERVANTS + " < " + + sampleRowKey + "." + SampleRow.NB_OBSERVANTS); + + if (log.isDebugEnabled()) { + log.debug("Exec query for result : " + query); + } + + List<Object[]> diffResults = query.execute(); + + // Use the map to set the number of non compliance results + for (Object[] row : diffResults) { + Company rowCompany = (Company)row[0]; + Long rowCount = (Long)row[1]; + if (log.isDebugEnabled()) { + log.debug("result row : " + rowCompany.getName() + " = " + rowCount); + } + results.put(rowCompany, rowCount.doubleValue()); + } + + // Get the previous value from the map and make the division to have + // the result percent of non compliance. Put 0 in the map if no + // previous result is set + for (Object[] row : totalResults) { + Company rowCompany = (Company)row[0]; + Long rowCount = (Long)row[1]; + if (log.isDebugEnabled()) { + log.debug("total row : " + rowCompany.getName() + " = " + rowCount); + } + Double value = results.get(rowCompany); + if (value == null) { + results.put(rowCompany, 0.); + } else { + results.put(rowCompany, value / rowCount); + } + } + + transaction.closeContext(); + } catch (Exception eee) { + String msgEnd = ""; + if (company != null) { + msgEnd = " pour la société " + company.getName(); + } + SuiviObsmerContext.serviceException(transaction, + "Impossible de récupérer l'indicateur de non respect du " + + "nombre d'observateurs embarqués" + msgEnd, eee); + } + return results; + } + + @Override + public Collection<ContactStateStatistics> getContactStateStatistics(Company company, PeriodDates period) throws SuiviObsmerException { + TopiaContext transaction = null; + Map<Company, ContactStateStatistics> results = new HashMap<Company, ContactStateStatistics>(); + try { + transaction = rootContext.beginTransaction(); + + ContactDAO dao = SuiviObsmerModelDAOHelper.getContactDAO(transaction); + + // Only for contacts not refused by the program + String contactKey = "C"; + String validationProgramKey = contactKey + "." + Contact.VALIDATION_PROGRAM; + TopiaQuery query = dao.createQuery(contactKey). + add(validationProgramKey + " IS NULL " + + "OR " + validationProgramKey + " = :booleanTrue"). + addParam("booleanTrue", Boolean.TRUE); + + String companyKey = contactKey + "." + Contact.OBSERVER + "." + WaoUser.COMPANY; + + if (company != null) { + query.add(companyKey, company); + } + + if (period != null) { + // Contacts include in the period + String tideBeginDateKey = contactKey + "." + Contact.TIDE_BEGIN_DATE; + String createDateKey = contactKey + "." + TopiaEntity.TOPIA_CREATE_DATE; + query.add("(" + tideBeginDateKey + " IS NOT NULL " + + "AND " + tideBeginDateKey + " BETWEEN :fromDate AND :thruDate)" + + " OR (" + tideBeginDateKey + " IS NULL " + + "AND " + createDateKey + " BETWEEN :fromDate AND :thruDate)"); + + query.addParam("fromDate", period.getFromDate()). + addParam("thruDate", period.getThruDate()); + } + + String stateKey = contactKey + "." + Contact.STATE; + query.addGroup(companyKey, stateKey). + addOrder(companyKey). + setSelect(companyKey, stateKey, "COUNT(*)"); + + if (log.isDebugEnabled()) { + log.debug("Exec query : " + query); + } + + List<Object[]> res = query.execute(); + + for (Object[] row : res) { + Company rowCompany = (Company)row[0]; + String rowState = (String)row[1]; + Long rowCount = (Long)row[2]; + if (log.isDebugEnabled()) { + log.debug("res : " + rowCompany.getName() + " _ " + rowState + " _ " + rowCount); + } + ContactStateStatistics stats = results.get(rowCompany); + if (stats == null) { + stats = new ContactStateStatisticsImpl(); + stats.setCompany(rowCompany); + results.put(rowCompany, stats); + } + stats.addResult(rowState, rowCount.intValue()); + } + + transaction.closeContext(); + } catch (Exception eee) { + String msgEnd = ""; + if (company != null) { + msgEnd = " pour la société " + company.getName(); + } + SuiviObsmerContext.serviceException(transaction, + "Impossible de récupérer les statistiques sur les états des " + + "contacts " + msgEnd, eee); + } + return results.values(); + } + +} Deleted: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceUserImpl.java =================================================================== --- trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/impl/ServiceUserImpl.java 2010-02-04 21:33:50 UTC (rev 325) +++ trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceUserImpl.java 2010-02-09 01:30:52 UTC (rev 339) @@ -1,322 +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.impl; - -import fr.ifremer.suiviobsmer.SuiviObsmerBusinessException; -import fr.ifremer.suiviobsmer.SuiviObsmerBusinessException.Type; -import fr.ifremer.suiviobsmer.SuiviObsmerException; -import fr.ifremer.suiviobsmer.SuiviObsmerModelDAOHelper; -import fr.ifremer.suiviobsmer.SuiviObsmerContext; -import fr.ifremer.suiviobsmer.entity.Company; -import fr.ifremer.suiviobsmer.entity.CompanyDAO; -import fr.ifremer.suiviobsmer.entity.Contact; -import fr.ifremer.suiviobsmer.entity.ContactDAO; -import fr.ifremer.suiviobsmer.entity.SampleRowLog; -import fr.ifremer.suiviobsmer.entity.SampleRowLogDAO; -import fr.ifremer.suiviobsmer.entity.WaoUser; -import fr.ifremer.suiviobsmer.entity.WaoUserDAO; -import fr.ifremer.suiviobsmer.services.ServiceUser; -import java.util.ArrayList; -import java.util.List; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.framework.TopiaQuery; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * ServiceUserImpl - * - * Created: 27 nov. 2009 - * - * @author fdesbois - * @version $Revision$ - * - * Mise a jour: $Date$ - * par : $Author$ - */ -public class ServiceUserImpl implements ServiceUser { - - private static final Logger log = LoggerFactory.getLogger(ServiceUserImpl.class); - - protected TopiaContext rootContext; - - public ServiceUserImpl() throws SuiviObsmerException { - rootContext = SuiviObsmerContext.getTopiaRootContext(); - } - - @Override - public WaoUser connect(String login, String password) throws SuiviObsmerException { - TopiaContext transaction = null; - WaoUser user = null; - try { - transaction = rootContext.beginTransaction(); - - WaoUserDAO dao = SuiviObsmerModelDAOHelper.getWaoUserDAO(transaction); - - String passwordEncoded = SuiviObsmerContext.encodeString(password); - user = dao.findByProperties(WaoUser.LOGIN, login, WaoUser.PASSWORD, passwordEncoded); - - if (user != null && user.getActive()) { - // load company entity - user.getCompany(); - } else if (user != null && !user.getActive()) { - throw new SuiviObsmerBusinessException(Type.ILLEGAL_CONNECTION, this.getClass(), - "Vous n'avez plus les droits nécessaires pour vous connecter. Veuillez contacter un administrateur."); - } else { - throw new SuiviObsmerBusinessException(Type.BAD_CONNECTION, this.getClass(), - "Identifiant ou mot de passe incorrects, veuillez réessayer."); - } - - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, "Une erreur est survenue lors de la demande de connexion", eee); - } - return user; - } - - @Override - public void forgetPassword(String login) throws SuiviObsmerException { - TopiaContext transaction = null; - try { - if (!login.contains("@")) { - throw new SuiviObsmerBusinessException(Type.SYNTAX, this.getClass(), "Votre identifiant n'est pas un email valide, " + - "veuillez contacter un administrateur pour qu'il puisse changer votre mot de passe."); - } - - transaction = rootContext.beginTransaction(); - - WaoUserDAO dao = SuiviObsmerModelDAOHelper.getWaoUserDAO(transaction); - - WaoUser user = dao.findByLogin(login); - if (user == null) { - throw new SuiviObsmerBusinessException(Type.NOT_EXISTS, this.getClass(), - "L'email '" + login + "' n'est pas référencé dans l'application."); - } - - String password = SuiviObsmerContext.createRandomString(8); - String passwordEncoded = SuiviObsmerContext.encodeString(password); - user.setPassword(passwordEncoded); - - String subject = "[WAO] Mot de passe oublié"; - String msg = "Bonjour,\n\n" + - "\tUn nouveau mot de passe a été généré pour votre identifiant " + login + " :\n" + - "\t\t * mot de passe = " + password + "\n\n" + - "Vous pouvez modifier votre password en accédant à la page de gestion de votre profile utilisateur :\n\n" + - "\t\thttp://" + SuiviObsmerContext.getProperty(SuiviObsmerContext.PROP_SERVER) + "\n\n" + - "Cordialement,\n\n" + - "L'Equipe WAO"; - - SuiviObsmerContext.sendEmail(user.getLogin(), subject, msg); - if (log.isDebugEnabled()) { - log.debug("send email to : " + user.getLogin()); - } - - transaction.commitTransaction(); - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, "Impossible de créer ou de mettre à jour l'utilisateur", eee); - } - } - - @Override - public void createUpdateUser(WaoUser user, boolean generatePassword) throws SuiviObsmerException { - TopiaContext transaction = null; - try { - if (user == null) { - throw new IllegalArgumentException("user parameter can't be null"); - } - - transaction = rootContext.beginTransaction(); - - WaoUserDAO dao = SuiviObsmerModelDAOHelper.getWaoUserDAO(transaction); - - boolean newUser = SuiviObsmerContext.prepareTopiaId(WaoUser.class, user); - - // Check for a new user if login already exists - if (newUser) { - WaoUser existUser = dao.findByLogin(user.getLogin()); - if (existUser != null) { - throw new SuiviObsmerBusinessException(Type.ALREADY_EXISTS, this.getClass(), - "Un utilisateur existe déjà avec ce login " + user.getLogin()); - } - } - - String password = user.getPassword(); - - if (generatePassword) { - password = SuiviObsmerContext.createRandomString(8); - user.setPasswordChanged(true); -// if (log.isDebugEnabled()) { -// log.debug("show generated password : " + password); -// } - } - // For a password set manually by user or generated - if (user.isPasswordChanged()) { - String passwordEncoded = SuiviObsmerContext.encodeString(password); - user.setPassword(passwordEncoded); - } - - dao.update(user); - - // FIXME-JC20100122 Use REGEX instead of @ to test if the login is - // a valid email - if (user.getLogin().contains("@") && user.isPasswordChanged()) { - String subject = "[WAO] "; - String msg = "Bonjour,\n\n"; - if (newUser) { - subject += "Création de votre compte"; - msg += "\tVous avez été inscris sur le site WAO : Web Applicatif Obsmer. Vos identifiants de connexion sont :\n" + - "\t\t * identifiant = " + user.getLogin() + "\n" + - "\t\t * mot de passe = " + password + "\n\n" + - "Vous pouvez modifier votre mot de passe en accédant à la page de gestion de votre profil utilisateur:\n\n" + - "\t\thttp://" + SuiviObsmerContext.getProperty(SuiviObsmerContext.PROP_SERVER) + "\n\n"; - } else if (generatePassword) { - subject += "Modification de votre compte"; - msg += "\tVotre mot de passe de connexion à l'application WAO a été modifié : " + password + "\n\n"; - } - msg += "Cordialement,\n\n" + - "L'Equipe WAO"; - - SuiviObsmerContext.sendEmail(user.getLogin(), subject, msg); -// if (log.isDebugEnabled()) { -// log.debug("send email to : " + user.getLogin()); -// } - } - - transaction.commitTransaction(); - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, "Impossible de créer ou de mettre à jour l'utilisateur", eee); - } - } - - @Override - public void deleteUser(WaoUser user) throws SuiviObsmerException { - TopiaContext transaction = null; - try { - transaction = rootContext.beginTransaction(); - - String userType = user.getAdmin() ? "administrateur" : "observateur"; - String msgBegin = "L'" + userType + " '" + user.getLogin() + "' ne peut pas être supprimé"; - String msgEnd = "Vous pouvez cependant le désactiver pour qu'il ne puisse plus se connecter."; - - if (user.getAdmin()) { - SampleRowLogDAO logDAO = SuiviObsmerModelDAOHelper.getSampleRowLogDAO(transaction); - List<SampleRowLog> results = logDAO.findAllByAdmin(user); - - if (!results.isEmpty()) { - throw new SuiviObsmerBusinessException(Type.ALREADY_EXISTS, this.getClass(), - msgBegin + " car il a participé à la modification du plan d'échantillonnage. " + msgEnd); - } - } else { - - ContactDAO contactDAO = SuiviObsmerModelDAOHelper.getContactDAO(transaction); - List<Contact> results = contactDAO.findAllByObserver(user); - - if (!results.isEmpty()) { - throw new SuiviObsmerBusinessException(Type.ALREADY_EXISTS, this.getClass(), - msgBegin + " car il est lié à plusieurs contacts existants. " + msgEnd); - } - } - - - WaoUserDAO dao = SuiviObsmerModelDAOHelper.getWaoUserDAO(transaction); - - dao.delete(user); - - transaction.commitTransaction(); - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, "Impossible de créer ou de mettre à jour l'utilisateur", eee); - } - } - - @Override - public void createUpdateCompany(Company company) throws SuiviObsmerException { - TopiaContext transaction = null; - try { - if (company == null) { - throw new IllegalArgumentException("company parameter can't be null"); - } - - transaction = rootContext.beginTransaction(); - - CompanyDAO dao = SuiviObsmerModelDAOHelper.getCompanyDAO(transaction); - - SuiviObsmerContext.prepareTopiaId(Company.class, company); - dao.update(company); - - transaction.commitTransaction(); - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, "Impossible de créer ou de mettre à jour la société", eee); - } - } - - @Override - public List<Company> getCompanies(boolean activeOnly) throws SuiviObsmerException { - TopiaContext transaction = null; - List<Company> results = new ArrayList<Company>(); - try { - transaction = rootContext.beginTransaction(); - - CompanyDAO dao = SuiviObsmerModelDAOHelper.getCompanyDAO(transaction); - - if (activeOnly) { - results = dao.findAllByActive(activeOnly); - } else { - results = dao.findAll(); - } - - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, "Impossible de récupérer la liste des sociétés", eee); - } - return results; - } - - @Override - public List<WaoUser> getObservers(boolean activeOnly) throws SuiviObsmerException { - TopiaContext transaction = null; - List<WaoUser> results = new ArrayList<WaoUser>(); - try { - transaction = rootContext.beginTransaction(); - - WaoUserDAO dao = SuiviObsmerModelDAOHelper.getWaoUserDAO(transaction); - TopiaQuery<WaoUser> query = dao.createQuery().add(WaoUser.ADMIN, Boolean.FALSE); - - if (activeOnly) { - query.add(WaoUser.ACTIVE, Boolean.TRUE); - } - - results = query.executeToEntityList(); - - transaction.closeContext(); - } catch (Exception eee) { - SuiviObsmerContext.serviceException(transaction, "Impossible de récupérer la liste des observateurs", eee); - } - return results; - } - - - -} Copied: trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceUserImpl.java (from rev 337, trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/impl/ServiceUserImpl.java) =================================================================== --- trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceUserImpl.java (rev 0) +++ trunk/suiviobsmer-business/src/main/java/fr/ifremer/suiviobsmer/services/ServiceUserImpl.java 2010-02-09 01:30:52 UTC (rev 339) @@ -0,0 +1,329 @@ +/* + * *##% + * 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.services; + +import fr.ifremer.suiviobsmer.SuiviObsmerBusinessException; +import fr.ifremer.suiviobsmer.SuiviObsmerBusinessException.Type; +import fr.ifremer.suiviobsmer.SuiviObsmerException; +import fr.ifremer.suiviobsmer.SuiviObsmerModelDAOHelper; +import fr.ifremer.suiviobsmer.SuiviObsmerContext; +import fr.ifremer.suiviobsmer.entity.Company; +import fr.ifremer.suiviobsmer.entity.CompanyDAO; +import fr.ifremer.suiviobsmer.entity.Contact; +import fr.ifremer.suiviobsmer.entity.ContactDAO; +import fr.ifremer.suiviobsmer.entity.SampleRowLog; +import fr.ifremer.suiviobsmer.entity.SampleRowLogDAO; +import fr.ifremer.suiviobsmer.entity.WaoUser; +import fr.ifremer.suiviobsmer.entity.WaoUserDAO; +import fr.ifremer.suiviobsmer.services.ServiceUser; +import java.util.ArrayList; +import java.util.List; +import org.nuiton.topia.TopiaContext; +import org.nuiton.topia.framework.TopiaQuery; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * ServiceUserImpl + * + * Created: 27 nov. 2009 + * + * @author fdesbois + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ +public class ServiceUserImpl implements ServiceUser { + + private static final Logger log = LoggerFactory.getLogger(ServiceUserImpl.class); + + protected TopiaContext rootContext; + + public ServiceUserImpl() throws SuiviObsmerException { + rootContext = SuiviObsmerContext.getTopiaRootContext(); + } + + @Override + public WaoUser connect(String login, String password) throws SuiviObsmerException { + TopiaContext transaction = null; + WaoUser user = null; + try { + transaction = rootContext.beginTransaction(); + + WaoUserDAO dao = SuiviObsmerModelDAOHelper.getWaoUserDAO(transaction); + + String passwordEncoded = SuiviObsmerContext.encodeString(password); + user = dao.findByProperties(WaoUser.LOGIN, login, WaoUser.PASSWORD, passwordEncoded); + + if (user != null && user.getActive()) { + // load company entity + user.getCompany(); + } else if (user != null && !user.getActive()) { + throw new SuiviObsmerBusinessException(Type.ILLEGAL_CONNECTION, this.getClass(), + "Vous n'avez plus les droits nécessaires pour vous connecter. Veuillez contacter un administrateur."); + } else { + throw new SuiviObsmerBusinessException(Type.BAD_CONNECTION, this.getClass(), + "Identifiant ou mot de passe incorrects, veuillez réessayer."); + } + + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, "Une erreur est survenue lors de la demande de connexion", eee); + } + return user; + } + + @Override + public void forgetPassword(String login) throws SuiviObsmerException { + TopiaContext transaction = null; + try { + if (!login.contains("@")) { + throw new SuiviObsmerBusinessException(Type.SYNTAX, this.getClass(), "Votre identifiant n'est pas un email valide, " + + "veuillez contacter un administrateur pour qu'il puisse changer votre mot de passe."); + } + + transaction = rootContext.beginTransaction(); + + WaoUserDAO dao = SuiviObsmerModelDAOHelper.getWaoUserDAO(transaction); + + WaoUser user = dao.findByLogin(login); + if (user == null) { + throw new SuiviObsmerBusinessException(Type.NOT_EXISTS, this.getClass(), + "L'email '" + login + "' n'est pas référencé dans l'application."); + } + + String password = SuiviObsmerContext.createRandomString(8); + String passwordEncoded = SuiviObsmerContext.encodeString(password); + user.setPassword(passwordEncoded); + + String subject = "[WAO] Mot de passe oublié"; + String msg = "Bonjour,\n\n" + + "\tUn nouveau mot de passe a été généré pour votre identifiant " + login + " :\n" + + "\t\t * mot de passe = " + password + "\n\n" + + "Vous pouvez modifier votre password en accédant à la page de gestion de votre profile utilisateur :\n\n" + + "\t\thttp://" + SuiviObsmerContext.getProperty(SuiviObsmerContext.PROP_SERVER) + "\n\n" + + "Cordialement,\n\n" + + "L'Equipe WAO"; + + SuiviObsmerContext.sendEmail(user.getLogin(), subject, msg); + if (log.isDebugEnabled()) { + log.debug("send email to : " + user.getLogin()); + } + + transaction.commitTransaction(); + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, "Impossible de créer ou de mettre à jour l'utilisateur", eee); + } + } + + @Override + public void createUpdateUser(WaoUser user, boolean generatePassword) throws SuiviObsmerException { + TopiaContext transaction = null; + try { + if (user == null) { + throw new IllegalArgumentException("user parameter can't be null"); + } + + transaction = rootContext.beginTransaction(); + + WaoUserDAO dao = SuiviObsmerModelDAOHelper.getWaoUserDAO(transaction); + + boolean newUser = SuiviObsmerContext.prepareTopiaId(WaoUser.class, user); + + // Check for a new user if login already exists + if (newUser) { + WaoUser existUser = dao.findByLogin(user.getLogin()); + if (existUser != null) { + throw new SuiviObsmerBusinessException(Type.ALREADY_EXISTS, this.getClass(), + "Un utilisateur existe déjà avec ce login " + user.getLogin()); + } + } + + String password = user.getPassword(); + + if (generatePassword) { + password = SuiviObsmerContext.createRandomString(8); + user.setPasswordChanged(true); +// if (log.isDebugEnabled()) { +// log.debug("show generated password : " + password); +// } + } + // For a password set manually by user or generated + if (user.isPasswordChanged()) { + String passwordEncoded = SuiviObsmerContext.encodeString(password); + user.setPassword(passwordEncoded); + } + + dao.update(user); + + // FIXME-JC20100122 Use REGEX instead of @ to test if the login is + // a valid email + if (user.getLogin().contains("@") && user.isPasswordChanged()) { + String subject = "[WAO] "; + String msg = "Bonjour,\n\n"; + if (newUser) { + subject += "Création de votre compte"; + msg += "\tVous avez été inscris sur le site WAO : Web Applicatif Obsmer. Vos identifiants de connexion sont :\n" + + "\t\t * identifiant = " + user.getLogin() + "\n" + + "\t\t * mot de passe = " + password + "\n\n" + + "Vous pouvez modifier votre mot de passe en accédant à la page de gestion de votre profil utilisateur:\n\n" + + "\t\thttp://" + SuiviObsmerContext.getProperty(SuiviObsmerContext.PROP_SERVER) + "\n\n"; + } else { + subject += "Modification de votre compte"; + if (generatePassword) { + msg += "\tVotre mot de passe de connexion à l'application WAO a été modifié : " + password + "\n\n"; + } else { + msg += "\tVotre changement de mot de passe à bien été enregistré.\n" + + "Pour des raisons de sécurité, le nouveau mot de passe n'est pas précisé dans ce message.\n" + + "Vous pouvez faire une nouvelle demande de mot de passe en cas de perte sur la page de connexion ou en " + + "répondant à ce message.\n\n"; + } + } + msg += "Cordialement,\n\n" + + "L'Equipe WAO"; + + SuiviObsmerContext.sendEmail(user.getLogin(), subject, msg); +// if (log.isDebugEnabled()) { +// log.debug("send email to : " + user.getLogin()); +// } + } + + transaction.commitTransaction(); + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, "Impossible de créer ou de mettre à jour l'utilisateur", eee); + } + } + + @Override + public void deleteUser(WaoUser user) throws SuiviObsmerException { + TopiaContext transaction = null; + try { + transaction = rootContext.beginTransaction(); + + String userType = user.getAdmin() ? "administrateur" : "observateur"; + String msgBegin = "L'" + userType + " '" + user.getLogin() + "' ne peut pas être supprimé"; + String msgEnd = "Vous pouvez cependant le désactiver pour qu'il ne puisse plus se connecter."; + + if (user.getAdmin()) { + SampleRowLogDAO logDAO = SuiviObsmerModelDAOHelper.getSampleRowLogDAO(transaction); + List<SampleRowLog> results = logDAO.findAllByAdmin(user); + + if (!results.isEmpty()) { + throw new SuiviObsmerBusinessException(Type.ALREADY_EXISTS, this.getClass(), + msgBegin + " car il a participé à la modification du plan d'échantillonnage. " + msgEnd); + } + } else { + + ContactDAO contactDAO = SuiviObsmerModelDAOHelper.getContactDAO(transaction); + List<Contact> results = contactDAO.findAllByObserver(user); + + if (!results.isEmpty()) { + throw new SuiviObsmerBusinessException(Type.ALREADY_EXISTS, this.getClass(), + msgBegin + " car il est lié à plusieurs contacts existants. " + msgEnd); + } + } + + + WaoUserDAO dao = SuiviObsmerModelDAOHelper.getWaoUserDAO(transaction); + + dao.delete(user); + + transaction.commitTransaction(); + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, "Impossible de créer ou de mettre à jour l'utilisateur", eee); + } + } + + @Override + public void createUpdateCompany(Company company) throws SuiviObsmerException { + TopiaContext transaction = null; + try { + if (company == null) { + throw new IllegalArgumentException("company parameter can't be null"); + } + + transaction = rootContext.beginTransaction(); + + CompanyDAO dao = SuiviObsmerModelDAOHelper.getCompanyDAO(transaction); + + SuiviObsmerContext.prepareTopiaId(Company.class, company); + dao.update(company); + + transaction.commitTransaction(); + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, "Impossible de créer ou de mettre à jour la société", eee); + } + } + + @Override + public List<Company> getCompanies(boolean activeOnly) throws SuiviObsmerException { + TopiaContext transaction = null; + List<Company> results = new ArrayList<Company>(); + try { + transaction = rootContext.beginTransaction(); + + CompanyDAO dao = SuiviObsmerModelDAOHelper.getCompanyDAO(transaction); + + if (activeOnly) { + results = dao.findAllByActive(activeOnly); + } else { + results = dao.findAll(); + } + + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, "Impossible de récupérer la liste des sociétés", eee); + } + return results; + } + + @Override + public List<WaoUser> getObservers(boolean activeOnly) throws SuiviObsmerException { + TopiaContext transaction = null; + List<WaoUser> results = new ArrayList<WaoUser>(); + try { + transaction = rootContext.beginTransaction(); + + WaoUserDAO dao = SuiviObsmerModelDAOHelper.getWaoUserDAO(transaction); + TopiaQuery query = dao.createQuery().add(WaoUser.ADMIN, Boolean.FALSE); + + if (activeOnly) { + query.add(WaoUser.ACTIVE, Boolean.TRUE); + } + + results = dao.findAllByQuery(query); + + transaction.closeContext(); + } catch (Exception eee) { + SuiviObsmerContext.serviceException(transaction, "Impossible de récupérer la liste des observateurs", eee); + } + return results; + } + + + +} Modified: trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/SuiviObsmerGlobalTest.java =================================================================== --- trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/SuiviObsmerGlobalTest.java 2010-02-09 01:17:29 UTC (rev 338) +++ trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/SuiviObsmerGlobalTest.java 2010-02-09 01:30:52 UTC (rev 339) @@ -23,7 +23,7 @@ import fr.ifremer.suiviobsmer.entity.Company; import fr.ifremer.suiviobsmer.entity.WaoUser; -import fr.ifremer.suiviobsmer.impl.ServiceUserImpl; +import fr.ifremer.suiviobsmer.services.ServiceUserImpl; import fr.ifremer.suiviobsmer.services.ServiceUser; import java.util.List; import static org.junit.Assert.*; Modified: trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/SuiviObsmerRunnerTest.java =================================================================== --- trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/SuiviObsmerRunnerTest.java 2010-02-09 01:17:29 UTC (rev 338) +++ trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/SuiviObsmerRunnerTest.java 2010-02-09 01:30:52 UTC (rev 339) @@ -25,16 +25,7 @@ import fr.ifremer.suiviobsmer.entity.CompanyImpl; import fr.ifremer.suiviobsmer.entity.WaoUser; import fr.ifremer.suiviobsmer.entity.WaoUserImpl; -import fr.ifremer.suiviobsmer.impl.ServiceBoatImpl; -import fr.ifremer.suiviobsmer.impl.ServiceContactImpl; -import fr.ifremer.suiviobsmer.impl.ServiceReferentialImpl; -import fr.ifremer.suiviobsmer.impl.ServiceSamplingImpl; -import fr.ifremer.suiviobsmer.impl.ServiceUserImpl; -import fr.ifremer.suiviobsmer.services.ServiceBoat; -import fr.ifremer.suiviobsmer.services.ServiceContact; -import fr.ifremer.suiviobsmer.services.ServiceReferential; -import fr.ifremer.suiviobsmer.services.ServiceSampling; -import fr.ifremer.suiviobsmer.services.ServiceUser; +import fr.ifremer.suiviobsmer.services.*; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; Modified: trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/entity/BoatImplTest.java =================================================================== --- trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/entity/BoatImplTest.java 2010-02-09 01:17:29 UTC (rev 338) +++ trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/entity/BoatImplTest.java 2010-02-09 01:30:52 UTC (rev 339) @@ -26,10 +26,10 @@ import fr.ifremer.suiviobsmer.SuiviObsmerRunner; import fr.ifremer.suiviobsmer.bean.ContactState; import fr.ifremer.suiviobsmer.SuiviObsmerRunnerTest; -import fr.ifremer.suiviobsmer.impl.ServiceBoatImpl; -import fr.ifremer.suiviobsmer.impl.ServiceContactImpl; -import fr.ifremer.suiviobsmer.impl.ServiceSamplingImpl; -import fr.ifremer.suiviobsmer.impl.ServiceUserImpl; +import fr.ifremer.suiviobsmer.services.ServiceBoatImpl; +import fr.ifremer.suiviobsmer.services.ServiceContactImpl; +import fr.ifremer.suiviobsmer.services.ServiceSamplingImpl; +import fr.ifremer.suiviobsmer.services.ServiceUserImpl; import fr.ifremer.suiviobsmer.services.ServiceBoat; import fr.ifremer.suiviobsmer.services.ServiceContact; import fr.ifremer.suiviobsmer.services.ServiceSampling; Modified: trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/entity/BoatInfosImplTest.java =================================================================== --- trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/entity/BoatInfosImplTest.java 2010-02-09 01:17:29 UTC (rev 338) +++ trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/entity/BoatInfosImplTest.java 2010-02-09 01:30:52 UTC (rev 339) @@ -21,26 +21,15 @@ package fr.ifremer.suiviobsmer.entity; -import fr.ifremer.suiviobsmer.SuiviObsmerContext; -import fr.ifremer.suiviobsmer.SuiviObsmerModelDAOHelper; import fr.ifremer.suiviobsmer.SuiviObsmerRunner; -import fr.ifremer.suiviobsmer.bean.ContactState; import fr.ifremer.suiviobsmer.SuiviObsmerRunnerTest; -import fr.ifremer.suiviobsmer.impl.ServiceBoatImpl; -import fr.ifremer.suiviobsmer.impl.ServiceContactImpl; -import fr.ifremer.suiviobsmer.services.ServiceBoat; -import fr.ifremer.suiviobsmer.services.ServiceContact; -import org.nuiton.topia.TopiaContext; -import java.io.InputStream; -import java.util.Date; -import java.util.List; +import fr.ifremer.suiviobsmer.services.ServiceBoatImpl; +import fr.ifremer.suiviobsmer.services.ServiceContactImpl; import org.junit.After; import org.junit.AfterClass; -import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.nuiton.util.DateUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; Modified: trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/entity/SampleRowImplTest.java =================================================================== --- trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/entity/SampleRowImplTest.java 2010-02-09 01:17:29 UTC (rev 338) +++ trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/entity/SampleRowImplTest.java 2010-02-09 01:30:52 UTC (rev 339) @@ -31,14 +31,12 @@ import java.util.GregorianCalendar; import org.junit.After; import org.junit.AfterClass; -import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.nuiton.topia.TopiaContext; import org.nuiton.topia.TopiaException; import org.nuiton.util.DateUtils; -import org.nuiton.util.PeriodDates; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.junit.Assert.*; Property changes on: trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/services ___________________________________________________________________ Added: svn:mergeinfo + Modified: trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/services/ActivityCalendarImportTest.java =================================================================== --- trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/impl/ActivityCalendarImportTest.java 2010-02-04 21:33:50 UTC (rev 325) +++ trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/services/ActivityCalendarImportTest.java 2010-02-09 01:30:52 UTC (rev 339) @@ -19,20 +19,17 @@ * ##%* */ -package fr.ifremer.suiviobsmer.impl; +package fr.ifremer.suiviobsmer.services; import fr.ifremer.suiviobsmer.SuiviObsmerContext; import fr.ifremer.suiviobsmer.SuiviObsmerException; import fr.ifremer.suiviobsmer.SuiviObsmerRunner; import fr.ifremer.suiviobsmer.SuiviObsmerRunnerTest; -import fr.ifremer.suiviobsmer.services.ServiceBoat; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.LineNumberReader; import java.util.zip.GZIPInputStream; import org.junit.After; import org.junit.AfterClass; Modified: trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/services/ServiceBoatImplTest.java =================================================================== --- trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/impl/ServiceBoatImplTest.java 2010-02-04 21:33:50 UTC (rev 325) +++ trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/services/ServiceBoatImplTest.java 2010-02-09 01:30:52 UTC (rev 339) @@ -19,7 +19,7 @@ * ##%* */ -package fr.ifremer.suiviobsmer.impl; +package fr.ifremer.suiviobsmer.services; import fr.ifremer.suiviobsmer.SuiviObsmerException; import fr.ifremer.suiviobsmer.SuiviObsmerModelDAOHelper; @@ -45,10 +45,6 @@ import fr.ifremer.suiviobsmer.entity.SampleRowLogImpl; import fr.ifremer.suiviobsmer.entity.WaoUser; import fr.ifremer.suiviobsmer.entity.WaoUserImpl; -import fr.ifremer.suiviobsmer.services.ServiceContact; -import fr.ifremer.suiviobsmer.services.ServiceReferential; -import fr.ifremer.suiviobsmer.services.ServiceSampling; -import fr.ifremer.suiviobsmer.services.ServiceUser; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; Modified: trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/services/ServiceReferentialImplTest.java =================================================================== --- trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/impl/ServiceReferentialImplTest.java 2010-02-04 21:33:50 UTC (rev 325) +++ trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/services/ServiceReferentialImplTest.java 2010-02-09 01:30:52 UTC (rev 339) @@ -19,7 +19,7 @@ * ##%* */ -package fr.ifremer.suiviobsmer.impl; +package fr.ifremer.suiviobsmer.services; import fr.ifremer.suiviobsmer.SuiviObsmerException; import fr.ifremer.suiviobsmer.SuiviObsmerRunner; Deleted: trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/services/ServiceSamplingImplTest.java =================================================================== --- trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/impl/ServiceSamplingImplTest.java 2010-02-04 21:33:50 UTC (rev 325) +++ trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/services/ServiceSamplingImplTest.java 2010-02-09 01:30:52 UTC (rev 339) @@ -1,584 +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.impl; - -import fr.ifremer.suiviobsmer.SuiviObsmerException; -import fr.ifremer.suiviobsmer.SuiviObsmerModelDAOHelper; -import fr.ifremer.suiviobsmer.SuiviObsmerRunner; -import fr.ifremer.suiviobsmer.SuiviObsmerContext; -import fr.ifremer.suiviobsmer.bean.ImportResults; -import fr.ifremer.suiviobsmer.bean.SamplingFilter; -import fr.ifremer.suiviobsmer.bean.SamplingFilterImpl; -import fr.ifremer.suiviobsmer.SuiviObsmerRunnerTest; -import fr.ifremer.suiviobsmer.bean.FacadeRow; -import fr.ifremer.suiviobsmer.entity.Boat; -import fr.ifremer.suiviobsmer.entity.Company; -import fr.ifremer.suiviobsmer.entity.CompanyDAO; -import fr.ifremer.suiviobsmer.entity.ElligibleBoat; -import fr.ifremer.suiviobsmer.entity.ElligibleBoatDAO; -import fr.ifremer.suiviobsmer.entity.FishingZone; -import fr.ifremer.suiviobsmer.entity.FishingZoneDAO; -import fr.ifremer.suiviobsmer.entity.Profession; -import fr.ifremer.suiviobsmer.entity.ProfessionDAO; -import fr.ifremer.suiviobsmer.entity.ProfessionImpl; -import fr.ifremer.suiviobsmer.entity.SampleMonth; -import fr.ifremer.suiviobsmer.entity.SampleMonthImpl; -import fr.ifremer.suiviobsmer.entity.SampleRow; -import fr.ifremer.suiviobsmer.entity.SampleRowDAO; -import fr.ifremer.suiviobsmer.entity.SampleRowLogImpl; -import fr.ifremer.suiviobsmer.services.ServiceBoat; -import fr.ifremer.suiviobsmer.services.ServiceSampling; -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 org.junit.After; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaException; -import org.nuiton.util.DateUtils; -import org.nuiton.util.PeriodDates; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import static org.junit.Assert.*; - -/** - * ServiceSamplingImplTest - * - * Created: 30 nov. 2009 - * - * @author fdesbois - * @version $Revision$ - * - * Mise a jour: $Date$ - * par : $Author$ - */ -public class ServiceSamplingImplTest { - - private static SuiviObsmerRunner runner; - - private static final Logger log = LoggerFactory.getLogger(ServiceSamplingImplTest.class); - - private ServiceSamplingImpl service; - - public ServiceSamplingImplTest() { - } - - @BeforeClass - public static void setUpClass() throws Exception { - runner = new SuiviObsmerRunnerTest(); - } - - @AfterClass - public static void tearDownClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - runner.start(); - service = new ServiceSamplingImpl(); - } - - @After - public void tearDown() throws Exception { - runner.stop(); - } - - @Test - public void testCreateUpdateSampleRow() throws Exception { - log.info("createUpdateSampleRow"); - - /** PREPARE DATA **/ - TopiaContext transaction = SuiviObsmerContext.getTopiaRootContext().beginTransaction(); - - List<FishingZone> zones = prepareFishingZones(transaction); - - InputStream input = getClass().getResourceAsStream("/import/navires.csv"); - ServiceBoat serviceBoat = new ServiceBoatImpl(); - serviceBoat.importBoatCsv(input); - - transaction.closeContext(); - - // CREATE - Profession profession1 = new ProfessionImpl(); - profession1.setCodeDCF5("OORR-BDP"); - profession1.setMeshSize(">=18"); - profession1.setSize("90-1000"); - profession1.setLibelle("Chalutage de poissons tubes"); - - List<SampleMonth> months = new ArrayList<SampleMonth>(); - for (int i = 0; i < 12; i++) { - SampleMonth month = new SampleMonthImpl(); - Calendar calendar = new GregorianCalendar(2009, i, 1); - month.setPeriodDate(calendar.getTime()); - month.setExpectedTidesValue(3); - months.add(month); - } - for (int i = 0; i < 3; i++) { - SampleMonth month = new SampleMonthImpl(); - Calendar calendar = new GregorianCalendar(2010, i, 1); - month.setPeriodDate(calendar.getTime()); - month.setExpectedTidesValue(4); - months.add(month); - } - - SampleRow row = service.getNewSampleRow(); - row.setCode("2010_03"); - row.setNbObservants(3); - row.setAverageTideTime(2.5); - row.setProgramName("DPMA-2009"); - row.setPeriodBegin(DateUtils.createDate(1, 1, 2009)); - row.setPeriodEnd(DateUtils.createDate(31, 3, 2010)); - row.setProfession(profession1); - row.setSampleMonth(months); - row.setFishingZone(zones); - row.setFishingZonesInfos("port tres loin du champ"); - - /** EXEC CREATE **/ - List<Boat> boats = serviceBoat.getBoatsByImmatriculations("174592 978419 273129"); - service.createUpdateSampleRow(row, boats, new SampleRowLogImpl()); - assertNotNull(row.getTopiaId()); - assertNotNull(row.getProfession().getTopiaId()); - - SampleRow result = service.getSampleRow(row.getTopiaId()); - assertEquals(3, result.getFishingZone().size()); - assertEquals(3, result.getElligibleBoat().size()); - - // TEST FOR DELETE ELLIGIBLE BOAT - boats.remove(2); - service.createUpdateSampleRow(result, boats, new SampleRowLogImpl()); - - result = service.getSampleRow(row.getTopiaId()); - assertEquals(2, result.getElligibleBoat().size()); - - } - - /** - * Test of getSampleRowsOrderedByFishingZone method, of class ServiceSamplingImpl. - */ - @Test - public void testGetSampleRowsOrderedByFishingZone() throws Exception { - log.info("getSampleRowsOrderedByFishingZone"); - - - /** PREPARE DATA **/ - - TopiaContext transaction = SuiviObsmerContext.getTopiaRootContext().beginTransaction(); - - List<FishingZone> zones = prepareFishingZones(transaction); - - //Program program1 = programDAO.create(Program.NAME, "DPMA-2009"); - Date dateBegin1 = DateUtils.createDate(1, 1, 2009); - Date dateEnd1 = DateUtils.createDate(1, 3, 2010); - PeriodDates period1 = new PeriodDates(dateBegin1, dateEnd1); - - //Program program2 = programDAO.create(Program.NAME, "PPDA-2008"); - Date dateBegin2 = DateUtils.createDate(1, 1, 2008); - Date dateEnd2 = DateUtils.createDate(1, 12, 2008); - PeriodDates period2 = new PeriodDates(dateBegin2, dateEnd2); - - SampleRowDAO dao = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); - - SampleRow row1 = dao.create(); - row1.setCode("2010_0001"); - row1.addFishingZone(zones.get(2)); - row1.setProgramName("DPMA-2009"); - row1.setPeriod(period1); - - log.info(row1.getCode() + " :: " + row1.getFacade() + " :: " + row1.getSectors()); - - SampleRow row2 = dao.create(); - row2.setCode("2010_0002"); - row2.addFishingZone(zones.get(0)); - row2.setProgramName("DPMA-2009"); - row2.setPeriod(period1); - - log.info(row2.getCode() + " :: " + row2.getFacade() + " :: " + row2.getSectors()); - - SampleRow row3 = dao.create(); - row3.setCode("2010_0003"); - row3.addFishingZone(zones.get(1)); - row3.addFishingZone(zones.get(2)); - row3.addFishingZone(zones.get(0)); - row3.setProgramName("PPDA-2008"); - row3.setPeriod(period2); - - log.info(row3.getCode() + " :: " + row3.getFacade() + " :: " + row3.getSectors()); - - SampleRow row4 = dao.create(); - row4.setCode("2010_0004"); - row4.addFishingZone(zones.get(0)); // Mer du Nord :: Manche - row4.setProgramName("DPMA-2009"); - row4.setPeriod(period1); - - log.info(row4.getCode() + " :: " + row4.getFacade() + " :: " + row4.getSectors()); - - transaction.commitTransaction(); - - /** EXEC service method **/ - - // FIRST TEST : - // ORDER by FishingZone (facadeName, sectorName, districtCode) - // BIG PERIOD, included program1 and program2 - // NO COMPANY (= null) - Calendar begin = new GregorianCalendar(2000, 0, 1, 0, 0, 0); - Calendar end = new GregorianCalendar(2020, 11, 31, 0, 0, 0); - PeriodDates period = new PeriodDates(begin, end); - // RESULT : [2010_0002, 2010_0004, 2010_0001, 2010_0003] - FacadeRow facade = service.getSampleRowsOrderedByFishingZone(period, null); - List<SampleRow> rows = facade.getValues(); - assertEquals(4, rows.size()); - SampleRow resultRow0 = rows.get(0); - assertEquals("2010_0002", resultRow0.getCode()); - SampleRow resultRow1 = rows.get(1); - assertEquals("2010_0004", resultRow1.getCode()); - -// List<FishingZone> zoneRow1 = resultRow1.getFishingZone(); -// assertEquals(3, zoneRow1.size()); -// FishingZone resultZone0 = zoneRow1.get(0); -// assertEquals("VIIb", resultZone0.getDistrictCode()); -// FishingZone resultZone1 = zoneRow1.get(1); -// assertEquals("VI", resultZone1.getDistrictCode()); -// FishingZone resultZone2 = zoneRow1.get(2); -// assertEquals("V", resultZone2.getDistrictCode()); - - SampleRow resultRow2 = rows.get(2); - assertEquals("2010_0003", resultRow2.getCode()); - SampleRow resultRow3 = rows.get(3); - assertEquals("2010_0001", resultRow3.getCode()); - - // SECOND TEST : - // ORDER by FishingZone (facadeName, sectorName, districtCode) - // BIG PERIOD, not included program2 - // NO COMPANY (= null) - begin = new GregorianCalendar(2009, 0, 1, 0, 0, 0); - end = new GregorianCalendar(2020, 11, 31, 0, 0, 0); - period = new PeriodDates(begin, end); - // RESULT : [2010_0002, 2010_0004, 2010_0001] - facade = service.getSampleRowsOrderedByFishingZone(period, null); - rows = facade.getValues(); - assertEquals(3, rows.size()); - resultRow0 = rows.get(0); - assertEquals("2010_0002", resultRow0.getCode()); - resultRow1 = rows.get(1); - assertEquals("2010_0004", resultRow1.getCode()); - resultRow2 = rows.get(2); - assertEquals("2010_0001", resultRow2.getCode()); - - } - - private List<FishingZone> prepareFishingZones(TopiaContext transaction) throws SuiviObsmerException, TopiaException { - - FishingZoneDAO fishingZoneDAO = SuiviObsmerModelDAOHelper.getFishingZoneDAO(transaction); - - FishingZone fishingZone1 = fishingZoneDAO.create(); - fishingZone1.setFacadeName("Atlantique"); - fishingZone1.setSectorName("Secteur Mer Celtique et Ouest Irlande centré Pays bigouden"); - fishingZone1.setDistrictCode("VIIb"); - - FishingZone fishingZone2 = fishingZoneDAO.create(); - fishingZone2.setFacadeName("Manche"); - fishingZone2.setSectorName("Secteur Cherbourg Honfleur centré sur Port-en-Bessin"); - fishingZone2.setDistrictCode("VI"); - - FishingZone fishingZone3 = fishingZoneDAO.create(); - fishingZone3.setFacadeName("Manche"); - fishingZone3.setSectorName("Secteur du Havre à Dunkerque centré sur Boulogne"); - fishingZone3.setDistrictCode("V"); - - transaction.commitTransaction(); - - return fishingZoneDAO.findAll(); - } - - public void testGetSampleRowsForUser() throws Exception { - log.info("getSampleRowsForUser"); - /** PREPARE DATA **/ - TopiaContext transaction = SuiviObsmerContext.getTopiaRootContext().beginTransaction(); - - FishingZoneDAO zoneDAO = SuiviObsmerModelDAOHelper.getFishingZoneDAO(transaction); - FishingZone zoneIId = zoneDAO.create(FishingZone.DISTRICT_CODE, "IId"); - FishingZone zoneIV = zoneDAO.create(FishingZone.DISTRICT_CODE, "IV"); - FishingZone zoneI = zoneDAO.create(FishingZone.DISTRICT_CODE, "I"); - - CompanyDAO companyDAO = SuiviObsmerModelDAOHelper.getCompanyDAO(transaction); - Company company = companyDAO.create(Company.NAME, "TARTANPION"); - Calendar begin = new GregorianCalendar(2009,8,1); - Calendar end = new GregorianCalendar(2010,11,31); - SampleRowDAO sampleRowDAO = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); - SampleRow row = sampleRowDAO.create( - SampleRow.CODE,"2010_178", - SampleRow.COMPANY,company, - SampleRow.PROGRAM_NAME, "DPMA-2009", - SampleRow.PERIOD_BEGIN, begin.getTime(), - SampleRow.PERIOD_END, end.getTime()); - - - transaction.commitTransaction(); - transaction.closeContext(); - - InputStream input = getClass().getResourceAsStream("/import/echantillonnage.csv"); - service.importSamplingPlanCsv(input); - - /** EXEC METHOD **/ - SamplingFilter filter = new SamplingFilterImpl(); -// User admin = new UserImpl(); -// admin.setAdmin(true); -// filter.setCompany() - filter.setNbMonthFinishedFromToday(0); - List<SampleRow> results = service.getSampleRowsByFilter(filter); - // total in file : 11, 1 refused, 1 finished - assertEquals(9, results.size()); - -// User user = new UserImpl(); -// user.setCompany(company); - filter.setCompany(company); - results = service.getSampleRowsByFilter(filter); - assertEquals(1, results.size()); - } - - /** - * Test of getHistoric method, of class ServiceSamplingImpl. - */ - //@Test - public void testGetHistoric() throws Exception { - System.out.println("getHistoric"); - } - - /** - * Test of getSampleRow method, of class ServiceSamplingImpl. - */ - //@Test - public void testGetSampleRow() throws Exception { - System.out.println("getSampleRow"); - } - - @Test - public void testGetNewProfession() throws Exception { - log.info("getNewProfession"); - - /** PREPARE DATA **/ - - TopiaContext transaction = SuiviObsmerContext.getTopiaRootContext().beginTransaction(); - - ProfessionDAO dao = SuiviObsmerModelDAOHelper.getProfessionDAO(transaction); - - Profession profession = dao.create( - Profession.CODE_DCF5, "OBR", - Profession.LIBELLE, "Fileyage en barre", - Profession.MESH_SIZE, "< 80", - Profession.OTHER, "90mm", - Profession.SPECIES, "barre, lieu noir, saumon des plages"); - - transaction.commitTransaction(); - transaction.closeContext(); - - /** EXEC METHOD **/ - Profession newProfession = service.getNewProfession(profession); - Assert.assertNotSame(profession, newProfession); - Assert.assertEquals("OBR", newProfession.getCodeDCF5()); - Assert.assertEquals("Fileyage en barre", newProfession.getLibelle()); - Assert.assertEquals("< 80", newProfession.getMeshSize()); - Assert.assertEquals("90mm", newProfession.getOther()); - Assert.assertEquals("barre, lieu noir, saumon des plages", newProfession.getSpecies()); - - } - - @Test - public void testDeleteSampleRow() throws Exception { - log.info("deleteSampleRow"); - - /** PREPARE DATA **/ - TopiaContext transaction = SuiviObsmerContext.getTopiaRootContext().beginTransaction(); - - FishingZoneDAO zoneDAO = SuiviObsmerModelDAOHelper.getFishingZoneDAO(transaction); - FishingZone zoneIId = zoneDAO.create(FishingZone.DISTRICT_CODE, "IId"); - FishingZone zoneIV = zoneDAO.create(FishingZone.DISTRICT_CODE, "IV"); - FishingZone zoneI = zoneDAO.create(FishingZone.DISTRICT_CODE, "I"); - - CompanyDAO companyDAO = SuiviObsmerModelDAOHelper.getCompanyDAO(transaction); - companyDAO.create(Company.NAME, "TARTANPION"); - companyDAO.create(Company.NAME, "BIS"); - transaction.commitTransaction(); - - - InputStream input = getClass().getResourceAsStream("/import/echantillonnage.csv"); - service.importSamplingPlanCsv(input); - - SampleRowDAO rowDAO = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); - SampleRow row = rowDAO.findByCode("2010_0001"); - row.getProfession(); - row.getCompany(); - transaction.closeContext(); - - input = getClass().getResourceAsStream("/import/navires.csv"); - ServiceBoat serviceBoat = new ServiceBoatImpl(); - serviceBoat.importBoatCsv(input); - List<Boat> boats = serviceBoat.getBoatsByImmatriculations("174592 978419 273129"); - - service.createUpdateSampleRow(row, boats, new SampleRowLogImpl()); - /** EXEC METHOD **/ - - service.deleteSampleRow(row); - transaction = SuiviObsmerContext.getTopiaRootContext().beginTransaction(); - rowDAO = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); - row = rowDAO.findByCode("2010_0001"); - assertNull(row); - - ElligibleBoatDAO elligibleDAO = SuiviObsmerModelDAOHelper.getElligibleBoatDAO(transaction); - List<ElligibleBoat> elligibles = elligibleDAO.findAll(); - assertEquals(0, elligibles.size()); - transaction.closeContext(); - } - - @Test - public void testImportSamplingPlanCsv() throws SuiviObsmerException, TopiaException { - log.info("importSamplingPlanCsv"); - - /** PREPARE DATA **/ - TopiaContext transaction = SuiviObsmerContext.getTopiaRootContext().beginTransaction(); - - FishingZoneDAO zoneDAO = SuiviObsmerModelDAOHelper.getFishingZoneDAO(transaction); - FishingZone zoneIId = zoneDAO.create(FishingZone.DISTRICT_CODE, "IId"); - FishingZone zoneIV = zoneDAO.create(FishingZone.DISTRICT_CODE, "IV"); - FishingZone zoneI = zoneDAO.create(FishingZone.DISTRICT_CODE, "I"); - - CompanyDAO companyDAO = SuiviObsmerModelDAOHelper.getCompanyDAO(transaction); - companyDAO.create(Company.NAME, "TARTANPION"); - companyDAO.create(Company.NAME, "BIS"); - transaction.commitTransaction(); - transaction.closeContext(); - - /** EXEC METHOD **/ - InputStream input = getClass().getResourceAsStream("/import/echantillonnage.csv"); - ImportResults result = service.importSamplingPlanCsv(input); - - // total imported - assertEquals(10, result.getNbRowsImported()); - // total refused - assertEquals(1, result.getNbRowsRefused()); - - /** CHECK VALUES **/ - transaction = SuiviObsmerContext.getTopiaRootContext().beginTransaction(); - - ProfessionDAO professionDAO = SuiviObsmerModelDAOHelper.getProfessionDAO(transaction); - - List<Profession> professions = professionDAO.findAll(); - assertEquals(9, professions.size()); - - SampleRowDAO rowDAO = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); - - SampleRow row1 = rowDAO.findByCode("2010_0001"); - assertNotNull(row1); - assertEquals(1, row1.getNbObservants()); - assertEquals(1.5, row1.getAverageTideTime(), 0.1); - - assertEquals("MA-2009", row1.getProgramName()); - - Profession profession = row1.getProfession(); - assertNotNull(profession); - assertEquals("DB_MOL", profession.getCodeDCF5()); - - List<SampleMonth> months = row1.getSampleMonth(); - assertEquals(11, months.size()); - - Collection<FishingZone> zones = row1.getFishingZone(); - assertEquals(2, zones.size()); - zones.contains(zoneI); - zones.contains(zoneIId); - - transaction.closeContext(); - } - - @Test - public void testGetPrograms() throws Exception { - /** PREPARE DATA **/ - TopiaContext transaction = SuiviObsmerContext.getTopiaRootContext().beginTransaction(); - - FishingZoneDAO zoneDAO = SuiviObsmerModelDAOHelper.getFishingZoneDAO(transaction); - zoneDAO.create(FishingZone.DISTRICT_CODE, "IId"); - zoneDAO.create(FishingZone.DISTRICT_CODE, "IV"); - zoneDAO.create(FishingZone.DISTRICT_CODE, "I"); - - CompanyDAO companyDAO = SuiviObsmerModelDAOHelper.getCompanyDAO(transaction); - companyDAO.create(Company.NAME, "TARTANPION"); - companyDAO.create(Company.NAME, "BIS"); - transaction.commitTransaction(); - transaction.closeContext(); - - InputStream input = getClass().getResourceAsStream("/import/echantillonnage.csv"); - service.importSamplingPlanCsv(input); - - /** EXEC METHOD **/ - List<String> programs = service.getPrograms(null); - assertEquals(4, programs.size()); - } - - - @Test - public void testGetNewSampleRowCode() throws Exception { - log.info("getNewSampleRowCode"); - - /** PREPARE DATA **/ - TopiaContext transaction = SuiviObsmerContext.getTopiaRootContext().beginTransaction(); - - FishingZoneDAO zoneDAO = SuiviObsmerModelDAOHelper.getFishingZoneDAO(transaction); - FishingZone zoneIId = zoneDAO.create(FishingZone.DISTRICT_CODE, "IId"); - FishingZone zoneIV = zoneDAO.create(FishingZone.DISTRICT_CODE, "IV"); - FishingZone zoneI = zoneDAO.create(FishingZone.DISTRICT_CODE, "I"); - - CompanyDAO companyDAO = SuiviObsmerModelDAOHelper.getCompanyDAO(transaction); - companyDAO.create(Company.NAME, "TARTANPION"); - companyDAO.create(Company.NAME, "BIS"); - transaction.commitTransaction(); - - ServiceSampling serviceSampling = new ServiceSamplingImpl(); - InputStream input = getClass().getResourceAsStream("/import/echantillonnage.csv"); - serviceSampling.importSamplingPlanCsv(input); - - transaction.closeContext(); - - /** EXEC METHOD **/ - - Calendar begin = new GregorianCalendar(2009, 11, 1); - - String result = service.getNewSampleRowCode(begin.getTime()); - Assert.assertEquals("2009_0007", result); - - // Test regex for replacment in importSamplingPlanCsv -// String code = "2010_1"; -// code = code.replaceFirst("_(\\d)$", "_0$1"); -// Assert.assertEquals("2010_01", code); -// -// code = "2010_04"; -// code = code.replaceFirst("_(\\d)$", "_0$1"); -// Assert.assertEquals("2010_04", code); - } - -} Copied: trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/services/ServiceSamplingImplTest.java (from rev 335, trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/impl/ServiceSamplingImplTest.java) =================================================================== --- trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/services/ServiceSamplingImplTest.java (rev 0) +++ trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/services/ServiceSamplingImplTest.java 2010-02-09 01:30:52 UTC (rev 339) @@ -0,0 +1,583 @@ +/* + * *##% + * 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.services; + +import fr.ifremer.suiviobsmer.SuiviObsmerException; +import fr.ifremer.suiviobsmer.SuiviObsmerModelDAOHelper; +import fr.ifremer.suiviobsmer.SuiviObsmerRunner; +import fr.ifremer.suiviobsmer.SuiviObsmerContext; +import fr.ifremer.suiviobsmer.bean.ImportResults; +import fr.ifremer.suiviobsmer.bean.SamplingFilter; +import fr.ifremer.suiviobsmer.bean.SamplingFilterImpl; +import fr.ifremer.suiviobsmer.SuiviObsmerRunnerTest; +import fr.ifremer.suiviobsmer.bean.FacadeRow; +import fr.ifremer.suiviobsmer.entity.Boat; +import fr.ifremer.suiviobsmer.entity.Company; +import fr.ifremer.suiviobsmer.entity.CompanyDAO; +import fr.ifremer.suiviobsmer.entity.ElligibleBoat; +import fr.ifremer.suiviobsmer.entity.ElligibleBoatDAO; +import fr.ifremer.suiviobsmer.entity.FishingZone; +import fr.ifremer.suiviobsmer.entity.FishingZoneDAO; +import fr.ifremer.suiviobsmer.entity.Profession; +import fr.ifremer.suiviobsmer.entity.ProfessionDAO; +import fr.ifremer.suiviobsmer.entity.ProfessionImpl; +import fr.ifremer.suiviobsmer.entity.SampleMonth; +import fr.ifremer.suiviobsmer.entity.SampleMonthImpl; +import fr.ifremer.suiviobsmer.entity.SampleRow; +import fr.ifremer.suiviobsmer.entity.SampleRowDAO; +import fr.ifremer.suiviobsmer.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 org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.nuiton.topia.TopiaContext; +import org.nuiton.topia.TopiaException; +import org.nuiton.util.DateUtils; +import org.nuiton.util.PeriodDates; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import static org.junit.Assert.*; + +/** + * ServiceSamplingImplTest + * + * Created: 30 nov. 2009 + * + * @author fdesbois + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ +public class ServiceSamplingImplTest { + + private static SuiviObsmerRunner runner; + + private static final Logger log = LoggerFactory.getLogger(ServiceSamplingImplTest.class); + + private ServiceSamplingImpl service; + + public ServiceSamplingImplTest() { + } + + @BeforeClass + public static void setUpClass() throws Exception { + runner = new SuiviObsmerRunnerTest(); + } + + @AfterClass + public static void tearDownClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + runner.start(); + service = new ServiceSamplingImpl(); + } + + @After + public void tearDown() throws Exception { + runner.stop(); + } + + @Test + public void testCreateUpdateSampleRow() throws Exception { + log.info("createUpdateSampleRow"); + + /** PREPARE DATA **/ + TopiaContext transaction = SuiviObsmerContext.getTopiaRootContext().beginTransaction(); + + List<FishingZone> zones = prepareFishingZones(transaction); + + InputStream input = getClass().getResourceAsStream("/import/navires.csv"); + ServiceBoat serviceBoat = new ServiceBoatImpl(); + serviceBoat.importBoatCsv(input); + + transaction.closeContext(); + + // CREATE + Profession profession1 = new ProfessionImpl(); + profession1.setCodeDCF5("OORR-BDP"); + profession1.setMeshSize(">=18"); + profession1.setSize("90-1000"); + profession1.setLibelle("Chalutage de poissons tubes"); + + List<SampleMonth> months = new ArrayList<SampleMonth>(); + for (int i = 0; i < 12; i++) { + SampleMonth month = new SampleMonthImpl(); + Calendar calendar = new GregorianCalendar(2009, i, 1); + month.setPeriodDate(calendar.getTime()); + month.setExpectedTidesValue(3); + months.add(month); + } + for (int i = 0; i < 3; i++) { + SampleMonth month = new SampleMonthImpl(); + Calendar calendar = new GregorianCalendar(2010, i, 1); + month.setPeriodDate(calendar.getTime()); + month.setExpectedTidesValue(4); + months.add(month); + } + + SampleRow row = service.getNewSampleRow(); + row.setCode("2010_03"); + row.setNbObservants(3); + row.setAverageTideTime(2.5); + row.setProgramName("DPMA-2009"); + row.setPeriodBegin(DateUtils.createDate(1, 1, 2009)); + row.setPeriodEnd(DateUtils.createDate(31, 3, 2010)); + row.setProfession(profession1); + row.setSampleMonth(months); + row.setFishingZone(zones); + row.setFishingZonesInfos("port tres loin du champ"); + + /** EXEC CREATE **/ + List<Boat> boats = serviceBoat.getBoatsByImmatriculations("174592 978419 273129"); + service.createUpdateSampleRow(row, boats, new SampleRowLogImpl()); + assertNotNull(row.getTopiaId()); + assertNotNull(row.getProfession().getTopiaId()); + + SampleRow result = service.getSampleRow(row.getTopiaId()); + assertEquals(3, result.getFishingZone().size()); + assertEquals(3, result.getElligibleBoat().size()); + + // TEST FOR DELETE ELLIGIBLE BOAT + boats.remove(2); + service.createUpdateSampleRow(result, boats, new SampleRowLogImpl()); + + result = service.getSampleRow(row.getTopiaId()); + assertEquals(2, result.getElligibleBoat().size()); + + } + + /** + * Test of getSampleRowsOrderedByFishingZone method, of class ServiceSamplingImpl. + */ + @Test + public void testGetSampleRowsOrderedByFishingZone() throws Exception { + log.info("getSampleRowsOrderedByFishingZone"); + + + /** PREPARE DATA **/ + + TopiaContext transaction = SuiviObsmerContext.getTopiaRootContext().beginTransaction(); + + List<FishingZone> zones = prepareFishingZones(transaction); + + //Program program1 = programDAO.create(Program.NAME, "DPMA-2009"); + Date dateBegin1 = DateUtils.createDate(1, 1, 2009); + Date dateEnd1 = DateUtils.createDate(1, 3, 2010); + PeriodDates period1 = new PeriodDates(dateBegin1, dateEnd1); + + //Program program2 = programDAO.create(Program.NAME, "PPDA-2008"); + Date dateBegin2 = DateUtils.createDate(1, 1, 2008); + Date dateEnd2 = DateUtils.createDate(1, 12, 2008); + PeriodDates period2 = new PeriodDates(dateBegin2, dateEnd2); + + SampleRowDAO dao = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); + + SampleRow row1 = dao.create(); + row1.setCode("2010_0001"); + row1.addFishingZone(zones.get(2)); + row1.setProgramName("DPMA-2009"); + row1.setPeriod(period1); + + log.info(row1.getCode() + " :: " + row1.getFacade() + " :: " + row1.getSectors()); + + SampleRow row2 = dao.create(); + row2.setCode("2010_0002"); + row2.addFishingZone(zones.get(0)); + row2.setProgramName("DPMA-2009"); + row2.setPeriod(period1); + + log.info(row2.getCode() + " :: " + row2.getFacade() + " :: " + row2.getSectors()); + + SampleRow row3 = dao.create(); + row3.setCode("2010_0003"); + row3.addFishingZone(zones.get(1)); + row3.addFishingZone(zones.get(2)); + row3.addFishingZone(zones.get(0)); + row3.setProgramName("PPDA-2008"); + row3.setPeriod(period2); + + log.info(row3.getCode() + " :: " + row3.getFacade() + " :: " + row3.getSectors()); + + SampleRow row4 = dao.create(); + row4.setCode("2010_0004"); + row4.addFishingZone(zones.get(0)); // Mer du Nord :: Manche + row4.setProgramName("DPMA-2009"); + row4.setPeriod(period1); + + log.info(row4.getCode() + " :: " + row4.getFacade() + " :: " + row4.getSectors()); + + transaction.commitTransaction(); + + /** EXEC service method **/ + + // FIRST TEST : + // ORDER by FishingZone (facadeName, sectorName, districtCode) + // BIG PERIOD, included program1 and program2 + // NO COMPANY (= null) + Calendar begin = new GregorianCalendar(2000, 0, 1, 0, 0, 0); + Calendar end = new GregorianCalendar(2020, 11, 31, 0, 0, 0); + PeriodDates period = new PeriodDates(begin, end); + // RESULT : [2010_0002, 2010_0004, 2010_0001, 2010_0003] + FacadeRow facade = service.getSampleRowsOrderedByFishingZone(period, null); + List<SampleRow> rows = facade.getValues(); + assertEquals(4, rows.size()); + SampleRow resultRow0 = rows.get(0); + assertEquals("2010_0002", resultRow0.getCode()); + SampleRow resultRow1 = rows.get(1); + assertEquals("2010_0004", resultRow1.getCode()); + +// List<FishingZone> zoneRow1 = resultRow1.getFishingZone(); +// assertEquals(3, zoneRow1.size()); +// FishingZone resultZone0 = zoneRow1.get(0); +// assertEquals("VIIb", resultZone0.getDistrictCode()); +// FishingZone resultZone1 = zoneRow1.get(1); +// assertEquals("VI", resultZone1.getDistrictCode()); +// FishingZone resultZone2 = zoneRow1.get(2); +// assertEquals("V", resultZone2.getDistrictCode()); + + SampleRow resultRow2 = rows.get(2); + assertEquals("2010_0003", resultRow2.getCode()); + SampleRow resultRow3 = rows.get(3); + assertEquals("2010_0001", resultRow3.getCode()); + + // SECOND TEST : + // ORDER by FishingZone (facadeName, sectorName, districtCode) + // BIG PERIOD, not included program2 + // NO COMPANY (= null) + begin = new GregorianCalendar(2009, 0, 1, 0, 0, 0); + end = new GregorianCalendar(2020, 11, 31, 0, 0, 0); + period = new PeriodDates(begin, end); + // RESULT : [2010_0002, 2010_0004, 2010_0001] + facade = service.getSampleRowsOrderedByFishingZone(period, null); + rows = facade.getValues(); + assertEquals(3, rows.size()); + resultRow0 = rows.get(0); + assertEquals("2010_0002", resultRow0.getCode()); + resultRow1 = rows.get(1); + assertEquals("2010_0004", resultRow1.getCode()); + resultRow2 = rows.get(2); + assertEquals("2010_0001", resultRow2.getCode()); + + } + + private List<FishingZone> prepareFishingZones(TopiaContext transaction) throws SuiviObsmerException, TopiaException { + + FishingZoneDAO fishingZoneDAO = SuiviObsmerModelDAOHelper.getFishingZoneDAO(transaction); + + FishingZone fishingZone1 = fishingZoneDAO.create(); + fishingZone1.setFacadeName("Atlantique"); + fishingZone1.setSectorName("Secteur Mer Celtique et Ouest Irlande centré Pays bigouden"); + fishingZone1.setDistrictCode("VIIb"); + + FishingZone fishingZone2 = fishingZoneDAO.create(); + fishingZone2.setFacadeName("Manche"); + fishingZone2.setSectorName("Secteur Cherbourg Honfleur centré sur Port-en-Bessin"); + fishingZone2.setDistrictCode("VI"); + + FishingZone fishingZone3 = fishingZoneDAO.create(); + fishingZone3.setFacadeName("Manche"); + fishingZone3.setSectorName("Secteur du Havre à Dunkerque centré sur Boulogne"); + fishingZone3.setDistrictCode("V"); + + transaction.commitTransaction(); + + return fishingZoneDAO.findAll(); + } + + public void testGetSampleRowsForUser() throws Exception { + log.info("getSampleRowsForUser"); + /** PREPARE DATA **/ + TopiaContext transaction = SuiviObsmerContext.getTopiaRootContext().beginTransaction(); + + FishingZoneDAO zoneDAO = SuiviObsmerModelDAOHelper.getFishingZoneDAO(transaction); + FishingZone zoneIId = zoneDAO.create(FishingZone.DISTRICT_CODE, "IId"); + FishingZone zoneIV = zoneDAO.create(FishingZone.DISTRICT_CODE, "IV"); + FishingZone zoneI = zoneDAO.create(FishingZone.DISTRICT_CODE, "I"); + + CompanyDAO companyDAO = SuiviObsmerModelDAOHelper.getCompanyDAO(transaction); + Company company = companyDAO.create(Company.NAME, "TARTANPION"); + Calendar begin = new GregorianCalendar(2009,8,1); + Calendar end = new GregorianCalendar(2010,11,31); + SampleRowDAO sampleRowDAO = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); + SampleRow row = sampleRowDAO.create( + SampleRow.CODE,"2010_178", + SampleRow.COMPANY,company, + SampleRow.PROGRAM_NAME, "DPMA-2009", + SampleRow.PERIOD_BEGIN, begin.getTime(), + SampleRow.PERIOD_END, end.getTime()); + + + transaction.commitTransaction(); + transaction.closeContext(); + + InputStream input = getClass().getResourceAsStream("/import/echantillonnage.csv"); + service.importSamplingPlanCsv(input); + + /** EXEC METHOD **/ + SamplingFilter filter = new SamplingFilterImpl(); +// User admin = new UserImpl(); +// admin.setAdmin(true); +// filter.setCompany() + filter.setNbMonthFinishedFromToday(0); + List<SampleRow> results = service.getSampleRowsByFilter(filter); + // total in file : 11, 1 refused, 1 finished + assertEquals(9, results.size()); + +// User user = new UserImpl(); +// user.setCompany(company); + filter.setCompany(company); + results = service.getSampleRowsByFilter(filter); + assertEquals(1, results.size()); + } + + /** + * Test of getHistoric method, of class ServiceSamplingImpl. + */ + //@Test + public void testGetHistoric() throws Exception { + System.out.println("getHistoric"); + } + + /** + * Test of getSampleRow method, of class ServiceSamplingImpl. + */ + //@Test + public void testGetSampleRow() throws Exception { + System.out.println("getSampleRow"); + } + + @Test + public void testGetNewProfession() throws Exception { + log.info("getNewProfession"); + + /** PREPARE DATA **/ + + TopiaContext transaction = SuiviObsmerContext.getTopiaRootContext().beginTransaction(); + + ProfessionDAO dao = SuiviObsmerModelDAOHelper.getProfessionDAO(transaction); + + Profession profession = dao.create( + Profession.CODE_DCF5, "OBR", + Profession.LIBELLE, "Fileyage en barre", + Profession.MESH_SIZE, "< 80", + Profession.OTHER, "90mm", + Profession.SPECIES, "barre, lieu noir, saumon des plages"); + + transaction.commitTransaction(); + transaction.closeContext(); + + /** EXEC METHOD **/ + Profession newProfession = service.getNewProfession(profession); + Assert.assertNotSame(profession, newProfession); + Assert.assertEquals("OBR", newProfession.getCodeDCF5()); + Assert.assertEquals("Fileyage en barre", newProfession.getLibelle()); + Assert.assertEquals("< 80", newProfession.getMeshSize()); + Assert.assertEquals("90mm", newProfession.getOther()); + Assert.assertEquals("barre, lieu noir, saumon des plages", newProfession.getSpecies()); + + } + + @Test + public void testDeleteSampleRow() throws Exception { + log.info("deleteSampleRow"); + + /** PREPARE DATA **/ + TopiaContext transaction = SuiviObsmerContext.getTopiaRootContext().beginTransaction(); + + FishingZoneDAO zoneDAO = SuiviObsmerModelDAOHelper.getFishingZoneDAO(transaction); + FishingZone zoneIId = zoneDAO.create(FishingZone.DISTRICT_CODE, "IId"); + FishingZone zoneIV = zoneDAO.create(FishingZone.DISTRICT_CODE, "IV"); + FishingZone zoneI = zoneDAO.create(FishingZone.DISTRICT_CODE, "I"); + + CompanyDAO companyDAO = SuiviObsmerModelDAOHelper.getCompanyDAO(transaction); + companyDAO.create(Company.NAME, "TARTANPION"); + companyDAO.create(Company.NAME, "BIS"); + transaction.commitTransaction(); + + + InputStream input = getClass().getResourceAsStream("/import/echantillonnage.csv"); + service.importSamplingPlanCsv(input); + + SampleRowDAO rowDAO = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); + SampleRow row = rowDAO.findByCode("2010_0001"); + row.getProfession(); + row.getCompany(); + transaction.closeContext(); + + input = getClass().getResourceAsStream("/import/navires.csv"); + ServiceBoat serviceBoat = new ServiceBoatImpl(); + serviceBoat.importBoatCsv(input); + List<Boat> boats = serviceBoat.getBoatsByImmatriculations("174592 978419 273129"); + + service.createUpdateSampleRow(row, boats, new SampleRowLogImpl()); + /** EXEC METHOD **/ + + service.deleteSampleRow(row); + transaction = SuiviObsmerContext.getTopiaRootContext().beginTransaction(); + rowDAO = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); + row = rowDAO.findByCode("2010_0001"); + assertNull(row); + + ElligibleBoatDAO elligibleDAO = SuiviObsmerModelDAOHelper.getElligibleBoatDAO(transaction); + List<ElligibleBoat> elligibles = elligibleDAO.findAll(); + assertEquals(0, elligibles.size()); + transaction.closeContext(); + } + + @Test + public void testImportSamplingPlanCsv() throws SuiviObsmerException, TopiaException { + log.info("importSamplingPlanCsv"); + + /** PREPARE DATA **/ + TopiaContext transaction = SuiviObsmerContext.getTopiaRootContext().beginTransaction(); + + FishingZoneDAO zoneDAO = SuiviObsmerModelDAOHelper.getFishingZoneDAO(transaction); + FishingZone zoneIId = zoneDAO.create(FishingZone.DISTRICT_CODE, "IId"); + FishingZone zoneIV = zoneDAO.create(FishingZone.DISTRICT_CODE, "IV"); + FishingZone zoneI = zoneDAO.create(FishingZone.DISTRICT_CODE, "I"); + + CompanyDAO companyDAO = SuiviObsmerModelDAOHelper.getCompanyDAO(transaction); + companyDAO.create(Company.NAME, "TARTANPION"); + companyDAO.create(Company.NAME, "BIS"); + transaction.commitTransaction(); + transaction.closeContext(); + + /** EXEC METHOD **/ + InputStream input = getClass().getResourceAsStream("/import/echantillonnage.csv"); + ImportResults result = service.importSamplingPlanCsv(input); + + // total imported + assertEquals(10, result.getNbRowsImported()); + // total refused + assertEquals(1, result.getNbRowsRefused()); + + /** CHECK VALUES **/ + transaction = SuiviObsmerContext.getTopiaRootContext().beginTransaction(); + + ProfessionDAO professionDAO = SuiviObsmerModelDAOHelper.getProfessionDAO(transaction); + + List<Profession> professions = professionDAO.findAll(); + assertEquals(9, professions.size()); + + SampleRowDAO rowDAO = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); + + SampleRow row1 = rowDAO.findByCode("2010_0001"); + assertNotNull(row1); + assertEquals(1, row1.getNbObservants()); + assertEquals(1.5, row1.getAverageTideTime(), 0.1); + assertEquals("Un petit commentaire", row1.getComment()); + + assertEquals("MA-2009", row1.getProgramName()); + + Profession profession = row1.getProfession(); + assertNotNull(profession); + assertEquals("DB_MOL", profession.getCodeDCF5()); + + List<SampleMonth> months = row1.getSampleMonth(); + assertEquals(11, months.size()); + + Collection<FishingZone> zones = row1.getFishingZone(); + assertEquals(2, zones.size()); + zones.contains(zoneI); + zones.contains(zoneIId); + + transaction.closeContext(); + } + + @Test + public void testGetPrograms() throws Exception { + /** PREPARE DATA **/ + TopiaContext transaction = SuiviObsmerContext.getTopiaRootContext().beginTransaction(); + + FishingZoneDAO zoneDAO = SuiviObsmerModelDAOHelper.getFishingZoneDAO(transaction); + zoneDAO.create(FishingZone.DISTRICT_CODE, "IId"); + zoneDAO.create(FishingZone.DISTRICT_CODE, "IV"); + zoneDAO.create(FishingZone.DISTRICT_CODE, "I"); + + CompanyDAO companyDAO = SuiviObsmerModelDAOHelper.getCompanyDAO(transaction); + companyDAO.create(Company.NAME, "TARTANPION"); + companyDAO.create(Company.NAME, "BIS"); + transaction.commitTransaction(); + transaction.closeContext(); + + InputStream input = getClass().getResourceAsStream("/import/echantillonnage.csv"); + service.importSamplingPlanCsv(input); + + /** EXEC METHOD **/ + List<String> programs = service.getPrograms(null); + assertEquals(4, programs.size()); + } + + + @Test + public void testGetNewSampleRowCode() throws Exception { + log.info("getNewSampleRowCode"); + + /** PREPARE DATA **/ + TopiaContext transaction = SuiviObsmerContext.getTopiaRootContext().beginTransaction(); + + FishingZoneDAO zoneDAO = SuiviObsmerModelDAOHelper.getFishingZoneDAO(transaction); + FishingZone zoneIId = zoneDAO.create(FishingZone.DISTRICT_CODE, "IId"); + FishingZone zoneIV = zoneDAO.create(FishingZone.DISTRICT_CODE, "IV"); + FishingZone zoneI = zoneDAO.create(FishingZone.DISTRICT_CODE, "I"); + + CompanyDAO companyDAO = SuiviObsmerModelDAOHelper.getCompanyDAO(transaction); + companyDAO.create(Company.NAME, "TARTANPION"); + companyDAO.create(Company.NAME, "BIS"); + transaction.commitTransaction(); + + ServiceSampling serviceSampling = new ServiceSamplingImpl(); + InputStream input = getClass().getResourceAsStream("/import/echantillonnage.csv"); + serviceSampling.importSamplingPlanCsv(input); + + transaction.closeContext(); + + /** EXEC METHOD **/ + + Calendar begin = new GregorianCalendar(2009, 11, 1); + + String result = service.getNewSampleRowCode(begin.getTime()); + Assert.assertEquals("2009_0007", result); + + // Test regex for replacment in importSamplingPlanCsv +// String code = "2010_1"; +// code = code.replaceFirst("_(\\d)$", "_0$1"); +// Assert.assertEquals("2010_01", code); +// +// code = "2010_04"; +// code = code.replaceFirst("_(\\d)$", "_0$1"); +// Assert.assertEquals("2010_04", code); + } + +} Deleted: trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/services/ServiceSynthesisImplTest.java =================================================================== --- trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/impl/ServiceSynthesisImplTest.java 2010-02-04 21:33:50 UTC (rev 325) +++ trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/services/ServiceSynthesisImplTest.java 2010-02-09 01:30:52 UTC (rev 339) @@ -1,276 +0,0 @@ - -package fr.ifremer.suiviobsmer.impl; - -import fr.ifremer.suiviobsmer.SuiviObsmerContext; -import fr.ifremer.suiviobsmer.SuiviObsmerModelDAOHelper; -import fr.ifremer.suiviobsmer.SuiviObsmerRunner; -import fr.ifremer.suiviobsmer.SuiviObsmerRunnerTest; -import fr.ifremer.suiviobsmer.bean.BoardingResult; -import fr.ifremer.suiviobsmer.bean.ContactState; -import fr.ifremer.suiviobsmer.entity.Boat; -import fr.ifremer.suiviobsmer.entity.Company; -import fr.ifremer.suiviobsmer.entity.CompanyDAO; -import fr.ifremer.suiviobsmer.entity.Contact; -import fr.ifremer.suiviobsmer.entity.ContactImpl; -import fr.ifremer.suiviobsmer.entity.SampleRow; -import fr.ifremer.suiviobsmer.entity.SampleRowDAO; -import fr.ifremer.suiviobsmer.entity.WaoUser; -import fr.ifremer.suiviobsmer.entity.WaoUserDAO; -import fr.ifremer.suiviobsmer.services.ServiceBoat; -import fr.ifremer.suiviobsmer.services.ServiceContact; -import fr.ifremer.suiviobsmer.services.ServiceReferential; -import fr.ifremer.suiviobsmer.services.ServiceSampling; -import java.io.InputStream; -import java.util.Date; -import java.util.List; -import java.util.Map; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.nuiton.topia.TopiaContext; -import org.nuiton.util.DateUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import static org.junit.Assert.*; - -/** - * - * @author fdesbois - */ -public class ServiceSynthesisImplTest { - - private static SuiviObsmerRunner runner; - - private static final Logger log = LoggerFactory.getLogger(ServiceSynthesisImplTest.class); - - private ServiceSynthesisImpl service; - - public ServiceSynthesisImplTest() { - } - - @BeforeClass - public static void setUpClass() throws Exception { - runner = new SuiviObsmerRunnerTest(); - } - - @AfterClass - public static void tearDownClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - runner.start(); - service = new ServiceSynthesisImpl(); - } - - @After - public void tearDown() throws Exception { - runner.stop(); - } - - /** - * Test of getDataSampling method, of class ServiceSynthesisImpl. - */ - //@Test - public void testGetDataSampling() throws Exception { - System.out.println("getDataSampling"); - } - - /** - * Test of getBoardingBoats method, of class ServiceSynthesisImpl. - */ - @Test - public void testGetBoardingBoats() throws Exception { - log.info("getBoardingBoats"); - /** PREPARE DATA **/ - InputStream input = getClass().getResourceAsStream("/import/navires.csv"); - ServiceBoat serviceBoat = new ServiceBoatImpl(); - serviceBoat.importBoatCsv(input); - List<Boat> boats = serviceBoat.getBoatsByImmatriculations("174258"); - Boat boat = boats.get(0); - - List<Boat> boats2 = serviceBoat.getBoatsByImmatriculations("177474"); - Boat boat2 = boats2.get(0); - - TopiaContext transaction = SuiviObsmerContext.getTopiaRootContext().beginTransaction(); - - CompanyDAO companyDAO = SuiviObsmerModelDAOHelper.getCompanyDAO(transaction); - Company company = companyDAO.create(Company.NAME, "TARTANPION"); - Company company2 = companyDAO.create(Company.NAME, "BIS"); - - WaoUserDAO userDAO = SuiviObsmerModelDAOHelper.getWaoUserDAO(transaction); - WaoUser user = userDAO.create(WaoUser.FIRST_NAME,"Jean", WaoUser.LAST_NAME, "Michmuche", - WaoUser.COMPANY, company); - company.addWaoUser(user); - WaoUser user2 = userDAO.create(WaoUser.FIRST_NAME,"Bill", WaoUser.LAST_NAME, "Murray", - WaoUser.COMPANY, company2); - company2.addWaoUser(user2); - - transaction.commitTransaction(); - - input = getClass().getResourceAsStream("/import/zonesPeche.csv"); - ServiceReferential serviceReferential = new ServiceReferentialImpl(); - serviceReferential.importFishingZoneCsv(input); - - input = getClass().getResourceAsStream("/import/echantillonnage.csv"); - ServiceSampling serviceSampling = new ServiceSamplingImpl(); - serviceSampling.importSamplingPlanCsv(input); - - SampleRowDAO rowDAO = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); - SampleRow row = rowDAO.findByCode("2010_0001"); - - transaction.closeContext(); - - - ServiceContact serviceContact = new ServiceContactImpl(); - // First contact : OK - Contact contact1 = new ContactImpl(); - contact1.setBoat(boat); - contact1.setObserver(user); - contact1.setSampleRow(row); - contact1.setState(ContactState.BOARDING_DONE.toString()); - Date begin = DateUtils.createDate(3, 3, 2009); - contact1.setTideBeginDate(begin); - contact1.setValidationCompany(Boolean.TRUE); - serviceContact.saveContact(contact1, false); - - Contact contact2 = new ContactImpl(); - contact2.setBoat(boat); - contact2.setObserver(user); - contact2.setSampleRow(row); - contact2.setState(ContactState.BOARDING_DONE.toString()); - begin = DateUtils.createDate(3, 3, 2009); - contact2.setTideBeginDate(begin); - contact2.setValidationCompany(Boolean.TRUE); - serviceContact.saveContact(contact2, false); - - Contact contact3 = new ContactImpl(); - contact3.setBoat(boat2); - contact3.setObserver(user); - contact3.setSampleRow(row); - contact3.setState(ContactState.BOARDING_DONE.toString()); - begin = DateUtils.createDate(3, 3, 2009); - contact3.setTideBeginDate(begin); - contact3.setValidationCompany(Boolean.TRUE); - serviceContact.saveContact(contact3, false); - - /** EXEC METHOD **/ - BoardingResult result = service.getBoardingBoats(null, null); - // one boat with one boarding (177474) - assertEquals(1, result.getData().get("1").intValue()); - // one boat with two boardings (174258) - assertEquals(1, result.getData().get("2").intValue()); - assertEquals(2, result.getMaxBoardingValue()); - assertEquals(174258, result.getMaxBoardingBoat().getImmatriculation()); - } - - /** - * Test of getBoardingBoats method, of class ServiceSynthesisImpl. - */ - @Test - public void testGetNonComplianceBoardingIndicator() throws Exception { - log.info("getNonComplianceBoardingIndicator"); - /** PREPARE DATA **/ - InputStream input = getClass().getResourceAsStream("/import/navires.csv"); - ServiceBoat serviceBoat = new ServiceBoatImpl(); - serviceBoat.importBoatCsv(input); - List<Boat> boats = serviceBoat.getBoatsByImmatriculations("174258"); - Boat boat = boats.get(0); - - List<Boat> boats2 = serviceBoat.getBoatsByImmatriculations("177474"); - Boat boat2 = boats2.get(0); - - TopiaContext transaction = SuiviObsmerContext.getTopiaRootContext().beginTransaction(); - - CompanyDAO companyDAO = SuiviObsmerModelDAOHelper.getCompanyDAO(transaction); - Company company = companyDAO.create(Company.NAME, "TARTANPION"); - Company company2 = companyDAO.create(Company.NAME, "BIS"); - - WaoUserDAO userDAO = SuiviObsmerModelDAOHelper.getWaoUserDAO(transaction); - WaoUser user = userDAO.create(WaoUser.FIRST_NAME,"Jean", WaoUser.LAST_NAME, "Michmuche", - WaoUser.COMPANY, company); - company.addWaoUser(user); - WaoUser user2 = userDAO.create(WaoUser.FIRST_NAME,"Bill", WaoUser.LAST_NAME, "Murray", - WaoUser.COMPANY, company2); - company2.addWaoUser(user2); - - transaction.commitTransaction(); - - input = getClass().getResourceAsStream("/import/zonesPeche.csv"); - ServiceReferential serviceReferential = new ServiceReferentialImpl(); - serviceReferential.importFishingZoneCsv(input); - - input = getClass().getResourceAsStream("/import/echantillonnage.csv"); - ServiceSampling serviceSampling = new ServiceSamplingImpl(); - serviceSampling.importSamplingPlanCsv(input); - - SampleRowDAO rowDAO = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); - SampleRow row = rowDAO.findByCode("2010_0001"); - SampleRow row2 = rowDAO.findByCode("2009_0006"); - - transaction.closeContext(); - - - ServiceContact serviceContact = new ServiceContactImpl(); - // First contact : OK - Contact contact1 = new ContactImpl(); - contact1.setBoat(boat); - contact1.setObserver(user); - contact1.setSampleRow(row); - // 1 real observer over 1 - contact1.setNbObservants(1); - contact1.setState(ContactState.BOARDING_DONE.toString()); - Date begin = DateUtils.createDate(3, 3, 2009); - contact1.setTideBeginDate(begin); - contact1.setValidationCompany(Boolean.TRUE); - serviceContact.saveContact(contact1, false); - - Contact contact2 = new ContactImpl(); - contact2.setBoat(boat); - contact2.setObserver(user); - contact2.setSampleRow(row); - // 2 real observer over 1 - contact2.setNbObservants(2); - contact2.setState(ContactState.BOARDING_DONE.toString()); - begin = DateUtils.createDate(3, 3, 2009); - contact2.setTideBeginDate(begin); - contact2.setValidationCompany(Boolean.TRUE); - serviceContact.saveContact(contact2, false); - - Contact contact3 = new ContactImpl(); - contact3.setBoat(boat2); - contact3.setObserver(user2); - contact3.setSampleRow(row2); - // 1 real observer over 2 - contact3.setNbObservants(1); - contact3.setState(ContactState.BOARDING_DONE.toString()); - begin = DateUtils.createDate(3, 3, 2009); - contact3.setTideBeginDate(begin); - contact3.setValidationCompany(Boolean.TRUE); - serviceContact.saveContact(contact3, false); - - /** EXEC METHOD **/ - - // result for company TARTANPION - Map<Company, Double> results = - service.getNonComplianceBoardingIndicator(company); - - assertEquals(1, results.size()); - - // 0% of non compliance - Double value = results.get(company); - assertEquals(0., value, 0); - - // result for company BIS using admin mode (no company filtered) - results = service.getNonComplianceBoardingIndicator(null); - - assertEquals(2, results.size()); - - // 100% of non compliance - value = results.get(company2); - assertEquals(1., value, 0); - } - -} \ No newline at end of file Copied: trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/services/ServiceSynthesisImplTest.java (from rev 331, trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/impl/ServiceSynthesisImplTest.java) =================================================================== --- trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/services/ServiceSynthesisImplTest.java (rev 0) +++ trunk/suiviobsmer-business/src/test/java/fr/ifremer/suiviobsmer/services/ServiceSynthesisImplTest.java 2010-02-09 01:30:52 UTC (rev 339) @@ -0,0 +1,419 @@ + +package fr.ifremer.suiviobsmer.services; + +import fr.ifremer.suiviobsmer.SuiviObsmerContext; +import fr.ifremer.suiviobsmer.SuiviObsmerModelDAOHelper; +import fr.ifremer.suiviobsmer.SuiviObsmerRunner; +import fr.ifremer.suiviobsmer.SuiviObsmerRunnerTest; +import fr.ifremer.suiviobsmer.bean.BoardingResult; +import fr.ifremer.suiviobsmer.bean.ContactState; +import fr.ifremer.suiviobsmer.bean.ContactStateStatistics; +import fr.ifremer.suiviobsmer.entity.Boat; +import fr.ifremer.suiviobsmer.entity.Company; +import fr.ifremer.suiviobsmer.entity.CompanyDAO; +import fr.ifremer.suiviobsmer.entity.Contact; +import fr.ifremer.suiviobsmer.entity.ContactImpl; +import fr.ifremer.suiviobsmer.entity.SampleRow; +import fr.ifremer.suiviobsmer.entity.SampleRowDAO; +import fr.ifremer.suiviobsmer.entity.WaoUser; +import fr.ifremer.suiviobsmer.entity.WaoUserDAO; +import java.io.InputStream; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.Map; +import org.apache.commons.collections.CollectionUtils; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.nuiton.topia.TopiaContext; +import org.nuiton.util.DateUtils; +import org.nuiton.util.PeriodDates; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import static org.junit.Assert.*; + +/** + * + * @author fdesbois + */ +public class ServiceSynthesisImplTest { + + private static SuiviObsmerRunner runner; + + private static final Logger log = LoggerFactory.getLogger(ServiceSynthesisImplTest.class); + + private ServiceSynthesisImpl service; + + public ServiceSynthesisImplTest() { + } + + @BeforeClass + public static void setUpClass() throws Exception { + runner = new SuiviObsmerRunnerTest(); + } + + @AfterClass + public static void tearDownClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + runner.start(); + service = new ServiceSynthesisImpl(); + } + + @After + public void tearDown() throws Exception { + runner.stop(); + } + + /** + * Test of getDataSampling method, of class ServiceSynthesisImpl. + */ + //@Test + public void testGetDataSampling() throws Exception { + System.out.println("getDataSampling"); + } + + /** + * Test of getBoardingBoats method, of class ServiceSynthesisImpl. + */ + @Test + public void testGetBoardingBoats() throws Exception { + log.info("getBoardingBoats"); + /** PREPARE DATA **/ + InputStream input = getClass().getResourceAsStream("/import/navires.csv"); + ServiceBoat serviceBoat = new ServiceBoatImpl(); + serviceBoat.importBoatCsv(input); + List<Boat> boats = serviceBoat.getBoatsByImmatriculations("174258"); + Boat boat = boats.get(0); + + List<Boat> boats2 = serviceBoat.getBoatsByImmatriculations("177474"); + Boat boat2 = boats2.get(0); + + TopiaContext transaction = SuiviObsmerContext.getTopiaRootContext().beginTransaction(); + + CompanyDAO companyDAO = SuiviObsmerModelDAOHelper.getCompanyDAO(transaction); + Company company = companyDAO.create(Company.NAME, "TARTANPION"); + Company company2 = companyDAO.create(Company.NAME, "BIS"); + + WaoUserDAO userDAO = SuiviObsmerModelDAOHelper.getWaoUserDAO(transaction); + WaoUser user = userDAO.create(WaoUser.FIRST_NAME,"Jean", WaoUser.LAST_NAME, "Michmuche", + WaoUser.COMPANY, company); + company.addWaoUser(user); + WaoUser user2 = userDAO.create(WaoUser.FIRST_NAME,"Bill", WaoUser.LAST_NAME, "Murray", + WaoUser.COMPANY, company2); + company2.addWaoUser(user2); + + transaction.commitTransaction(); + + input = getClass().getResourceAsStream("/import/zonesPeche.csv"); + ServiceReferential serviceReferential = new ServiceReferentialImpl(); + serviceReferential.importFishingZoneCsv(input); + + input = getClass().getResourceAsStream("/import/echantillonnage.csv"); + ServiceSampling serviceSampling = new ServiceSamplingImpl(); + serviceSampling.importSamplingPlanCsv(input); + + SampleRowDAO rowDAO = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); + SampleRow row = rowDAO.findByCode("2010_0001"); + + transaction.closeContext(); + + + ServiceContact serviceContact = new ServiceContactImpl(); + // First contact : OK + Contact contact1 = new ContactImpl(); + contact1.setBoat(boat); + contact1.setObserver(user); + contact1.setSampleRow(row); + contact1.setState(ContactState.BOARDING_DONE.toString()); + Date begin = DateUtils.createDate(3, 3, 2009); + contact1.setTideBeginDate(begin); + contact1.setValidationCompany(Boolean.TRUE); + serviceContact.saveContact(contact1, false); + + Contact contact2 = new ContactImpl(); + contact2.setBoat(boat); + contact2.setObserver(user); + contact2.setSampleRow(row); + contact2.setState(ContactState.BOARDING_DONE.toString()); + begin = DateUtils.createDate(3, 3, 2009); + contact2.setTideBeginDate(begin); + contact2.setValidationCompany(Boolean.TRUE); + serviceContact.saveContact(contact2, false); + + Contact contact3 = new ContactImpl(); + contact3.setBoat(boat2); + contact3.setObserver(user); + contact3.setSampleRow(row); + contact3.setState(ContactState.BOARDING_DONE.toString()); + begin = DateUtils.createDate(3, 3, 2009); + contact3.setTideBeginDate(begin); + contact3.setValidationCompany(Boolean.TRUE); + serviceContact.saveContact(contact3, false); + + /** EXEC METHOD **/ + BoardingResult result = service.getBoardingBoats(null, null); + // one boat with one boarding (177474) + assertEquals(1, result.getData().get("1").intValue()); + // one boat with two boardings (174258) + assertEquals(1, result.getData().get("2").intValue()); + assertEquals(2, result.getMaxBoardingValue()); + assertEquals(174258, result.getMaxBoardingBoat().getImmatriculation()); + } + + /** + * Test of getBoardingBoats method, of class ServiceSynthesisImpl. + */ + @Test + public void testGetNonComplianceBoardingIndicator() throws Exception { + log.info("getNonComplianceBoardingIndicator"); + /** PREPARE DATA **/ + InputStream input = getClass().getResourceAsStream("/import/navires.csv"); + ServiceBoat serviceBoat = new ServiceBoatImpl(); + serviceBoat.importBoatCsv(input); + List<Boat> boats = serviceBoat.getBoatsByImmatriculations("174258"); + Boat boat = boats.get(0); + + List<Boat> boats2 = serviceBoat.getBoatsByImmatriculations("177474"); + Boat boat2 = boats2.get(0); + + TopiaContext transaction = SuiviObsmerContext.getTopiaRootContext().beginTransaction(); + + CompanyDAO companyDAO = SuiviObsmerModelDAOHelper.getCompanyDAO(transaction); + Company company = companyDAO.create(Company.NAME, "TARTANPION"); + Company company2 = companyDAO.create(Company.NAME, "BIS"); + + WaoUserDAO userDAO = SuiviObsmerModelDAOHelper.getWaoUserDAO(transaction); + WaoUser user = userDAO.create(WaoUser.FIRST_NAME,"Jean", WaoUser.LAST_NAME, "Michmuche", + WaoUser.COMPANY, company); + company.addWaoUser(user); + WaoUser user2 = userDAO.create(WaoUser.FIRST_NAME,"Bill", WaoUser.LAST_NAME, "Murray", + WaoUser.COMPANY, company2); + company2.addWaoUser(user2); + + transaction.commitTransaction(); + + input = getClass().getResourceAsStream("/import/zonesPeche.csv"); + ServiceReferential serviceReferential = new ServiceReferentialImpl(); + serviceReferential.importFishingZoneCsv(input); + + input = getClass().getResourceAsStream("/import/echantillonnage.csv"); + ServiceSampling serviceSampling = new ServiceSamplingImpl(); + serviceSampling.importSamplingPlanCsv(input); + + SampleRowDAO rowDAO = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); + SampleRow row = rowDAO.findByCode("2010_0001"); + SampleRow row2 = rowDAO.findByCode("2009_0006"); + + transaction.closeContext(); + + + ServiceContact serviceContact = new ServiceContactImpl(); + // First contact : OK + Contact contact1 = new ContactImpl(); + contact1.setBoat(boat); + contact1.setObserver(user); + contact1.setSampleRow(row); + // 1 real observer over 1 + contact1.setNbObservants(1); + contact1.setState(ContactState.BOARDING_DONE.toString()); + Date begin = DateUtils.createDate(3, 3, 2009); + contact1.setTideBeginDate(begin); + contact1.setValidationCompany(Boolean.TRUE); + serviceContact.saveContact(contact1, false); + + Contact contact2 = new ContactImpl(); + contact2.setBoat(boat); + contact2.setObserver(user); + contact2.setSampleRow(row); + // 2 real observer over 1 + contact2.setNbObservants(2); + contact2.setState(ContactState.BOARDING_DONE.toString()); + begin = DateUtils.createDate(3, 3, 2009); + contact2.setTideBeginDate(begin); + contact2.setValidationCompany(Boolean.TRUE); + serviceContact.saveContact(contact2, false); + + Contact contact3 = new ContactImpl(); + contact3.setBoat(boat2); + contact3.setObserver(user2); + contact3.setSampleRow(row2); + // 1 real observer over 2 + contact3.setNbObservants(1); + contact3.setState(ContactState.BOARDING_DONE.toString()); + begin = DateUtils.createDate(3, 3, 2009); + contact3.setTideBeginDate(begin); + contact3.setValidationCompany(Boolean.TRUE); + serviceContact.saveContact(contact3, false); + + /** EXEC METHOD **/ + + // result for company TARTANPION + Map<Company, Double> results = + service.getNonComplianceBoardingIndicator(company); + + assertEquals(1, results.size()); + + // 0% of non compliance + Double value = results.get(company); + assertEquals(0., value, 0); + + // result for company BIS using admin mode (no company filtered) + results = service.getNonComplianceBoardingIndicator(null); + + assertEquals(2, results.size()); + + // 100% of non compliance + value = results.get(company2); + assertEquals(1., value, 0); + } + + /** + * Test of getBoardingBoats method, of class ServiceSynthesisImpl. + */ + @Test + public void testGetContactStateStatistics() throws Exception { + log.info("getContactStateStatistics"); + /** PREPARE DATA **/ + InputStream input = getClass().getResourceAsStream("/import/navires.csv"); + ServiceBoat serviceBoat = new ServiceBoatImpl(); + serviceBoat.importBoatCsv(input); + List<Boat> boats = serviceBoat.getBoatsByImmatriculations("174258"); + Boat boat = boats.get(0); + + List<Boat> boats2 = serviceBoat.getBoatsByImmatriculations("177474"); + Boat boat2 = boats2.get(0); + + TopiaContext transaction = SuiviObsmerContext.getTopiaRootContext().beginTransaction(); + + CompanyDAO companyDAO = SuiviObsmerModelDAOHelper.getCompanyDAO(transaction); + Company company = companyDAO.create(Company.NAME, "TARTANPION"); + Company company2 = companyDAO.create(Company.NAME, "BIS"); + + WaoUserDAO userDAO = SuiviObsmerModelDAOHelper.getWaoUserDAO(transaction); + WaoUser user = userDAO.create(WaoUser.FIRST_NAME,"Jean", WaoUser.LAST_NAME, "Michmuche", + WaoUser.COMPANY, company); + company.addWaoUser(user); + WaoUser user2 = userDAO.create(WaoUser.FIRST_NAME,"Bill", WaoUser.LAST_NAME, "Murray", + WaoUser.COMPANY, company2); + company2.addWaoUser(user2); + + transaction.commitTransaction(); + + input = getClass().getResourceAsStream("/import/zonesPeche.csv"); + ServiceReferential serviceReferential = new ServiceReferentialImpl(); + serviceReferential.importFishingZoneCsv(input); + + input = getClass().getResourceAsStream("/import/echantillonnage.csv"); + ServiceSampling serviceSampling = new ServiceSamplingImpl(); + serviceSampling.importSamplingPlanCsv(input); + + SampleRowDAO rowDAO = SuiviObsmerModelDAOHelper.getSampleRowDAO(transaction); + SampleRow row = rowDAO.findByCode("2010_0001"); + + transaction.closeContext(); + + + ServiceContact serviceContact = new ServiceContactImpl(); + + // Contacts for company TARTANPION + Contact contact1 = new ContactImpl(); + contact1.setObserver(user); + contact1.setState(ContactState.BOARDING_DONE.toString()); + Date begin = DateUtils.createDate(3, 3, 2009); + contact1.setTideBeginDate(begin); + serviceContact.saveContact(contact1, false); + + Contact contact2 = new ContactImpl(); + contact2.setObserver(user); + contact2.setState(ContactState.BOARDING_DONE.toString()); + begin = DateUtils.createDate(3, 10, 2009); + contact2.setTideBeginDate(begin); + serviceContact.saveContact(contact2, false); + + Contact contact3 = new ContactImpl(); + contact3.setObserver(user); + contact3.setState(ContactState.BOAT_REFUSED.toString()); + begin = DateUtils.createDate(3, 5, 2009); + contact3.setTopiaCreateDate(begin); + serviceContact.saveContact(contact3, false); + + // Contacts for company BIS + Contact contact4 = new ContactImpl(); + contact4.setObserver(user2); + contact4.setState(ContactState.BOARDING_EXPECTED.toString()); + begin = DateUtils.createDate(3, 5, 2009); + contact4.setTopiaCreateDate(begin); + serviceContact.saveContact(contact4, false); + + Contact contact5 = new ContactImpl(); + contact5.setObserver(user2); + contact5.setState(ContactState.BOAT_UNAVAILABLE.toString()); + begin = DateUtils.createDate(3, 3, 2010); + contact5.setTopiaCreateDate(begin); + serviceContact.saveContact(contact5, false); + + // Contact refused by program, will not be in result + Contact contact6 = new ContactImpl(); + contact6.setObserver(user2); + contact6.setState(ContactState.BOAT_UNAVAILABLE.toString()); + begin = DateUtils.createDate(3, 3, 2010); + contact6.setTopiaCreateDate(begin); + contact6.setValidationProgram(Boolean.FALSE); + serviceContact.saveContact(contact6, false); + + /** EXEC METHOD **/ + + // result for company TARTANPION with no period + Collection<ContactStateStatistics> results = + service.getContactStateStatistics(company, null); + + assertEquals(1, results.size()); + ContactStateStatistics result = (ContactStateStatistics)CollectionUtils.get(results, 0); + assertEquals(3, result.getTotal()); + Map<ContactState, Integer> data = result.getData(); + assertNotNull(data); + + assertEquals(ContactState.values().length, data.size()); + assertEquals(2, data.get(ContactState.BOARDING_DONE).intValue()); + assertEquals(1, data.get(ContactState.BOAT_REFUSED).intValue()); + + // result for company BIS using admin mode + results = service.getContactStateStatistics(null, null); + assertEquals(2, results.size()); + + result = null; + for (ContactStateStatistics stats : results) { + if (stats.getCompany().equals(company2)) { + result = stats; + break; + } + } + + assertEquals(2, result.getTotal()); + data = result.getData(); + assertEquals(1, data.get(ContactState.BOARDING_EXPECTED).intValue()); + assertEquals(1, data.get(ContactState.BOAT_UNAVAILABLE).intValue()); + + // result for period 3/5/2009 to 3/10/2009 for BIS company + begin = DateUtils.createDate(3, 5, 2009); + Date end = DateUtils.createDate(31, 10, 2009); + PeriodDates period = new PeriodDates(begin, end); + + results = service.getContactStateStatistics(company2, period); + assertEquals(1, results.size()); + + result = (ContactStateStatistics)CollectionUtils.get(results, 0); + + assertEquals(1, result.getTotal()); + data = result.getData(); + assertEquals(1, data.get(ContactState.BOARDING_EXPECTED).intValue()); + assertEquals(0, data.get(ContactState.BOAT_UNAVAILABLE).intValue()); + } + +} \ No newline at end of file Modified: trunk/suiviobsmer-ui/src/main/java/fr/ifremer/suiviobsmer/ui/services/AppModule.java =================================================================== --- trunk/suiviobsmer-ui/src/main/java/fr/ifremer/suiviobsmer/ui/services/AppModule.java 2010-02-09 01:17:29 UTC (rev 338) +++ trunk/suiviobsmer-ui/src/main/java/fr/ifremer/suiviobsmer/ui/services/AppModule.java 2010-02-09 01:30:52 UTC (rev 339) @@ -19,11 +19,9 @@ package fr.ifremer.suiviobsmer.ui.services; -import fr.ifremer.suiviobsmer.entity.CompanyImpl; import fr.ifremer.suiviobsmer.entity.WaoUser; import fr.ifremer.suiviobsmer.entity.WaoUserImpl; import fr.ifremer.suiviobsmer.services.*; -import fr.ifremer.suiviobsmer.impl.*; import org.apache.tapestry5.SymbolConstants; import org.apache.tapestry5.ioc.MappedConfiguration;
participants (1)
-
fdesbois@users.labs.libre-entreprise.org